C++ simple loop question

Hi, I'm having trouble figuring out the answer to this question. The output for this Code is suppose to be.

i is 5
5678
i is 9
_


I do not understand why there should be a 5 before 6 since the increment operator adds 1 hence I think the answer should be:

i is 5
678
i is 9
_


I know I'm wrong but can anyone explain why this is so.

The code for this problem is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std ;

int main ()
{
   int i = 5 ;

   cout << "i is " << i << "\n" ;

   while (i < 9)
   {
      cout << i++ ;
   }

   cout << endl ;
   cout << "i is " << i << "\n" ;

   return 0 ;
}	// end of main 


Any help would be appreciated. Thanks.
Last edited on
Let consider the execution path step by step.



1
2
3
   int i = 5 ;

   cout << "i is " << i << "\n" ;


i is set to 5 and then this value is outputed.

Then there is the loop

1
2
3
4
   while (i < 9)
   {
      cout << i++ ;
   }


As 5 is less than 9 then the control will enter the loop body.
Inside the loop there is postincrement operator ++. Its value is the value of i before its incrementing.
So this statement
cout << i++ ;
outputs the value of i that is equal to 5 and after assigns i the new incremented value that is equal to 6. And so on.
In the last iteration of the loop before the statement above i will be equal to 8. This value will be outputed and due to the postincrement operator ++ i will set to 9.
The condition of the loop

while (i < 9)

will be equal to false because 9 is not less than 9.
So the loop will be terminated and the control will be passed to the next statements after the loop

1
2
   cout << endl ;
   cout << "i is " << i << "\n" ;


They output 9 that is the current value of i.


Last edited on
i is still 5 the first time the while loop is encountered. i is incremented after line 12 - that is the purpose of the postfix ++ operator. To get the output you want use the prefix form ++i, which increments it first before printing it.

HTH
Great explanations. Thanks.
Last edited on
Topic archived. No new replies allowed.