Can someone help me out here or at least put me on the right path to figuring this question out...
Write a program that declares a 5000 element integer array and then use an appropriate loop to assign 5000 random integers between 0 and 50 to the elements of the array. Use a second loop to then process the array and count
the number of times 42 appears in the array (hint: how many of the array elements are == to 42?) . Output the result.
You're both making a mistake in your array bounds.
An array of 5000 elements has slots from 0 to 4999 (size-1). In jet's case, it will overstep by one since it writes to 0 to 5000 (<5001) and in Aramil's case it will count from 1 from 5000, which is the correct number, but will cause an error abecause your last iteration tries to write at count[5000], which doesn't exist.
Also, please don't post topics in caps. Very annoying.
Also: srand() doesn't belong within the loop. It has to be at the very begining of main(). Otherwise you'd get always the same value since the seed is always the same until the next second (which is a long time for a computer).
#include<iostream>
#include<cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
usingnamespace std;
int main()
{
int myarray[5000];
int k=0,i=0;
for(i=0;i<5000;i++)
{
myarray[i]= rand()%51;
cout<<"# "<<i<<" "<< myarray[i]<<endl;
}
if (myarray[i]==42)
{
for(k=0;k<5000;k++)
{
cout<<"The total number of times 42 was used as a random number is: "<<k<<endl;
}
}
else
{
cout<<"The number 42 was not used!"<<endl;
}
return 0;
}