Answer to Question #255294 in Java | JSP | JSF for Rob

Question #255294

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()

  • Receive the values of b and n from main() and compute the nth power of b recursively

• 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()

  • Accept the value for b and n which will be used to compute the nth power of
  • Display the computed nth power of b from both iterative and recursive methods


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.



1
Expert's answer
2021-10-22T16:46:18-0400

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





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS