1. Home
  2. Computing & Technology
  3. C / C++ / C#

How Do I Roll Dice in C?
Simulating 10 million Dice Rolls

By , About.com Guide

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;
}
Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. How To Do Things in C
  6. Learn how to simulate dice rolls in C? >

©2009 About.com, a part of The New York Times Company.

All rights reserved.