Calculate power of 2 to n times

This program is to calculate nth power of 2 .





public class PowerOf2 {

public static void main(String[] args) {

Scanner scn =new Scanner(System.in);
System.out.println("Enter power of 2");
int pow = scn.nextInt();
long result = getPow(pow);
System.out.println("result = "+result);

}

private static long getPow(int n) {
long result = 1;
for(int i=1;i<=n;i++) {
result*= 2;
}
return result;
}
}

Post a Comment

Previous Post Next Post