How many times will the following loop execute? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How many times will the following loop execute?

int x = 1; while (x++ < 5) { if (x % 2 == 0) x += 2; } The answer is 2. I got 4, where am I going wrong? 1 % 2 != 0, therefore the if statement shouldn't execute. 1 % 2 = 1 I guess remainders always round up? Since the if statement shouldn't execute, the function should loop 4 times because of the post-increment. If the if statement was formulated with a / instead of a % the answer would be 2. Maybe there's a bug in the application's answer? It's a sheet response, not a program.

13th Dec 2021, 11:07 AM
Alain Sauve
2 Answers
+ 4
First loop: while(x++ < 5) //x is 1 { //x is 2 because x++ if(x % 2 == 0) //true { x += 2; //x is 4 } } Second loop: if(x++ < 5) //x is 4 { //x is 5 because x++ if(x % 2 == 0) //false { x += 2; //no effect } } Third loop: is not executed because x++ < 5 is false
13th Dec 2021, 11:42 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 3
Thanks for the clarification. I was going through the forum on the question itself, and I found the answer. I wasn't aware that the while command would execute regardless of the result of the if statement. I thought the curly bracket statements needed to resolve prior to the rest of the function. So modulus (%) doesn't grant the quotient, it just finds remainders if they exist.
13th Dec 2021, 11:46 AM
Alain Sauve