315,752 views
10 votes
10 votes
In C language

In a main function declare an array of 1000 ints. Fill up the array with random numbers that represent the rolls of a die.
That means values from 1 to 6. 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.
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.

User Yash Pokar
by
2.8k points

1 Answer

5 votes
5 votes

Answer:

The program in C is as follows:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main(){

int dice [1000];

int count [6]={0};

srand(time(0));

for (int i = 0; i < 1000; i++) {

dice[i] = (rand() %(6)) + 1;

count[dice[i]-1]++;

}

for (int i = 0; i < 6; i++) {

printf("%d %s %d %s",(i+1)," occurs ",count[i]," times");

printf("\\");

}

return 0;

}

Step-by-step explanation:

This declares an array that hold each outcome

int dice [1000];

This declares an array that holds the count of each outcome

int count [6]={0};

This lets the program generate different random numbers

srand(time(0));

This loop is repeated 1000 times

for (int i = 0; i < 1000; i++) {

This generates an outcome between 1 and 6 (inclusive)

dice[i] = (rand() %(6)) + 1;

This counts the occurrence of each outcome

count[dice[i]-1]++; }

The following prints the occurrence of each outcome

for (int i = 0; i < 6; i++) {

printf("%d %s %d %s",(i+1)," occurs ",count[i]," times");

printf("\\"); }

User Djizeus
by
2.3k points