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

Java

Java Nested for Loops

4 Likes

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)resultRemarks
5True2result = 1 x 2, e becomes 4
4True4result = 2 x 2, e becomes 3
3True8result = 4 x 2, e becomes 2
2True16result = 8 x 2, e becomes 1
1True32result = 16 x 2, e becomes 0
0FalseLoop terminates

    n = result / 2, p = i - 1;
⇒ n = 32 / 2, p = 5 - 1
⇒ n = 16, p = 4

Answered By

1 Like


Related Questions