Dice rolls: Counting number of rolls that = 6 or 7

The following calculates the number of times the sum of two dice (randomly rolled) equals six or seven.


#include <iostream>
#include <cstdlib>

using namespace std;

int main(){
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
int numSixes = 0; // Tracks number of 6s found
int numSevens = 0; // Tracks number of 7s found
int die1 = 0; // Dice values
int die2 = 0; // Dice values
int rollTotal = 0; // Sum of dice values

cout << "Enter number of rolls: " << endl;
cin >> numRolls;

srand(time(0));

if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
rollTotal = die1 + die2;

// Count number of sixs and sevens
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
else if (rollTotal == 7) {
numSevens = numSevens + 1;
}
cout << endl << "Roll " << (i + 1) << " is "
<< rollTotal << " (" << die1
<< "+" << die2 << ")";
}

// Print statistics on dice rolls
cout << endl << endl;
cout << "Dice roll statistics:" << endl;
cout << "6s: " << numSixes << endl;
cout << "7s: " << numSevens << endl;
}
else {
cout << "Invalid rolls. Try again." << endl;
}

return 0;
}

Create different versions of the program that:

1) Calculates the number of times the sum of the randomly rolled dice equals each possible value from 2 to 12.

2) Repeatedly asks the user for the number of times to roll the dice, quitting only when the user-entered number is less than 1. Hint: Use a while loop that will execute as long as numRolls is greater than 1. Be sure to initialize numRolls correctly.

3) Prints a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like * that number of times, as shown below.

Dice roll histogram:

2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
1
2
3
4
if(rollTotal == 6 || rollTotal == 7)
{
   rollTotalsEqualTo6OrSeven++;
}


Logical or is what you were looking for.
Last edited on
I dunno, I feel like he should keep the separate counters, and that way he can reuse the same code for #3, since it's dice so you're only dealing with whole integers and you can only have one result per dice roll.

But to save @OP some writing, I would personally write your counters as

numSixes += 1; which is syntactically the same as numSixes = numSixes +1; since you already initialized them to 0, and not some random trash integer.
@YFGHNG
I was just giving him an example of logical or. That wasn't a legitimate solution. Although it would suffice for him.
Oh ok ok.
Use an array to store the count of the sum of the rolls:
1
2
3
4
int count[13] = {0};
...

++count[rollTotal];
Topic archived. No new replies allowed.