code
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i < 10)
if (i % 2 == 0)
cout << i << endl;
return 0;
}
The output is
3
5
7
9
Since i is 1, I thought that the if statement satisfies 2% 2 == 0 and 2 should be output, but I don't know why 3.
CodePudding user response:
if (i % 2 == 0)
means evaluate i%2
and compare to 0
, and increment i
at some point after evaluating it but before cout << i
That's why you're seeing odd numbers printed. In every case, an even value of i
caused the statement controlled by the if
to be executed, and the increment changed the even value to an odd one.
CodePudding user response:
You are using post-increment, which increments the variable and then returns the old value before the increment. You are then printing the incremented value.
So, lets look at your loop step-by-step:
On the 1st iteration,
i
is 1.i
setsi
to2
, but returns1
. So theif
compares1 % 2 == 0
, which is false.On the 2nd iteration,
i
is 2.i
setsi
to3
, but returns2
. So theif
compares2 % 2 == 0
, which is true, socout << i
prints3
.On the 3rd iteration,
i
is 3.i
setsi
to4
, but returns3
. So theif
compares3 % 2 == 0
, which is false.On the 4th iteration,
i
is 4.i
setsi
to5
, but returns4
. So theif
compares4 % 2 == 0
, which is true, socout << i
prints5
.And so on...
It sounds like perhaps you were expecting i
to pre-increment instead, returning the new value rather than the old value. In which case, there is a slightly different syntax for that purpose:
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i < 10)
if ( i % 2 == 0) // <-- i vs i
cout << i << endl;
return 0;
}
Note the position of
in relation to i
. Both syntaxes increment i
, but positioning
to the left of i
returns the new value after i
is incremented, while positioning
to the right of i
returns the old value before i
was incremented.
Same with the decrement operator --
, too. It has pre-decrement and post-decrement versions.
CodePudding user response:
According to the C 14 Standard (5.2.6 Increment and decrement)
1 The value of a postfix expression is the value of its operand. [ Note: the value obtained is a copy of the original value — end note ] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a complete object type. The value of the operand object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true.
So for example in the second iteration of the while loop the variable i
is indeed equal to 2
after incrementing it in the first iteration of the loop
while (i < 10)
if (i % 2 == 0)
cout << i << endl;
Thus the condition of the if statement
if (i % 2 == 0)
evaluates to true. But the value of the variable i
after the evaluation of the condition was incremented. So this statement
cout << i << endl;
outputs the new value 3.
You can equivalently rewrite the while loop the following way
while (i < 10)
if (i % 2 == 0)
cout << i << endl;
else
i;