Science, Tech, Math › Computer Science How Do I Roll Dice in C, C++, and C#? Share Flipboard Email Print Ian Johnston/EyeEm/Getty Images Computer Science C & C++ Programming PHP Programming Perl Python Java Programming Javascript Programming Delphi Programming Ruby Programming Visual Basic View More By David Bolton David Bolton Computer Science Expert B.A., Computer Science, Queen's University Belfast David Bolton is a software developer who has worked for several major firms, including Morgan Stanley, PwC, BAE Systems, and LCH. Learn about our Editorial Process Updated on July 03, 2019 This application uses the srand() function to seed the random number generator. The function Random(n) returns an integer in the range of 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 461304 1386085 2772786 4626077 6953818 9720209 115834710 125367111 124926712 115648013 97200514 69287415 46245216 27757517 13914218 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;} Cite this Article Format mla apa chicago Your Citation Bolton, David. "How Do I Roll Dice in C, C++, and C#?" ThoughtCo, Aug. 28, 2020, thoughtco.com/how-to-roll-dice-in-c-958661. Bolton, David. (2020, August 28). How Do I Roll Dice in C, C++, and C#? Retrieved from https://www.thoughtco.com/how-to-roll-dice-in-c-958661 Bolton, David. "How Do I Roll Dice in C, C++, and C#?" ThoughtCo. https://www.thoughtco.com/how-to-roll-dice-in-c-958661 (accessed June 8, 2023). copy citation