C++ Dice Rolls Sum Calculated

C++BasicsInputArithmeticConditionsLoops → Array → Functions → Random Numbers → Dice Roll and Sum → Dice Roll, Sum, and Counter

Random Numbers and Related Programs

  1. Random Numbers Basics
  2. Dice Roll and Random Numbers
  3. Dice Roll, Sum and Counter (You are here)

Before trying these programs you should have a look at the basics of dice rolled and random numbers. And you should also have basic knowledge of Functions.

Consider three C++ programs. The first program is very simple where a function ‘dice’ is made that sums the face values of two dices. Then we called the ‘dice’ function into the main function. In the second program the result is saved in an array. And, in the third program we used that array to count the each possible sum of the two dices (2 to 12).

  1. Write a function ‘dice’ in C++ that simulates throwing of two dices and returns the sum of their face values as an int.
  2. Write a function ‘getResult’ in C++ that takes the result from the function ‘dice’ and save it as an array.
  3. In program 2, you saved the result in an array. Now count how many times each number appeared.

Program 1.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int dice();
int main()
{
srand(time(0));
for (int i =0; i<10; i++)
{
int number = dice();
cout << number << endl;
}
}
int dice()
{
int dice1 = (int)(1+(rand()%6));
int dice2 = (int)(1+(rand()%6));
int diceSum = dice1 + dice2;
return diceSum;
}

Program 2.
This C++ code is just saving the result of the function ‘dice’ in an array.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int dice();
int getResult();
int main()
{
getResult();
}
int getResult()
{
srand(time(0));
int myarray[10];
for (int i =0; i<10; i++)
{
int number = dice();
myarray[i] = number;
cout << number << endl;
}
}
int dice()
{
int dice1 = (int)(1+(rand()%6));
int dice2 = (int)(1+(rand()%6));
int diceSum = dice1 + dice2;
return diceSum;
}

Program 3.
In the above program the sum of the two dices is stored in an array. Now, we use this array to count each number.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int dice();
int getResult();
int main()
{
getResult();
}
int getResult()
{
srand(time(0));
int myarray[10];
for (int i =0; i<10; i++)
{
int number = dice();
myarray[i] = number;
cout << number << endl;
}
int counter = 0;
for (int j = 2; j<13; j++)
{
for (int k = 0; k<10; k++)
{
if (myarray[k]==j)
{
counter++;
}
}
cout << j << " appeared " << counter << " times." << endl;
counter = 0;
}
}
int dice()
{
int dice1 = (int)(1+(rand()%6));
int dice2 = (int)(1+(rand()%6));
int diceSum = dice1 + dice2;
return diceSum;
}

NEXT: Fibonacci sequence using for, while, and do-while loop