Solving Array Homework: Output Explained

  • Thread starter Thread starter asz304
  • Start date Start date
  • Tags Tags
    Array Confused
Click For Summary

Discussion Overview

The discussion revolves around a homework problem involving a C++ function that processes an array of doubles. Participants are examining the output of the function based on the provided array and the loop's indexing behavior.

Discussion Character

  • Homework-related
  • Technical explanation

Main Points Raised

  • The initial poster questions why the output of the function is "1, 7.7, 11, 3.2, 5.6" instead of "7.7, 11, 3.2, 5.6".
  • Some participants clarify that the loop starts with the index at 4 (5-1) and decrements after each iteration, which affects the output.
  • One participant explains the general structure and evaluation order of a for loop in C++, emphasizing the sequence of evaluations and control flow.

Areas of Agreement / Disagreement

Participants generally agree on the mechanics of the loop and indexing, but the initial poster's confusion about the output suggests some uncertainty remains regarding the expected behavior of the function.

Contextual Notes

There may be assumptions about the understanding of zero-based indexing and the behavior of for loops in C++ that are not explicitly stated.

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

  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
Replies
9
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 38 ·
2
Replies
38
Views
5K
  • · Replies 5 ·
Replies
5
Views
7K
  • · Replies 16 ·
Replies
16
Views
12K
  • · Replies 13 ·
Replies
13
Views
2K