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
1 Like
Related Questions
Convert the following for loop statement into the corresponding while loop and do-while loop:
int sum = 0; for (int i = 0; i <= 50; i++) sum = sum + i;
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++);
What are the differences between while loop and do-while loop?
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);