Display array as histogram

Hi all,

I'm trying to display values of 4 dice rolls as a horizontal histogram, which would look like:

4: ***
5: *****
6: ******

and so on until...

24:****


I've tried inputting the values into an array with

int main()
{
int i;
cout << "Enter attempts";
cin >> i;
counts[i];
int counter = 0;

for (counter = 0; counter <= i; counter++)
{
counts[counter] = Random() + Random() + Random() + Random();
}
}

I'd like to know how to convert the array values into a histogram (if I'm even doing that part right), and I feel like I need a loop but I'm not sure how to implement it. Any help is appreciated.
closed account (D80DSL3A)
A different approach is needed.
You do need an array, but the one you've (tried to) declare isn't right. The number of elements shouldn't equal the number of rolls.
You want an array where you can tally the number of roll outcomes as 4, 5, 6, 7,..., 24
There are 25 possible roll outcomes (ie 4 through 24 inclusive).
Declare:
int counts[25] = {0};// for storing the 25 roll tallies
Here's the tricky part. You use the roll outcome as the index into the array, and increment the count by 1 for that roll result.
Since the lowest value of a roll is 4 and you wish to store the tally for 4 point rolls in the 1st counts element (ie counts[0]), you'll need to subtract an offset for the index value.
Some more detail because I'm sure that last part was a bit confusing!

Declare:
int rollValue;
Then use it in your for loop like so:
1
2
3
4
5
for (counter = 0; counter < i; counter++)// I changed <= to < so the loop goes i times (not i+1)
{
    rollValue = Random() + Random() + Random() + Random();// assuming Random() returns 1-6
    ++counts[rollValue-4];// increment the tally for this roll value
}

The data you need for the histogram is now stored in the counts array.

EDIT: I got the number of cases wrong. 4 trough 24 inclusive is only 21 (not 25) outcomes. Oops! Better too low that too high, I guess.
Last edited on
Thank you! Your answer was really helpful in trying to store the occurrences rather than the roll value, and I got the whole thing working perfectly now. Thanks again!
Topic archived. No new replies allowed.