From the C++ Primer book, chapter 1
Code:
For statement:
for (int val = 1; val <= 10; ++val)
Each for statement has two parts: a header and a body.
The header controls how often the body is executed.
an int statement (val = 1)
a condition (val <= 10)
and an expression (++val)
The variable val exists only inside the for; it is not possible to use val after this loop terminates
The init-statement is executed only once, on entry to the for
The condition (val <= 10) is tested each time through the loop. As long as val is less than or equal to 10, we excute the for body.
The expression is executed after the for body (it skips the first ++val and goes to the body first then back to the ++val and loops)
After executing the expression, the for retests the condition.
Code:
for (i=2;i>1;i=i-1)
{
printf("%d",arr[i]);
}
i is initialized to equal 2, i has to be greater than 1
prints arr at position 2 (2)
then the expression is executed (subtracts 1)
i is no longer greater than 1 so the loop stops.
Couple of more problems:
It will never be able to print 3 because you've got the expression i -= 1 (compound operator, same as i = i - 1), you're always subtracting 1 from i (eventually giving you a negative value)
The last loop will never execute if you are able to get it to print 3 because while i > 3 it will continue to print arr[i]
You don't have a type for you main
Code:
int arr[3]={0,1,2};
int i;
arr[0]=1;
arr[1]=2;
arr[2]=3;
You can initialize the values in arr[3] to equal 1, 2, 3 instead of changing them after. Get rid of int i and declare it in the for loop instead (So it exists only in each for loop)