My crash program at the end

1

I am learning to program C ++ and I have written the following code. Everything runs fine but in the end (when the tenth value is admitted) it stops working. I am using MSVC2015.

Can you help me with this, please?

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {

    int pank[10];

    for (int i = 0; i <= 10; i++) {
        cout << "Cuantos pancakes se comio la persona No." << i << " " << endl;
        cin >> pank[i];
    }

    system("pause");
    return 0;
}
    
asked by Daniel Luna 28.11.2016 в 01:37
source

1 answer

3

That's because the arrays start at position 0. That is, if your array has to have 10 positions, you will have the positions:

0, 1, 2, 3, 4, 5, 6, 7, 8 y 9

Therefore, in your loop you have to go from position 0 to position n-1 (10-1 = 9) . You should change the condition so that:

for (int i = 0; i < 10; i++) {
                 ^^
   cout << "Cuantos pancakes se comio la persona No." << i << " " << endl;
   cin >> pank[i];
}

The error it gives you is because if you put the condition i<=10 you will also try to store a value for the position 10 of the array, which does not exist.

You will try to do this:

cin >> pank[10];

which is wrong since that position does not exist and that is why you have to indicate in the condition that you go up to the number n-1 .

    
answered by 28.11.2016 в 02:03