ICSE Class 10 Computer Applications
Question 53 of 76
Revising Basic Java Concepts — Question 57
Back to all questions 57
Question Question 34
Predict the output :
class Power {
public static void main(String args[]) {
int e = 5, result, i;
result = 1 ;
i = e ;
while(e > 0) {
result *= 2 ;
e--;
}
int n = result /2, p = i - 1;
System.out.println("2 to the power of " + i + " is " + result);
System.out.println("2 to the power of " + p + " is " + n);
}
}Output
2 to the power of 5 is 32
2 to the power of 4 is 16
Explanation
The execution of while loop is shown in the table below:
| e | (e > 0) | result | Remarks |
|---|---|---|---|
| 5 | True | 2 | result = 1 x 2, e becomes 4 |
| 4 | True | 4 | result = 2 x 2, e becomes 3 |
| 3 | True | 8 | result = 4 x 2, e becomes 2 |
| 2 | True | 16 | result = 8 x 2, e becomes 1 |
| 1 | True | 32 | result = 16 x 2, e becomes 0 |
| 0 | False | Loop terminates |
n = result / 2, p = i - 1;
⇒ n = 32 / 2, p = 5 - 1
⇒ n = 16, p = 4