Discussion 2 Correction
Discussion 2 Correction

The explanation given for the Simple Trace Example given in discussion class was wrong with regards to the behavior of the for loop. In class, you were told that the expressions:

int Sum10 (void) { int answer, i; answer = 0; for ( i = 0; i <= 10; ++i ) { answer += i; } return (answer); } ... and ... int Sum10 (void) { int answer, i; answer = 0; for ( i = 0; i <= 10; i++ ) { answer += i; } return (answer); } ... would produce different outputs (due to when i is incremented in the for loop) when in fact they do not. They both output the following: {4:57pm}[irix1] cs201/dis2 >a.out The result was 4.000000. The result was 21.000000. *gasp* Why's if different? {4:57pm}[irix1] cs201/dis2 > The incrementation of i is done in the for loop before it is ever used in the statement answer += i;. Now for the correct information. The examples below have answers which are effected by how i is incrememnted. See if you can detect what the problem was and why the outputs are different?

Function Code Output
int Sum10 (void) { int answer, i, more; answer = 0; for ( i = 0; i <= 10; more = ++i ) { answer += more; } return (answer); } {4:48pm}[irix1] cs201/dis2 >a.out The result was 4.000000. The result was 21.000000. *gasp* Why's if different? {4:48pm}[irix1] cs201/dis2 >
int Sum10 (void) { int answer, i, more; answer = 0; for ( i = 0; i <= 10; more = i++ ) { answer += more; } return (answer); } {4:52pm}[irix1] cs201/dis2 >a.out The result was 4.000000. The result was 17.666666. *gasp* Why's if different? {4:52pm}[irix1] cs201/dis2 >

Please email me if you have any further questions. Thanks!


Main Page
Last Modified 3 October 2000