0

? and : in c++

int x = 0; for (int i = 0; i < 4; i++) { x += (i % 2 ? 1 : 0); } The solution is 2, but how do I do the calculation on paper?

5th Jun 2017, 11:33 AM
gorgamin
gorgamin - avatar
3 Answers
+ 1
x += (i % 2 ? 1 : 0); is the same as if(i % 2) ++x; or x += i % 2 -- It just counts the even numbers until a certain number. I hope this helps
5th Jun 2017, 12:24 PM
Madera Oxidada
Madera Oxidada - avatar
+ 1
it is ternary operator. u must be aware of operator precedence and associativity. which will helpful to perform such statements. based on that these statements got executed.
5th Jun 2017, 5:41 PM
Nanda Balakrishnan
0
It does, thanks!
5th Jun 2017, 1:48 PM
gorgamin
gorgamin - avatar