I am making an array of int called score but the for loops is not working properly (i think the loops didn't stop).

I've tried to remove the cin >> score[i] and it turned to normal.

array<int, 9> score;

cout << "Score graphics from 1 to ten\n\n";

for(int i = 0; i <= score.size(); i++){
    cout << "The number of people who get " << i + 1 << " : ";
    cin >> score[i];
}

I expect the output The number of people who get 1 : (input) to The number of people who get 10 : (input)

1 Answers

5
ruohola On Best Solutions

This:

for(int i = 0; i <= score.size(); i++){

Should be:

for(int i = 0; i < score.size(); i++){

Since score.size() will return 9, but the last index of the array is 8.

 

With your original code the last run of the loop will just invoke some undefined behavior when accessing an array with an too large index:

cin >> score[9];  // score array only goes from 0 to 8!!