#
Java Program – Program to Find Powers of 2

This program computes the Power of 2 by recursion. That is, 2^n for a positive integer n.

Recursive technique is used in this program

/*Power of 2 by recursion
Write a recursive mathematical definition for computing 2^n, for a positive integer n.
E.g. find 2^n
Mukesh Tekwani
*/
import java.util.Scanner;
class Powerof2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the power of 2:");
int n = input.nextInt();
System.out.println("2 raised to " + n + " is " + power(n));
}
public static long power(int n)
{
if (n == 0) //base case
return 1;
else if (n == 1)
return 2;
else
return (2 * power(n - 1));
}
}

### Share this with your friends:

### Like this:

Like Loading...