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 29 30 31 32 33 34 35
|
#include <iostream>
using namespace std;
int main() // <- fixed this for you... main should always return int
{
// These just create some variables.
// The single integer 'i' and an array of 10 integers, 'temp'
int i, temp[10];
// This loop properly fills the array with:
// 0 2 4 6 8 10 12 14 16 18
// as you'd expect
for(i = 0; i < 10; i++)
temp[i] = 2 * i;
// However, at this point... now i==10 because that's where the last for
// loop left it. So this is attempting to print temp[10]... which
// is OUT OF BOUNDS. temp[9] is the highest legal index. [10] is past
// the end of your array. Therefore this is accessing random memory and
// is printing garbage:
cout << temp[i];
// This properly prints each element in the array as you'd expect:
// 0 2 4 6 8 10 12 14 16 18
for (i = 0; i < 10; i++)
cout << temp[i] << " ";
// Print a new line
cout << endl;
// This will print even elements of the array:
// 0 4 8 12 16
for (i = 0; i < 10; i = i + 2)
cout << temp[i] << " ";
}
|
EDIT:
To explain further....
A for loop is constructed of several parts. Specifically, 4 parts:
1 2 3 4
|
for( initialization; condition; increment )
{
body;
}
|
It works like this:
1) 'initialization' is performed
2) 'condition' is checked. If it's true, continue to step 3. Otherwise (if it's false), exit the loop.
3) Perform the 'body'
4) Perform the 'increment'
5) go to step #2
For purposes of example... let's look at your last for loop in your code:
1 2
|
for (i = 0; i < 10; i = i + 2)
cout << temp[i] << " ";
|
The 4 parts are:
1 2 3 4
|
i = 0; // <- initialzation
i < 10; // <- condition
i = i + 2; // <- increment
cout << temp[i] << " "; // <- body
|
This means the for loop will accomplish the following:
- Step 1 - initialzation. i=0; is performed initializing i.
- Step 2 - check the condition. i<10 is true, so we continue to step 3
- Step 3 - body. temp[i] is printed (since i=0, this prints temp[0], which is
0)
- Step 4 - increment. i = i + 2. After this i==2
-- go back to step 2
- Step 2 - check condition. i<10 is still true, so keep going
- Step 3 - body. i=2, so temp[2], or
4 is printed.
- Step 4 - increment. After this, i==4
-- go back to step 2
- Step 2 - i==4, so condition is still true
- body. temp[4] or
8 is printed
- increment. now i==6
-- loop
- Step 2, condition is still true
- body. temp[6] or
12 is printed
- increment. now i==8
-- loop
- Step 2, condition is still true
- body. temp[8] or
16 is printed
- increment. now i==10
-- loop
- Step 2, i==10, so now the condition i<10 is FALSE... so the loop exits. Leaving i==10