KnowledgeBoat Logo

Computer Applications

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

Java

Java Iterative Stmts

3 Likes

Answer

8
6
4
0
Finished

Working

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:

IterationnumTest Condition
num > 0
OutputRemarks
1st10True8num becomes 8 (10 - 2)
if condition false
2nd8True6num becomes 6 (8 - 2)
if condition false
3rd6True4num becomes 4 (6 - 2)
if condition false
4th4Truenum becomes 2 (4 - 2)
if condition becomes true, Continue statement sends control to next iteration of while loop
5th2True0num 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.

Answered By

1 Like


Related Questions