ICSE Class 10 Computer Applications
Question 13 of 69
Iterative Constructs in Java — Question 13
Back to all questions 13
Question Question 9
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");Output
18
16
14
12
10
8
6
Finished
Explanation
The initial value of num is 20. Every time the while loop is executed, num decreases by 2. Execution of the loop is summarized in the table below:
| Iteration | num | Test Conditionnum > 0 | Output | Remarks |
|---|---|---|---|---|
| 1st | 20 | True | 18 | num becomes 18 (20 - 2)if condition false |
| 2nd | 18 | True | 16 | num becomes 16 (18 - 2)if condition false |
| 3rd | 16 | True | 14 | num becomes 14 (16 - 2)if condition false |
| 4th | 14 | True | 12 | num becomes 12 (14 - 2)if condition false |
| 5th | 12 | True | 10 | num becomes 10 (12 - 2)if condition false |
| 6th | 10 | True | 8 | num becomes 8 (10 - 2)if condition false |
| 7th | 8 | True | 6 | num becomes 6 (8 - 2)if condition false |
| 8th | 6 | True | num becomes 4 (6 - 2)if condition becomes true, loop terminates. |
Since, in 8th iteration num becomes 4, the condition of if statement becomes true. break statement is executed and control jumps out of while loop to the println statement and "Finished" is printed on the screen.