+ 1

What's the output of this code [[ AND WHY EXPLAIN LINE BY LINE OF YOU CAN]]

int x =7; while (x%3) { x+ = (x-2); x/ = 2 ; } cout << x ;

19th Jan 2017, 12:09 PM
Amr Monsef
Amr Monsef - avatar
3 ответов
+ 3
The output is 6. First the loop checks the condition x%3 (checks if there is a remainder), which will keep the loop running until the condition is equal to 0. At first x=7. In the loop, 7%3=1, which means the condition is true and the loop runs. The first statement is x=7+(7-2) which is 12. Now the value of x=12. The second statement is x= 12/2, which means x is now equal to 6. Now it checks the condition in the loop again (x%3). Now, x=6, which means that the condition is 6%3. 6%3=0, since there is no remainder. The condition then evaluates to false and the loop doesn't run a second time. Keep in mind that x is still equal to 6. Now, cout<<x prints the value of x to the screen, which means that it prints 6, making the output of the code equal to 6. I hope you understand now.
19th Jan 2017, 1:36 PM
Nikolay Ganev
Nikolay Ganev - avatar
+ 2
the answer is 6 first you assigned x = 7 then checked the condition x%3 => 7%3 witch outputs 1 so the condition is true then subtract x and added it to x so it will be like x = x + (x-2) => x = 7 + (7-2) = 12 then divided x by 2 so x = 12/2 = 6 then it will check the condition again 6%3=0 so the condition is false so it will exit from the while loop and prints x that equals 6.
19th Jan 2017, 1:30 PM
Mohammad Khaled
Mohammad Khaled - avatar
+ 1
@Anonymo0s @Mohammad Khaled ; many thanks to you guys.. it's pretty easier now to understand.. am gonna try this code in the codes playground and see what will be the output and changing some numbers ..
19th Jan 2017, 1:50 PM
Amr Monsef
Amr Monsef - avatar