Computer Applications
What is the output produced by the following code?
int n = 20;
do {
System.out.println(n);
n = n - 3;
} while (n > 0);
Answer
20
17
14
11
8
5
2
Working
The initial value of n
is 20
. Every time the do-while loop is executed, n decreases by 3. Execution of the loop is summarized in the table below:
Iteration | n | Output | Test Conditionn > 0 | Remarks |
---|---|---|---|---|
1st | 20 | 20 | True | n is initially 20 . After updation, it becomes 17 (20 - 3) |
2nd | 17 | 17 | True | n becomes 14 (17 - 3) |
3rd | 14 | 14 | True | n becomes 11 (14 - 3) |
4th | 11 | 11 | True | n becomes 8 (11 - 3) |
5th | 8 | 8 | True | n becomes 5 (8 - 3) |
6th | 5 | 5 | True | n becomes 2 (5 - 3) |
7th | 2 | 2 | True | n becomes -1 (2 - 3) |
Since, the condition of while loop becomes false, the loop terminates.
Related Questions
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++);
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 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");
What is the output produced by the following code?
int num = 10; while (num > 0) { num = num - 2; if (num == 2) continue; System.out.println(num); } System.out.println("Finished");