Part 4 In a main function declare an array of 1000 ints. Fill up the array with
ID: 3823885 • Letter: P
Question
Part 4
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.
(continued…)
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.
Explanation / Answer
#include <iostream>
#include <climits>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
int n = 1000;
int MIN_VALUE = 1;
int MAX_VALUE = 6;
int array[n];
int count[6] = {0,0,0,0,0,0};
for(int i=0;i <n; i++){
array[i] = rand() % (MAX_VALUE) + MIN_VALUE;
}
for(int i=0;i <n; i++){
count[array[i]-1]++;
}
for(int i=0; i<6; i++){
cout<<(i+1)<<" occurs "<<count[i]<<" times"<<endl;
}
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
1 occurs 166 times
2 occurs 170 times
3 occurs 166 times
4 occurs 164 times
5 occurs 169 times
6 occurs 165 times