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");
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:
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.
Related Questions
Write a program using do-while loop to compute the sum of the first 500 positive odd integers.
What is the output produced by the following code?
int n = 20; do { System.out.println(n); n = n - 3; } while (n > 0);
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");
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