Simple Program Crashes

Can you see what is wrong with this program? 0 causes an exit which is normal. The program also seem to run fine with input less than 7, if I enter 7 or more I get a crash.

As you can see some parts are bold. These are the parts I added that broke the program. It worked fine before I added the bold parts. I tried to modify it so it would run repeatedly until someone enters a 0.

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
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>

using namespace std;

int rand_0toN1(int n);

#define VALUES  5

int hits[VALUES];

int main()
{
    int n;  // Number of trials
    int i;  // loop counter
    int r;  // Hold a random number

    srand(time(NULL));

    cout << "Enter how many trials? (0 to exit): ";
    cin >> n;

    while (n != 0)
    {
        // Initialize array
        for (i = 0; i < n; i++)
            hits[i] = 0;

        for (i = 0; i < n; i++)
        {
            r = rand_0toN1(VALUES);
            hits[r]++;
        }

        for (i = 0; i < VALUES; i++)
        {
            cout << i << ": " << hits[i] << " Accuracy: ";
            double results = hits[i];
            cout << results / (n/VALUES) << endl;
        }

        cout << "Enter how many trials? (0 to exit): ";
        cin >> n;
    }
    return 0;
}

int rand_0toN1(int n)
{
    return rand()%n;
}
hits have 5 elements so if n > 5 you are accessing elements that doesn't exist on line 29.
Silly me :/

Thanks
Topic archived. No new replies allowed.