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:
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.
Answered By
1 Like
Related Questions
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");
Write a program to input n number of integers and find out:
i. Number of positive integers
ii. Number of negative integers
iii. Sum of positive numbers
iv. Product of negative numbers
v. Average of positive numbers
What is the output produced by the following code?
int n = 20; do { System.out.println(n); n = n - 3; } while (n > 0);
How many times are the following loop bodies repeated? What is the final output in each case?
int z = 2; while (z < 20) if ((z++) % 2 == 0) System.out.println(z);