Exercise-related to:
• Design and write recursive methods.
Question 1
Write a recursive method that calculates and returns the sum of 1 + X + X2 + X3+ X4 +…. +
XN where X and N are parameters passed to the method.
Solution
public static double Calculate(int X, int N)
{
if(N == 0)
return 1;
else
return [Link](X, N) + Calculate(X, N-1);
}
Question 2
Write a recursive method that counts and returns the number of occurrences of a specific character in
a String. Your method should have the following parameters: str: String, ch: char, and the length of
str: int.
Solution
public static int occurrences(String str, int length, char ch)
{
if(length == 0)
return 0;
else
if([Link](length – 1) == ch)
return 1 + occurrences (str, length – 1, ch);
else return occurrences (str, length – 1, ch);
}
Question 3
Write a recursive method that returns the sum of all odd numbers between two given values n
and m, where n and m are two integer parameters passed to the method, with n < m.
Solution
public static int addOdd(int n, int m)
{
if (n > m)
return 0;
else if (n%2 != 0)
return (n + addOdd(n+1, m));
else
1
return addEven(n+1, m);
}
Question 4
Write a recursive method that searches for a specific value in an integer array A. This method returns
true if the value is found and false otherwise. Your method should have the following parameters: an
array A: int, value: int, and the length of A: int.
Solution
public static boolean found (int [] A, int length, int item)
{
if(length != 0)
{
if(A[length - 1] == item)
return true;
else return found(A, length - 1, item);
}
return false;
}
Question 5
Write a recursive method findFactors that displays the factors (divisors) of a given integer number
N. The method should have two parameters: findFactors (int N, int num), where N is the
integer to be factored, and num is an integer initialized to 1 when first calling the function from main().
public static void findFactors(int N, int num)
{
if(num < N)
{
if(N % num ==0 )
[Link]( num + " ");
findFactors(N, num + 1);
}
}