For loop causing program to crash

Hi, I'm writing code for a number drawing simulation where a pool of 24 balls are drawn 3 times without replacement. Then running this process 1000x times, and tallying the total of the three numbers and recording how often that sum is hit.

Without the 1000x for-loop, the program can run fine. It will produce a sum and then add it to the tally[25] array, but with the for loop the program just crashes.

Where did I mess up??

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
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

    enum{Yellow=1,Blue=2,Red=3,Purple=4,Orange=5,Green=6,Maroon=7,Black=8};
    int tally[25];


    int num, ball, total=0;
    srand(time(NULL));


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


    static int arr[]={1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8};
    vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

    num=rand()%23+1;
    ball=vec[num];
    total+=ball;
    std::swap(vec[num],vec[23]);
    vec.pop_back();

    num=rand()%22+1;
    ball=vec[num];
    total+=ball;
    std::swap(vec[num],vec[22]);
    vec.pop_back();

    num=rand()%21+1;
    ball=vec[num];
    total+=ball;
    std::swap(vec[num],vec[21]);
    vec.pop_back();

    tally[total]++;


}


}
Without the 1000x for-loop, the program can run fine. It will produce a sum and then add it to the tally[25] array, but with the for loop the program just crashes.

Your for loop is infinite.
closed account (E0p9LyTq)
You have at least two problems with your code:

1. your for loop will never end, you are assigning 1000 to i. If you are trying to iterate through your loop 1000 times then i < 1000.

2. total exceeds the boundaries of your tally array after a few iterations through your loop, you keep adding 3 values to it with each loop iteration. That is the actual cause of the program crash.
Topic archived. No new replies allowed.