Computer Applications
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);
}
}
Answer
2 to the power of 5 is 32
2 to the power of 4 is 16
Working
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
Related Questions
Write one difference between / and % operator.
Give the output of the following program segment and also mention how many times the loop is executed.
int i; for (i = 5 ; i > 10; i++) System.out.println(i); System.out.println(i * 4);
Predict the output :
class Test { public static void main (String args[]) { double x, y, z ; x = 3; y = 4; z = Math.sqrt(x * x + y * y); System.out.println("z = " + z); } }
Predict the output :
class FindFac { public static void main (String args[]) { for(int i = 2; i <= 100; i++) { System.out.print("Factors of" + i + ": "); for(int j = 2; j < i; j++) if((i % j) == 0) System.out.print(j + " "); System.out.println(); } } }