0

What's the meaning of the below code? Particularly that if condition.

for (int i = 0; i<10; i++) { if (!i) { cout << ++i; } }

27th Mar 2022, 3:32 AM
King
King - avatar
3 ответов
+ 2
Your loop will execute total 10 times condition will fail when loop reaches to 10<10. In if condition you have written i with (!) Not operator and anything integer number in if condition apart from zero will treat as a bool value true so and this ! Operator will make it false So If(!0) to which is true When i will increase then condition will be like this If( !1) which will be false Same for other numbers when your loop condition will true then control will move inside the body And Value will be printed 1 on the screen if(1) // true if(2) //true if(0) //false if(!0) // true if(!5) // false
27th Mar 2022, 4:03 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
The `if` block will only be executed once, that is when <i> value was zero. For other numbers, none will be printed because they are all non zero, which for C++ means numerically true. Iteration 1 <i> = 0 if( !i ) Evaluates to true because !0 yields true, just like !false. The if block is executed ... std::cout << ++i; // increment <i> before printing <i> Then <i> becomes 1 Then the third part of loop construct is executed i++ Which again, increments <i> so <i> becomes 2 None of the next numbers in sequence will pass the condition checked in the `if` conditional.
27th Mar 2022, 4:20 AM
Ipang
0
(!i) is same as i==0. That's why loop runs once.
27th Mar 2022, 6:06 AM
Simba
Simba - avatar