Need help.

Add a for loop that will:
 generate a number of 1's and 2's as requested by the user
 add up the number 1's and 2's generated and store the values in variables numberOfOnes and numberOfTwos

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

int noOfValues = 0; //user is prompted for this
int value = 0; //randomly generated in the for loop. is either 1 or 2
int numberOfOnes = 0; //number of 1s generated
int numberOfTwos = 0; //number or 2s generated


//prime the random number generator so it is ready to go
srand(time(0));


cout << "Enter the number of values to generate : ";
cin >> noOfValues;

//inside a "for" loop randomly generate a 1 or 2 and count the number of 1's and 2's
//the number of times the loop iterates is determined by the number in noOfValues



//display the statistics. no changes needed
cout << fixed << showpoint << setprecision(2);
cout << "Ones generated: " << numberOfOnes << "\tPercent: ";
cout << static_cast<double>(numberOfOnes) / noOfValues * 100 << "%" << endl;

cout << "Twos generated: " << numberOfTwos << "\tPercent: ";
cout << static_cast<double>(numberOfTwos) / noOfValues * 100 << "%" << endl;;

cout << "WOW! " << endl << endl;


}
So whats your question? Please, when looking for help ask a specific question. Also please use code tags next time.

Its simple enough I can see where you're stuck though. I'll give you two ways of doing it.
1. If the rand number is odd its a 1 and even is a 0
1
2
3
4
5
6
7
8
	for (int count = 0; count < noOfValues; count++) {
		if (rand() % 2 == 1) {
			numberOfOnes++;
		}
		else {
			numberOfTwos++;
		}
	}


2. Not necessary here but can be helpful later is
1
2
	
Temp = rand() % ( high - low + 1 ) + low


1
2
3
4
5
6
7
8
9
	for (int count = 0; count < noOfValues; count++) {
		int Temp = rand() % (1 - 0 + 1) + 0;
		if (Temp == 1) {
			numberOfOnes++;
		}
		else {
			numberOfTwos++;
		}
	}

In this example you can see it simplifys to the same thing we had above int Temp = rand() % 2;

Use the first example, its the better option, but the second example can be helpful if you wanted a random number between say 50 and 100. It would look like:
1
2
		//Temp = rand() % (high - low + 1) + low
		Temp = rand() % (100 - 50 + 1) + 50;


Also, don't forget to return 0 at the end of your main function.
1
2
3
4
	//code above
	//dont foget
	return 0;
}
Last edited on
Topic archived. No new replies allowed.