Solving Array Homework: Output Explained

  • Thread starter Thread starter asz304
  • Start date Start date
  • Tags Tags
    Array Confused
AI Thread Summary
The discussion clarifies the output of a function that processes an array of doubles. The array a contains five elements, and the function iterates from the last index down to zero, printing the absolute values of negative numbers. The confusion arises from the initial index calculation; the loop starts at index 4, not 3, due to zero-based indexing. This results in the output being "1, 7.7, 11, 3.2, 5.6" instead of the expected "7.7, 11, 3.2, 5.6." Understanding the for loop's mechanics is crucial for interpreting the output correctly.
asz304
Messages
107
Reaction score
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?
 
Physics news on Phys.org
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
 
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.
 

Similar threads

Back
Top