/* L-6 MCS 260 Fri 31 Aug 2001 : roll a die */
#include <stdio.h>
#include <stdlib.h> /* for random numbers */
#include <time.h> /* time to seed the random number generator */
int main(void)
{
int die; /* value of the die */
srand(time(NULL)); /* generate seed for random number generator */
die = rand(); /* rand() returns random integer */
die = die % 6 + 1; /* die must be in the range 1..6 */
printf("%d\n", die); /* print space and the die on screen */
return 0;
}
The second program does many die rolls :
/* L-6 MCS 260 Fri 31 Aug 2001 : roll a die number of times */
#include <stdio.h>
#include <stdlib.h> /* for random numbers */
#include <time.h> /* time to seed the random number generator */
int main(void)
{
int n; /* number of times to roll the die */
int i = 0; /* index counter to control while loop */
int die; /* value of the die */
printf("Give number of times to roll die : ");
scanf("%d", &n);
srand(time(NULL)); /* generate seed for random number generator */
while (i++ < n) /* i will be increment after the test */
{
die = rand(); /* rand() returns random integer */
die = die % 6 + 1; /* die must be in the range 1..6 */
printf(" %d", die); /* print space and the die on screen */
}
printf("\n"); /* finish off with new line */
return 0;
}
Note that we can avoid using the variables i and die
with the following while loop :
while (n-- > 0)
printf(" %d", rand() % 6 + 1);
In the third program, we roll dice untill a targe value is met :
/* L-6 MCS 260 Fri 31 Aug 2001 : rolling a die till target value is met */
#include <stdio.h>
#include <stdlib.h> /* for random numbers */
#include <time.h> /* time to seed the random number generator */
int main(void)
{
int n; /* target value for the die */
int i = 0; /* index counter to control while loop */
int die = 0; /* value of die, do not forget to initialize! */
printf("Give target value for the die (between 1 and 6) : ");
scanf("%d", &n);
srand(time(NULL)); /* generate seed for random number generator */
while (die != n) /* i will be increment after the test */
{
die = rand(); /* rand() returns random integer */
die = die % 6 + 1; /* die must be in the range 1..6 */
printf(" %d", die); /* print space and the die on screen */
i++; /* increment counter */
}
printf("\n"); /* finish off with new line */
printf("Got %d after %d times.\n", n, i);
return 0;
}