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)
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));
}
}
Comments
Leave a comment