Programme crash

Hello guys.
Could someone please point to me why this programme crash every time I run it? It crashes after reading and displaying the total number of books sold. The programme was to read number of books sold monthly for three years using two dimensional array, I try to figure out what is causing the problem, but I can't. Someone please help.
Thanks
Misbahu

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
     const int years = 3;
const int MnthArrSize = 12;
const char* Months[MnthArrSize] =
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};

int YearsOfBookSells[years][MnthArrSize];
int bookssold;
int totalsum = 0;
for (int i = 0; i < years; i++)
{
    cout << "Books sell for year " << i+1 << endl;
    for (int months = 0; months < MnthArrSize; months++)
    {
        cout << "Enter number of books sold in " << Months[months] << ": ";
        cin >> bookssold;
       YearsOfBookSells[years][months] = bookssold;
       totalsum += bookssold;
    }

}

 cout << "The total number of " << totalsum << " books are sold in 3 years" << endl;
Line 29
 
    YearsOfBookSells[years][months] = bookssold;
should be
 
    YearsOfBookSells[i][months] = bookssold;


The existing code using years as a subscript is causing out-of-bounds array access, since valid subscripts are in the range 0 to years-1.

It might be more consistent and make more sense of instead of
 
const int years = 3;
you might put
 
const int YearArrSize  = 3;

and so on. The choice of consistent and meaningful variable names can help to avoid such accidental errors.

You're being tripped up by your inconsistent variable namings.

MnthArrSize is the number of months.
years is the number of years.

months is the current month.
i is the current year.

Now you should realize why YearsOfBookSells[years][months] is wrong.
Last edited on
I got it. I was looking at it as years is the array counter. I just realized that consistent in naming variables is powerful.

Thanks guys
Topic archived. No new replies allowed.