Answer to Question #207221 in Java | JSP | JSF for zura

Question #207221

1.    Write a recursive function, power, that takes as parameters two integers x and y such that x is nozero and return xy. You can use the following recursive function definition to calculate xy. If y>= 0,

 


                    1 if y=0

power(x, y) =    x                       if y=1

                        x*power(x,y-1)   if y>1

 

if y<0,

             power(x, y) = 1/power(x, -y)



1
Expert's answer
2021-06-15T07:08:27-0400
import java.util.Scanner;
public class Main
{
    static float power(int x, int y) {
        if (y ==0)
            return 1;
        else if (y == 1)
            return x;
        else if (y > 1)
            return (x * power(x, y - 1));
        else if (y < 0)
            return (1 / power(x,-y));
        return 0;
    }
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		System.out.print("Enter x:");
		int x=sc.nextInt();
		System.out.print("Enter y:");
		int y=sc.nextInt();
		System.out.println(x+"^"+y+" = "+power(x,y));
	}
}

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