ICSE Class 10 Computer Applications Question 9 of 69

Iterative Constructs in Java — Question 9

Back to all questions
9
Question

Question 7(i)

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);
Answer

The loop repeats for infinite times.

Output
2
2
2
2
2
.
.
.
.
Explanation

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.