Compute Power: Write a program to compute a^n (a power n) using recursion.
Input and Output Format:
Input consists of 2 integers.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Sample Input and Output:
Enter the value of a
2
Enter the value of n
8
The value of 2 power 8 is 256
Solution
import java.util.*;
class Main{
public static void main(String[] args) {
int a, b, c, d;
System.out.println("Enter the value of a");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
System.out.println("Enter the value of n");
b = sc.nextInt();
System.out.println("The value of " + a + " power " + b + " is " + computePower(a, b));
//sauravhathi
}
public static int computePower(int a, int b) {
if (n>1){
return a*computePower(a, n-1);
}
else if (n==0){
return 1;
}
else{
return a;
}
}
}Happy Learning – If you require any further information, feel free to contact me.
![[Solved] Compute a^n Compute Power with Java [Solved] Compute a^n with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Compute-a^n-with-Java.png)
![[Solved] Letter Frequency with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Letter-Frequency-with-Java-300x200.png)
![[Solved] Lucy at the Film Festival with Java, C++, Python](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Lucy-at-the-Film-Festival-with-Java-C-Python-300x200.png)
