I have a problem that i'm trying to solve using arrays. The problem is very detailed to where I can only use 1 printf statement and I need to find out how many times each numbers rolled. I'm having trouble at the for statement. Either I'm having a brain fart or i've been looking at this too long but can someone guide me in the right direction. I'm thinking i'm also wrong in using a define constant.
Assignment guidelines:
Write a loop that will count how many times each of the values appears in the array of 1000 die rolls.
Use an array of 6 elements to keep track of the counts, as opposed to 6 individual variables. This is called a frequency array.
Print out how many times each value appears in the array.
1 occurs XXX times
2 occurs XXX times
Hint: If you find yourself repeating the same line of code you need to use a loop. If you declare several variables that are almost the same, maybe you need to use an array. count1, count2, count3, count4, … is wrong. Make an array and use the elements of the array as counters. Output the results using a loop with one printf statement. This gets more important when we are rolling 2 dice.
You need to initialize rollCounts to zeros. THis array will count the number of times each roll appears.
Line 14 needs to be inside your loop. As it is now, you will only roll the dice once. You also need to remove the +1. We're going to use diceRoll[0]-[5]. Adding 1 here will cause us to index out of bounds.
Line 17 should be:
1 2
rollsCounts[diceRoll]++;
You will need a second loop to print out the counts after you've made the 1000 rolls.
1 2
for (i=0; i<6; i++)
printf ("%d occurs %d time\n", i+1, diceRoll[i]); // Adjust i for 1-6
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROLLS 10
int main() {
int rollCounts[6]={0};//You want them all to start count at 0
int diceRoll;
int i;
srand(time(0));
for (i = 0; i < ROLLS; i++) {
diceRoll = rand() % 6 + 1;
rollCounts[diceRoll-1]++;
}
for(i=0;i<6;++i)
printf("The value [%d] was rolled %d times.\n", i+1,rollCounts[i]);
system("pause");
}
The value [1] was rolled 3 times.
The value [2] was rolled 3 times.
The value [3] was rolled 0 times.
The value [4] was rolled 2 times.
The value [5] was rolled 1 times.
The value [6] was rolled 1 times.
Press any key to continue . . .
Analyze and abstract.
Edit: Tip: initializing one value in an array will set the others to 0.
In the above, the first element was set to 0, and the remaining, was defaulted to 0. I've heard that some compilers set array values to 0 by default, but this has never been true for me; however, setting one value to anything, will set the remaining to 0.