In: Computer Science
Write a program in C++ called RollDice.cpp that simulates rolling a pair of dice until the total on the dice comes up to be a given number. Ask the user for the number that you are rolling for.
To have your program roll two dice, use the rand() function this way:
die1 = rand() % 6 + 1; die2 = rand() % 6 + 1;
Your program then computes and prints the number of rolls it takes to get the given number. Valid numbers are 2 through 12.
If the user asked for a 2 your program should output:
It took 20 rolls to get a 2.
(your number of rolls will be different of course)
//program for given question
#include <iostream>
#include <stdlib.h> //for srand(), rand()
#include <time.h> //for time()
using namespace std;
int main()
{
int found=0,num,count=0;
int die1,die2;
srand (time(NULL)); //initializing random seed
cout<<"The number that you are rolling for: "; //taking input
from user
cin>>num;
if(num>12 || num<2){ //checking for valid input
cout<<"INVALID NUMBER!!(Number should be from 2 through
12)";
return 0; //if the input is not valid program will terminate
here.
}
while(found==0){ //if input is valid this loop will execute
count++; //counting number of times this loop runs
die1 = rand() % 6 + 1; //rolling dice 1
die2 = rand() % 6 + 1; //rolling dice 2
if((die1+die2)==num){ //checking if we got the required
number
found=1;
}
}
cout<<"It took "<<count<<" rolls to get a
"<< num; //giving the output
return 0; //end of program
}
NOTE- In this program we are using srand to initializing random seed .If we don't use srand then the program will genrate same sequence of numbers every time it is executed .
for eg: If the user gives input 6 then supoose it take 8 rolls of dice to get 6 .Then if you run the program again with same input 6 then it will again give same output that is 8 rolls of dice .
so to avoid this we use srand() with time() function to generate a randome seed.
CODING AND OUTPUT SCREEN
OUTPUT: