Die Roll with Arrays

I'm really not understanding arrays; for my project I had to simulate a die rolling 2,000 times and keep track of how many times each was rolled. How can I fix this? :
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

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>	//include this for rand functions


using namespace std;
int main(){
	const int rolls=2000; //set number of rolls to 2000

	int rolls[6];	//declare array
	rolls[6] = {0};
	
	srand(time(0));
	for(i=0, i<=rolls, i++){
		die = (rand()%6)+1;
		rolls[die] = rolls[die]+1;
	}

	for(die=1; die<7; die ++){
		cout << die << " rolled " << rolls[die] << " times" << endl;
	}



	system("PAUSE");
	return(0);

}


1
2
3
4
for(i=0, i<=rolls, i++){
		die = (rand()%6)+1;
		rolls[die] = rolls[die]+1;
	}


First of all, this for loop is going to execute 2001 times. Also, the value of die will be between 1 and 6 inclusive, but your array indices will be between 0 and 5 inclusive. So when die == 6 and the statement rolls[die] = rolls[die] + 1 executes, the array index will be out of bounds
The second for loop will also cause an array index out of bounds error

Remember if an array size is n, the array indices will range from 0 to n-1. Counting usually starts from 0, not 1.
Last edited on
Topic archived. No new replies allowed.