CC-14 : Implement power function.
Description:
Given an input number and input integer named pow, return the value of num to the power pow.
Test cases and expected outputs:
| Input Parameters |
Expected outputs |
Number: 8
Power: 2
|
NumToPow: 64
|
Number: 2
Power: 5
|
NumToPow: 32
|
Pseudocode:
numToPow(num, pow):
| If pow==0, return 1; (base case).
|
| Else:
Return product of num and return value of recursive call to numToPow(num,pow-1).
|
Code:
public int numToPower(int num, int pow){
if (pow == 0) {
return 1;
}else {
return num*numToPower(num, pow-1);
}
}
Click here to download and run code and test cases !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class RecursionPowerFunction {
public int numToPower(int num, int pow){
if (pow == 0) {
return 1;
}else {
return num*numToPower(num, pow-1);
}
}
public static void main(String[] args) {
/***********************
Test cases given below:
**********************/
int retVal;
try {
RecursionPowerFunction rcn=new RecursionPowerFunction();
int num=8; int pow=2;
retVal=rcn.numToPower(num, pow);
System.out.println("Number: "+num);
System.out.println("Power: "+pow);
retVal=rcn.numToPower(num, pow);
System.out.println("NumToPow: "+retVal);
System.out.println();
num=8; pow=0;
retVal=rcn.numToPower(num, pow);
System.out.println("Number: "+num);
System.out.println("Power: "+pow);
retVal=rcn.numToPower(num, pow);
System.out.println("NumToPow: "+retVal);
System.out.println();
num=2; pow=5;
retVal=rcn.numToPower(num, pow);
System.out.println("Number: "+num);
System.out.println("Power: "+pow);
retVal=rcn.numToPower(num, pow);
System.out.println("NumToPow: "+retVal);
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
exception.printStackTrace();
}
}
}