In: Computer Science
1. Write a program that plays a simple dice game between the
computer and the user. When the program runs, it asks the user to
input an even number in the interval [2..12], the number of plays.
Display a prompt and read the input into a variable called ‘plays’
using input validation. Your code must ensure that the input always
ends up being valid, i.e. even and in [2..12].
2. A loop then repeats for ‘plays’ iterations. Do the following for
each iteration:
generate a random integer in the range of 1 through 6; this is
the face value of the
computer’s die; output it clearly labeled as ‘computer’s die’
generate another random integer in the range of 1 through 6; this
is the face value of
the user’s die; output it clearly labeled as ‘user’s die’
the die with the highest value wins; display the winner for this
iteration, computer or
user, or state it was a tie
3. As the loop iterates, the program keeps count of the number of
times the computer wins, and of the number of times that the user
wins. After the loop performs all of its iterations, the program
displays the grand winner, the computer or the user, or it states
that the game was tied.
Code (in C):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int plays,i,cw=0,uw=0;
printf("Input an even number in the interval [2..12], the number of
plays: ");
scanf("%d",&plays);
while(!(plays%2==0 && plays>=2
&&plays<=12))
{
printf("Try again!\n");
printf("Input an even number in the interval [2..12], the number of
plays: ");
scanf("%d",&plays);
}
for(i=0;i<plays;i++)
{
int cd = (rand() % (6 - 1 + 1)) + 1;
printf("\nComputer’s Die: %d\n",cd);
int ud = (rand() % (6 - 1 + 1)) + 1;
printf("User’s Die: %d\n",ud);
if(cd>ud)
{
printf("Winner -> Computer\n");
cw++;
}
else if(ud>cd)
{
printf("Winner -> User\n");
uw++;
}
else
printf("Tie\n");
}
if(cw>uw)
printf("\nGrand winner -> Computer\n");
else if(cw<uw)
printf("\nGrand winner -> User\n");
else
printf("\nGrand winner -> Tie\n");
return 0;
}
Please refer to the screenshot of the code to understand the indentation of the code:
Output:
For any doubts or questions comment below.