# C programming questions including the use of arrays

• 12-02-2012
Volodya93
C programming questions including the use of arrays
Hello! Sorry to make the first post as a question, but I am struggling on the following question:

"Write a program to simulate the rolling of a dice. The sum of the two dice is to be calculated. If the dice is rolled 10,000 times, using arrays record the number of times each possible sum occurs."

for the simulating the rolling of dice and it's sum it is very simple, but how would you go about recording (using arrays) the amount of times the same sum occurs (inside the loop) ? :redface:

Thank you all in advance !
• 12-02-2012
Syscal
Just create an array of type int and loop through each of your 10000 cases storing the result in the location that sum has (2 - 12). Pseudo code below:

Code:

```int results[13] = { 0 }, sum = 0, index; //12 is the highest possible sum for(index = 0; index <= 10000; index++){ //for each of the 10,000 iterations         sum = getSum();         results[sum]++; }```
That's how I would go about doing it.

Then to read this info back to stdout, you could just loop through your array like so:

Code:

``` for( index = 0; index <= 12; index++ )         printf("There were %d %d's\n", result[index], index );```
• 12-02-2012
Volodya93
Quote:

Originally Posted by Syscal
Just create an array of type int and loop through each of your 10000 cases storing the result in the location that sum has (2 - 12). Pseudo code below:

Code:

```int results[13] = { 0 }, sum = 0, index; //12 is the highest possible sum for(index = 0; index <= 10000; index++){ //for each of the 10,000 iterations     sum = getSum();     results[sum]++; }```
That's how I would go about doing it.

Then to read this info back to stdout, you could just loop through your array like so:

Code:

``` for( index = 0; index <= 12; index++ )     printf("There were %d %d's\n", result[index], index );```

Thanks! Just to clear up a small misunderstanding from my side - what is getSum() being used for in your code? As well as in your second example - result[]?
• 12-03-2012
c99tutorial
Quote:

Originally Posted by Volodya93
Thanks! Just to clear up a small misunderstanding from my side - what is getSum() being used for in your code? As well as in your second example - result[]?

Your original problem statement said that you need to find the sum of two rolls of a die. It means you should write a function called getSum() which rolls two dice and returns the sum of the two rolls.

results[] is an array which stores the results. For example, if you roll two dice and get the sum 12, then you could keep a tally of this fact by incrementing results[12].