Hi, I am taking a Data Structures & Algorithms class in Java this semester and w
ID: 3733359 • Letter: H
Question
Hi,
I am taking a Data Structures & Algorithms class in Java this semester and we are currently working on Recursion. I am struggling with understanding it and I have no idea how to do this assignment. If someone could help me with this, that would be great! I have attached the assignment.
Thanks!
Assignment
2. Read the "Raising a Number to Power" in textbook pp. 303-304. Write a recursive method power() that takes a number and a power (integer) as parameters and calculate the power of the number. For example, if the number is 2 and power is 8, the method will calculate 28 and return 256. Also, write a main method that prompts the user to enter a number and a power and uses the recursive method to calculate the power of the numberExplanation / Answer
PowerTest.java
import java.util.Scanner;
public class PowerTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = scan.nextInt();
System.out.println("Enter the power: ");
int p = scan.nextInt();
System.out.println("Power is "+power(n,p));
}
public static int power(int base,int exponent) {
if(exponent ==0) {
return 1;
} else {
return base * power(base, exponent-1);
}
}
}
Output:
Enter the number:
2
Enter the power:
8
Power is 256
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.