arrays subtracting numbers

hello people, im trying to write this program that subtracts 2 from each element of the array, the program works fine but it gives me a wrong answer for the last element. plz help
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
#include<iostream>

using namespace std;

int main()
{
    int x=0;
    int myArray[10];

    myArray[0]=30;



    while(x<=10)
    {

        myArray[x+1] = myArray[x]-2;

        cout << myArray[x]<< endl;

        x++;

    }

    return 0;
}


heres the program output, notice the last number.

30
28
26
24
22
20
18
16
14
10
Last edited on
I'm surprised your program doesn't crash.

You're going out of bounds. Since your array is 10 long, the largest index you can use is 9. so cout << myArray[10] <<endl; has a good chance of crashing your program.

Now look at your while loop: For the last iteration x is 10. Let's see what this will look like:
1
2
myArray[11] = myArray[10]-2;
cout << myArray[10] << endl;


To fix, change line 14 to:
while(x < 9)
Last edited on
@Stewbond i tried that before and it only outputs 9 elements, (up to 14)

i also tried while(x<=9) it gives me the same output as before(last element is 10)
Last edited on
Topic archived. No new replies allowed.