Consider a class MathUtils which has method that perform various mathematical fu
ID: 3624995 • Letter: C
Question
Consider a class MathUtils which has method that perform various mathematical functions using recursion.
public class MathUtils
{
public static int factorial ( int n)
{
//to be implemented }
public static int power ( int base, int exp)
{
// to be implemented}
public static void triple (int[] a)
{
//to be implemented}
}
a. The factorial method returns the factorial of the number given. Implement factorial using recursion.
b. The power method raises base to the power exp. Implement power using recursion.
c. The triple method triples every element in the given array. Implement triple using recursion, adding a helper method if necessary.
Explanation / Answer
public static int factorial(int n)
{
if (n <= 1)
return 1;
return n*factorial(n-1);
}
public static int power(int base, int exp)
{
if(exp == 0)
return 1;
return base*power(base, exp-1);
}
public static void triple(int[] a)
{
helper(a, 0);
}
private static void helper(int[] a, int start)
{
if(start >= a.length)
return;
a[start] *= 3;
helper(a, start+1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.