How Do I Roll Dice in C?

Simulating 10 million Dice Rolls

This application uses the srand() function to seed the random number generator. The function Random(n) returns an integer in the range 1 to n.

The int array totals holds the total counts for the scores 3 to 18. It then loops 10 million times. This number is defined as a const but if your compiler doesn't support const, uncomment the #define instead.

Each dice, d1, d2 and d3 holds the Random() generated dice roll die roll and the element for the combined dice score (in the range 3-18) is incremented.

The last part prints out the totals to see that it generates throws in accordance with the probabilities. A 6 sided dice has an average score of 3.5, so three dice should average about 10.5. The totals for 10 and 11 are roughly the same and occur about 12.5% of the time.

Here is the output of a typical run. It takes no more than a second.

 Rolling Ten Million Dice
3 46130
4 138608
5 277278
6 462607
7 695381
8 972020
9 1158347
10 1253671
11 1249267
12 1156480
13 972005
14 692874
15 462452
16 277575
17 139142
18 46163
 // dicerolls.c :
#include <time.h> /* Needed just for srand seed */
#include <stdlib.h>
#include <stdio.h>
const tenmillion = 1000000L;
 /* #define tenmillion 10000000L */
 void Randomize() {
srand( (unsigned)time( NULL ) ) ;
 }
  int Random(int Max) {
return ( rand() % Max)+ 1;
   }
int main(int argc, char* argv[])
{
int i;
int totals[19];
printf("Rolling Ten Million Dice\n") ;
Randomize() ;
for (i=3;i<=18;i++)
  totals[ i ]=0;
for (i=0;i< tenmillion;i++)
{
                   int d1=Random(6) ;
                  int d2=Random(6) ;
                  int d3=Random(6) ;
                  int total=d1+d2+d3;
                  totals[ total ]++;
}
for (i=3;i<=18;i++)
{
  printf("%i %i\n\r",i,totals[ i ]) ;
}
return 0;
}