Computer Applications

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

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

Java

Java Iterative Stmts

2 Likes

Answer

The loop repeats for infinite times.

2

Working

The value of y is 2. The test condition of while loop — y < 20 is true and the test condition of if — y % 2 == 0 is also true. So the loop prints the value of y i.e., 2 for the first time and then the postfix operator increments it to 3.

In the next iteration, the test condition y < 20 is true but the condition of if — y % 2 == 0 is false. Thus, there is no updation in the value of y and y remains less than 20. This creates an infinite loop.

Answered By

3 Likes


Related Questions