-4

I'm getting confused a little
why does this code

#include <iostream>
#include <string>
using namespace std;
int main()
{
   int n = 1;
   do
   cout << n << " " ;
   while (n++ <= 3);
}

return 1 2 3 4

and this code

#include <iostream>
#include <string>
using namespace std;
int main()
{
   int n = 1;
   do
   cout << n << " " ;
   while (++n <= 3);
}

returns just 1 2 3

I mean, in the first code, why does it return 4 when 4 is definitely larger than 3?? and why it stops at 3 in the second code :/ confusing

2 Answers2

1

Because the value n++ is the value of n before the increment. The value of ++n is the value of n after the increment.

e.g.

int n = 1;
std::cout << n++ << std::cout; // shows 1
std::cout << n << std::cout; // shows 2

n = 1;
std::cout << ++n << std::cout; // shows 2
std::cout << n << std::cout; // shows 2

In the first code, why does it return 4 when 4 is definitely larger than 3?

As you can see above example, the value of n returns before the increment happens.

Why it stops at 3 in the second code?

Because the value of n returns after the increment happens.

0xdw
  • 3,755
  • 2
  • 25
  • 40
0

This is because in:

#include <iostream>
#include <string>
using namespace std;
int main()
{
   int n = 1;
   do
   cout << n << " " ;
   while (n++ <= 3);//**
} 

** because here the value of n is incremented after this while n++ <=3 statement that means once n=3 and 1,2,3 are printed the condition will be tested for n=3 and after that the value will be increased to 4, and since the condition was found to be true as well as the value of n was also incremented hence n=4 will also be printed.

sam2611
  • 455
  • 5
  • 15