Computer Applications

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");

Java

Java Iterative Stmts

2 Likes

Answer

18
16
14
12
10
8
6
Finished

Working

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:

IterationnumTest Condition
num > 0
OutputRemarks
1st20True18num becomes 18 (20 - 2)
if condition false
2nd18True16num becomes 16 (18 - 2)
if condition false
3rd16True14num becomes 14 (16 - 2)
if condition false
4th14True12num becomes 12 (14 - 2)
if condition false
5th12True10num becomes 10 (12 - 2)
if condition false
6th10True8num becomes 8 (10 - 2)
if condition false
7th8True6num becomes 6 (8 - 2)
if condition false
8th6Truenum 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.

Answered By

3 Likes


Related Questions