Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, I am taking a Data Structures & Algorithms class in Java this semester and w

ID: 3732846 • Letter: H

Question

Hi,

I am taking a Data Structures & Algorithms class in Java this semester and we are learning about Recursion. I am struggling with understanding it and I don't really know how to approach one part of the assignment . If someone could help me with this, that would be great!

Thanks!

Assignment

2. Read the "Raising a Number to Power" in textbook pp. 303-304. Write a recursive method power() that takes a number and a power (integer) as parameters and calculate the power of the number. For example, if the number is 2 and power is 8, the method will calculate 28 and return 256. Also, write a main method that prompts the user to enter a number and a power and uses the recursive method to calculate the power of the number

Explanation / Answer

class DSJAVA {

/* Function to calculate x raised to the power y */

static int power(int x, int y)

{

if (y == 0)

return 1;

else if (y % 2 == 0)

return power(x, y / 2) * power(x, y / 2);

else

return x * power(x, y / 2) * power(x, y / 2);

}

/* Program to test function power */

public static void main(String[] args)

{

int x = 2;

int y = 3;

System.out.printf("%d", power(x, y));

}

}

OUTPUT:-

8

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote