Hello Everyone,
I have the following assignment to do.
"
(Recursive power Method) Write a recursive method power(base, exponent) that, when called, returns
base exponent
For Example, power(3,4) = 3*3*3*3. Assume that exponent is an integer greater than or equal to 1.
Hint: The recursion step should use the relationship
base exponent = base * base exponent-1
and the terminating condition occurs when exponent is equal to 1, because
base exponent 1 = base
Incorporate this method into a program that enables the user to enter the base and exponent.
"
Here is the code I wrote,
package recursionpower; import java.util.Scanner; public class RecursionPower { int baseNumber; int exponent; int count; int base; int answer; public static void main(String[] args) { RecursionPower begin = new RecursionPower(); begin.UserEntry(); } public void UserEntry(){ Scanner input = new Scanner(System.in); System.out.print("Enter base number -> "); base = input.nextInt(); System.out.print("Enter the exponent number -> "); exponent = input.nextInt(); baseNumber = base; Power(base, exponent); } public int Power(int base, int count){ if(count==1){ System.out.println("1 - The Answer is: " + base); } else{ System.out.println(count + " - " + base + " * " + baseNumber + " = " + (baseNumber * base)); base = baseNumber * base; count--; Power(base, count); } return base; } }
The above code works and the correct answer is produced every time,
run:
Enter base number -> 9
Enter the exponent number -> 5
5 - 9 * 9 = 81
4 - 81 * 9 = 729
3 - 729 * 9 = 6561
2 - 6561 * 9 = 59049
1 - The Answer is: 59049
BUILD SUCCESSFUL (total time: 6 seconds)
I am just looking for a more experience java programmer who can critique this and let me know what or how to make it better, if any.
Thanks,