CJ_Slip14A

Slip No.14

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

1. Open Notepad.

2. Type the following code:

    import java.util.Scanner;

    public class PowerCalculator {

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

    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Input base and exponent
    System.out.print("Enter base: ");
    int base = scanner.nextInt();

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

    // Call recursive method
    int result = power(base, exponent);

    // Display result
    System.out.println(base + " raised to the power " + exponent + " is: " + result);

    scanner.close();
    }
    }
3. Save the file with the name PowerCalculator.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac PowerCalculator.java

6. Run the compiled Java program by typing:
java PowerCalculator

No comments:

Post a Comment