KnowledgeBoat Logo

Computer Applications

How many times are the following loop bodies repeated? What is the final output in each case?

int x = 2;
while (x < 20)
    if (x % 2 == 0)
        System.out.println(x);

Java

Java Iterative Stmts

1 Like

Answer

The loop repeats for infinite times.

2
2
2
2
2
.
.
.
.

Working

The value of x is 2. The test condition of while loop — x < 20 is true and the test condition of if — x % 2 == 0 is also true. So the loop prints the value of x i.e., 2 for the first time.

In the absence of update expression, the while loop continues infinitely and keeps on printing 2 on the output screen.

Answered By

2 Likes


Related Questions