ICSE Class 10 Computer Applications
Question 14 of 69
Iterative Constructs in Java — Question 14
Back to all questions 14
Question Question 10
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");Output
8
6
4
0
Finished
Explanation
The initial value of num is 10. 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 | 10 | True | 8 | num becomes 8 (10 - 2)if condition false |
| 2nd | 8 | True | 6 | num becomes 6 (8 - 2)if condition false |
| 3rd | 6 | True | 4 | num becomes 4 (6 - 2)if condition false |
| 4th | 4 | True | num becomes 2 (4 - 2)if condition becomes true, Continue statement sends control to next iteration of while loop | |
| 5th | 2 | True | 0 | num becomes 0 (2 - 0)if condition false |
After 5th iteration, num becomes 0 so the loop terminates.
Since, the body of if contains continue statement, when num becomes 2, control ignores the remaining statements in the loop and starts the next iteration of the loop.