KnowledgeBoat Logo

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

Java

Java Iterative Stmts

3 Likes

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:

IterationnOutputTest Condition
n > 0
Remarks
1st2020Truen is initially 20. After updation, it becomes 17 (20 - 3)
2nd1717Truen becomes 14 (17 - 3)
3rd1414Truen becomes 11 (14 - 3)
4th1111Truen becomes 8 (11 - 3)
5th88Truen becomes 5 (8 - 3)
6th55Truen becomes 2 (5 - 3)
7th22Truen becomes -1 (2 - 3)

Since, the condition of while loop becomes false, the loop terminates.

Answered By

1 Like


Related Questions