Thursday, 26 October 2023

Write a Java program to calculate power of a number using recursion.

 Write a Java program to calculate power of a number using recursion.

 import java.util.Scanner;

import java.io.*;

public class powernum {

   public static int power(int base, int exp){

      if (exp !=0){

         return (base * power(base, exp-1));

      }else {

         return 1;

      }

   }

   public static void main(String args[]){

      Scanner sc = new Scanner(System.in);

      System.out.println("Enter the base number :");

      int base = sc.nextInt();

      System.out.println("Enter the exponent number :");

      int exp = sc.nextInt();

      System.out.println("Output : "+power(base, exp));

   }

}

 

C:\Program Files\Java\jdk1.7.0_80\bin>javac powernum.java

C:\Program Files\Java\jdk1.7.0_80\bin>java powernum

Enter the base number : 7

Enter the exponent number : 2

Output : 49