# Confused with array

## Homework Statement

say a[5] = { 5.6, -3.2, 11, -7.7, -1 );
and b = 5
Code:
void fum ( double a[], int b ){
for ( int i = b -1; i >= 0; i-- ){
if ( a[i] < 0 )
cout << -a[i];
else cout << a[i];
cout << ", ";
}
}

Why is the output

1, 7.7, 11, 3.2, 5.6

and not

7.7, 11, 3.2, 5.6 ?

Shouldn't the value of the first i in the for loop 3? and not 4? because i = 5-1 = 4 then it decrements to 3?

Your index will decrement after the loop has iterated once. So the first run through the index will be (5-1)=4, then decremented to 3 on the next iteration.

Since the 4th item in your array is -1, it'll print that (0-based index, of course).

Thanks. :D

Mark44
Mentor
A for loop generally looks like this:
Code:
for(expr1; expr2; expr3)
{
statement(s)
}
The order in which things happen is:
1. expr1 is evaluated.
2. expr2 is evaluated. If true (non-zero), the body of the for loop is executed. If false (zero), control flows to the first statement following the for loop.
3. expr3 is evaluated.

Note that when expr2 evaluates to false (zero), step 3 is not performed.