TYBBA(CA) Core Java Slip No 14 Q A

Q.Write a Java program to calculate power of a number using recursion. [15 M]

import java.util.Scanner;

public class PowerRecursion {

    // Recursive method to calculate power
    static int power(int base, int exp) {
        if(exp == 0)
            return 1;
        else
            return base * power(base, exp - 1);
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter base number: ");
        int b = sc.nextInt();

        System.out.print("Enter exponent: ");
        int e = sc.nextInt();

        int result = power(b, e);

        System.out.println("Power = " + result);

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top