Histogram, almost done!

For this project I basically allowed the user to input how many times they wanted to roll two dice, put the dice rolls into an array, and displayed how many times they rolled a certain value. The code works, but I currently have it showing numerically how many times they rolled a value when instead it is supposed to look something like this:

So if the dice rolls were 7, 4, 9, 3, 5, 6, 4, 7, 10, 11, 2

the histogram would look like

2:X
3:X
4:XX
5:X
6:X
7:XX
8:
9:X
10:X
11:X
12:

I've already looked around quite a bit on different forums but everything I have tried doesn't work quite right. Here's what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>

using namespace std;


void fill(int rollValues[], int size);
void print(int rollValues[], int size);

int main()
{
    srand(time(0));
    int i;
    int x;
    int dice1;
    int dice2;
    int rollValues[13];
    int size;


    cout << "How many times would you like to roll the dice?";
    cin >> size;
    cout <<"Value of Rolls: " << endl;

    for(i = 0; i < 13; i = i + 1)
    {
        rollValues[i] = 0;
    }


    fill(rollValues, size);
    print(rollValues, size);



    return 0;
}

void fill(int rollValues[], int size)
{
    for (int i = 1; i <= size; i++)
    {
        int dice1 = rand() % 6 + 1;
        int dice2 = rand() % 6 + 1;
        rollValues[dice1 + dice2] = rollValues[dice1 + dice2] + 1;

    }
}
void print(int rollValues[], int size)
{
    for (int i=2; i< 10; i++)
    {   int x = rollValues[i];
        cout << endl << " " << i << ": " << rollValues[i];

    }


    for (int i=10; i< 13; i++)
    {
        cout << endl << i << ": ";
        int x = rollValues[i];
        cout << endl << " " << i << ": ";


    }

}
I'm sure there is an easier way, but you should try this:
1
2
3
4
5
6
7
8
9
for (int i=2; i< 10; i++)
    {   int x = rollValues[i];
        cout << endl << " " << i << ": ";
        if (x != 0)
        {
            for (int k = 1; k <= x; k++)
            cout << "X";
        }
    }


I'm not sure why you have two for loops in the print function. Why can't you do int i = 2; i < 13; i++?
Last edited on
Works great, I tried going about it that way earlier but didn't include the if (x != 0) part. Thanks!
Topic archived. No new replies allowed.