Do-While loop. Increment

Good afternoon ladies and gentlemen. I'm reviewing Loops from my textbook and a section review question asks what the output should be for the following code:

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

int main()
{
   int  funny = 1, serious = 0, count = 0, limit = 4;
   do
   {
      funny++;
      serious += 2;
   }while (count++ < limit);
   cout << funny << " " << serious << " " << count << endl;

   return 0;
}


The output is 6 10 5

This is what I think is happening:
iteration...funny...serious...count
0..............2..........2.............0
1st...........3..........4.............1
2nd..........4..........6.............2
3rd...........5..........8.............3
4th...........6..........10...........4

Given the while condition, how did 'funny' and 'serious' output their values up to the 4th iteration. I thought their outputs would be at 3rd iteration. And more confusing to me, how did 'count' increment all the way to 5 (skipping 4).

Please advise. Thanks in advnace...
Last edited on
The key here is to realize that the value of count++ is the value of count before it is incremented. The last time through the loop:
The second to last time through the loop count++ increments count from 3 to 4. The value of count++ is 3 so the loop continues.
The last thing through the loop count++ increments count from 4 to 5. The value of count++ is 4 and the loop ends.
closed account (EwCjE3v7)
Look at these programs:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
   int z = 0;
   while (z != 5) { // I will use a while as you might have not come across a for loop
    cout << (z++) << endl; // note the ++ is after z(postfix)
    cout << z << endl;
    cout << endl;
   }
   return 0;
}


The output will be

0 1
1 2
2 3
3 4
4 5


Now look at this

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
   int z = 0;
   while (z != 5) { // I will use a while as you might have not come across a for loop
    cout << (++z) << endl; // note the ++ is before z(prefix)
    cout << z << endl;
    cout << endl;
   }
   return 0;
}


output:

2 2
3 3
4 4
5 5


The postfix operator here(the ++ after that you used) returns the value of the object and then increments.

1
2
3
int z = 2;
foo(z++); // passes 2 and then increments
cout << z << endl; // prints 3 


1
2
3
int z = 2;
foo(++z); // passes 3
cout << z << endl; // prints 3 


Also on the first iteration the values will be 2,2,1 with the program you have above.
Last edited on
Thank you dhayden and fr0zen1. I will look further in to it. I'm reviewing the example codes now. But from the gist of both your feedback, it looks like I wasn't taking into consideration the effect of post fix and how the value of a counter can remain in a buffer.
Last edited on
Topic archived. No new replies allowed.