Write a program that prints the result of rolling one fair dice.
Hint: use the rand() function with range given in arguments to generate a random integer in the desired range.
Add a loop to print the sum of rolling 10 fair dice.
Add a second loop to repeat this N times, printing the sum after each trial.
Maintain an array count[] so that count[k] stores the number of times the sum is exactly k.
Review your code and eliminate glitches and unnecessary repetitions if any.
#include<time.h>
#include <cmath>
#include <stdio.h>
#include <conio.h>
#define NO_OF_DICE 10
#define ITERATIONS 5
main(void)
{
int Sum=0,n,t=0,k;
int Dice[NO_OF_DICE];
int Sum_Itr[ITERATIONS];
srand(time(0));
printf("\nSolution-1: Rolling a fair dice %d times",NO_OF_DICE);
for(n=0;n<NO_OF_DICE;n++)
{
while(t<1 || t>6) t=rand();
printf("\nDice Roll No. %d = %d",n+1,t);
t=0;
}
printf("\n\nSolution-2: Sum of rolling %d fair dice",NO_OF_DICE);
Sum=0;
for(n=0;n<10;n++)
{
while(t<1 || t>6) t=rand();
printf("\nDice Roll No. %d = %d",n+1,t);
Sum = Sum + t;
t=0;
}
printf("\nTotal Sum = %d",Sum);
printf("\n\nSolution-3: Sum of rolling %d fair dice",NO_OF_DICE);
Sum=0;
for(k=0;k<ITERATIONS;k++)
{
Sum_Itr[k]=0;
for(n=0;n<NO_OF_DICE;n++)
{
while(t<1 || t>6) t=rand();
Sum_Itr[k] = Sum_Itr[k]+t;
t=0;
}
printf("\nSum of %d no. of fair Dices at Iteration No. %d = %d",NO_OF_DICE,k,Sum_Itr[k]);
}
}
Comments
Leave a comment