C++ Code Display: Understanding Output of Exam-Related Question

  • Context: C/C++ 
  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    C++ Code
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
11 replies · 3K views
ineedhelpnow
Messages
649
Reaction score
0
I came across this question while studying for a C++ exam. What is the screen output of the code?

Code:
#include <stdio.h>

int main(){
   int i, counter=0;

   for(i=0;i<100;counter++){
      i++;
      ++counter;
    }
    cout<<i<<' '<<counter<<'\n';

    return 0;
}

What will this code display on the screen once compiled and executed?
 
Physics news on Phys.org
First, how may times would you say the loop body executes?
 
MarkFL said:
First, how may times would you say the loop body executes?

99.
 
ineedhelpnow said:
99.

The variable i begins at 0 and ends at 99 and is incremented by 1, so the loop iterates 100 times. Here is a general formula to determine the number of times a loop will iterate:

$$N=\frac{\text{Ending value}-\text{Initial value}}{\text{Increment}}+1=\frac{99-0}{1}+1=100$$

So, how many times are the two variables incremented?
 
Let's look at the variable [m]i[/m] first. We see it is incremented by 1 every time the loop is iterated. And the loop continues to iterate as long as [m]i < 100[/m]. Once i is incremented to store a value of 100, the loop terminates. So, we can be certain that the ending value of [m]i[/m] is 100.

The variable [m]counter[/m] is a little different. It is incremented in the body of the loop, but it is also incremented in the increment statement of the for loop. The increment statement is performed before the condition is evaluated.

So, if the loop is iterated 100 times, how many times is [m]counter[/m] incremented?
 
ineedhelpnow said:
200?

Yes, it is incremented twice per loop iteration, and with 100 iterations, this is 200 increments. So, [m]counter[/m] is initialized to be 0, and is then incremented by 1 200 times...what will its final value be?
 
ineedhelpnow said:
199

Think of the formula:

$$N=0+\sum_{k=1}^n(1)=n$$

So, the final value would be 200.

Or think of you having no money in your hand initially. Then I begin placing one dollar bills into your hand one at a time. I do this 200 times...so you end up with 200 dollars in your hand. :D
 
do-me-a-favor-smiley-emoticon.png
Oops. I understand. So the screen would display 100 200?
 
ineedhelpnow said:
Oops. I understand. So the screen would display 100 200?

Yes. (Yes)