Let b is a real number. Let n be a non-negative integer. Assume
b and n are not simultaneously 0. Write iterative and recursive functions that return value of bn , the nth power of b.
follow the following methods’ details :
powerRecursive()
• Return the computed nth power of b
powerIteration()
• Receive the values of b and n from main() and compute the nth power of b iteratively
• Return the computed nth power of b
main()
Sample Output:
Enter value of b:3
Enter value of n: 6
6th power of 3 is 729. --> This is displayed through Iterative Method.
6th power of 3 is 729. --> This is displayed through Recursive Method.
Source code
import java.util.Scanner;
public class Main
{
static int powerRecursive(int b,int n){
if(n==0)
return 1;
else
return (b*powerRecursive(b,n-1));
}
static int powerIteration(int b,int n){
int power = 1;
for(int i=1;i<=n;i++){
power = power * b;
}
return power;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of b: ");
int b=sc.nextInt();
System.out.print("Enter value of n: ");
int n=sc.nextInt();
System.out.println(n+"th power of "+b+" is "+powerRecursive(b,n)+". --> This is displayed through Iterative Method.");
System.out.println(n+"th power of "+b+" is "+powerIteration(b,n)+". --> This is displayed through Iterative Method.");
}
}
Output
Comments
Leave a comment