KnowledgeBoat Logo

Computer Applications

How many times will the following loop execute? Write the output of the code:

int x=10; 
while (true){
System.out.println(x++ * 2);
if(x%3==0)
break;
} 

Java

Java Iterative Stmts

ICSE Sp 2025

3 Likes

Answer

The loop executes two times.

Output

20
22

Explanation:

Step-by-Step Execution of the Code

Initial Value of x:
x = 10

Iteration 1:
System.out.println(x++ * 2);

  • x++ → Use the current value of x (10), then increment x to 11.
  • Output: 10 * 2 = 20

if (x % 3 == 0):

  • x = 11, so 11 % 3 = 2 → Condition is false.

Iteration 2:
System.out.println(x++ * 2);

  • x++ → Use the current value of x (11), then increment x to 12.
  • Output: 11 * 2 = 22

if (x % 3 == 0):

  • x = 12, so 12 % 3 = 0 → Condition is true.

break;

  • The break statement exits the loop.

Answered By

2 Likes


Related Questions