C++ Dice and Random Numbers

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

Random Numbers and Related Programs

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

Before trying these programs you should have a look at the basics of random numbers to be familiar with some #include libraries.

Q.1 When a dice is rolled, any number from 1 to 6 could appear. Write a program in C++ that returns uniformly distributed random numbers between 1 and 6, thereby simulating the throwing of a six sided dice (The dice is rolled 10 times).

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

Q.2 Two dices are rolled. Write a program in C++ that simulates throwing two dice and returns the sum of their face values as an int.

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

NEXT: Dice Roll, Sum, and Counter