Confused with array

  • Thread starter asz304
  • Start date
  • #1
108
0

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?
 

Answers and Replies

  • #2
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).
 
  • #3
108
0
Thanks. :D
 
  • #4
35,227
7,048
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.
 

Related Threads on Confused with array

  • Last Post
Replies
1
Views
765
Replies
3
Views
2K
  • Last Post
Replies
6
Views
6K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
5
Views
744
Replies
4
Views
2K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
6
Views
2K
Top