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++);
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.
Related Questions
How many times are the following loop bodies repeated? What is the final output in each case?
int z = 2; while (z < 20) if ((z++) % 2 == 0) System.out.println(z);
What are the differences between while loop and do-while loop?
What is the output produced by the following code?
int n = 20; do { System.out.println(n); n = n - 3; } while (n > 0);
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);