Computer Applications
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);
Answer
The loop repeats for 18 times.
3
5
7
9
11
13
15
17
19
Working
The loop executes 18 times. Value of z
is printed 9 times inside the loop. The condition if((z++) % 2 == 0)
will be false when z
is odd and true when z
is even. Value of z
will be incremented after if check is performed due to post increment operator z++
. Execution of the loop is summarized in the table below:
Iterations | z | (z++) % 2 == 0 | Output | Remarks |
---|---|---|---|---|
1st | 2 | True | 3 | Value of z becomes 3 after if check as z++ increments it after the evaluation of (z++) % 2 == 0 . Hence, 3 is printed. |
2nd | 3 | False | z becomes 4 after if check | |
3rd | 4 | True | 5 | z becomes 5. |
4th | 5 | False | z becomes 6. | |
5th | 6 | True | 7 | z becomes 7. |
6th | 7 | False | z becomes 8. | |
7th | 8 | True | 9 | z becomes 9. |
8th | 9 | False | z becomes 10. | |
9th | 10 | True | 11 | z becomes 11. |
10th | 11 | False | z becomes 12. | |
11th | 12 | True | 13 | z becomes 13. |
12th | 13 | False | z becomes 14. | |
13th | 14 | True | 15 | z becomes 15. |
14th | 15 | False | z becomes 16. | |
15th | 16 | True | 17 | z becomes 17. |
16th | 17 | False | z becomes 18. | |
17th | 18 | True | 19 | z becomes 19. |
18th | 19 | False | z becomes 20. |
As value of z
is now 20
, the test condition of while loop becomes false
hence, 19th iteration of the loop is not executed.
Related Questions
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);
What is the output produced by the following code?
int n = 20; do { System.out.println(n); n = n - 3; } while (n > 0);
What is the output produced by the following code?
int num = 20; while (num > 0) { num = num - 2; if (num == 4) break ; System.out.println(num); } System.out.println("Finished");
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++);