Beginner question. Please help

What is wrong with this simple program?

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
  #include <iostream>

using namespace std;




int main()
{
int sample[8];

int x=0;



for (x = 0; x < 8; x++)
{
     if (x%2 == 0)

         sample[x] = x;

     else

          sample[x] = x + 100;
}
cout <<sample[x];
		return 0;
}
The error is at the end, when you try to output the array. If you want to print the content of an array you can't do

cout << sample[x];

Instead, you have to scan the array element by element and print each value.
After the for loop ends, x is 8 so,

cout <<sample[x];

will try to output element simple[8] which is not possible since the array 'simple' 's size is 8.

If you would like to print all the elements in the array. As minomis said, you have to loop this array again and print each element.
Topic archived. No new replies allowed.