cout floating in array

hi all
why this program only cout 3.5 for two times not cout this 2.5 3.5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17


#include <iostream>
using namespace std;
main ()
{
    float a[2],z=2.5,y=3.5;
    int i=0,s=2;
    while(s>0){
        a[i]=z;
        i++;
        a[i]=y;
        s--;
    }
    for(int x=0;x<i;x++)
    cout<<a[i];

If you step through this, the code ends up accessing an out of bounds element of the array. I just added in some output statements to show how the numbers change.

I think you mean to use a[x] not a[i] in your for loop, but the while loop still tries to assign a value to an out of bounds element of the array.

beginning of while loop
i = 0
a[0] = 2.5
i = 1
a[1] = 3.5
s = 1
end of while loop
beginning of while loop
i = 1
a[1] = 2.5
i = 2
a[2] = 3.5 // this element does not exist
s = 0
end of while loop
in the for loop
a[2] = 3.5
in the for loop
a[2] = 3.5
Topic archived. No new replies allowed.