Creating program for school assignment that prints random values. I have to create an if statement to find and print how many a value occurs, specially the value 42. I'm not sure how to do this with an if statement.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int count = 1000;
int range = 100;
int value = 42;
int found = 0;
int seed;
cout << "Enter seed: ";
cin >> seed;
void srandom(unsigned int seed);
for (int i=0; i < count; i++)
{
int num = random() % range;
cout << num << " ";
}
cout << "\nthe value " << value
<< " was found " << found << " times\n";
return 0;
}
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int count = 1000;
int range = 100;
int value = 42;
int found = 0;
int seed;
cout << "Enter seed: ";
cin >> seed;
void srandom(unsignedint seed);
char *initstate(unsignedint seed, char *state, size_t n);
char *setstate(char *state);
for (int i=0; i < count; i++)
{
int num = random() % range;
cout << num << " ";
}
cout << "\nthe value " << value
<< " was found " << found << " times\n";
return 0;
}
in order to do this you must store your numbers in an array or vector. Once that is done you create a for loop cycling through it looking for the variable "value" which is 42. So in the for loop place an if statement which says if (array[i] = 42) the body of this if statement would be found++ so it would cycle through the entire array and add 1 to the found variable.
Also it would be better to seed the random number generator with time to create a more random sequence of numbers.
std::generate to populate std::vector<int> with random numbers, in turn generated using <random>
create std::map<int, int> from the vector, key being the number and value being its occurrence frequency
map[42] gives # of occurrences of the no. 42:
My problem is that I am not allowed to alter the code, i.e. store the numbers in an array or vector. My only task is to add an if statement to search for said value and its occurrence.
I have changed the code to seed the random number generator.
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int count = 1000;
int range = 100;
int value = 42;
int found = 0;
int seed;
cout << "Enter seed: ";
cin >> seed;
srand( time(0) );
for (int i=0; i < count; i++)
{
int num = random() % range;
cout << num << " ";
}
cout << "\nthe value " << value
<< " was found " << found << " times\n";
}
return 0;
}
What are you actually interested in? The num.
If you do run your program as is, you should see that the num is a thousand values.
The only thing you need to do is to count every time that the num is something.