3. Recursion
3. Recursion
3-Recursion
Note: You can select and do some questions according to your ability only. We would like to note you that the more
questions you do the better for you in doing final practical and writing exams.
Writing exercises
1. Give the sequence of argument values that result when the following program is invoked for each of the integers
1 through 9.
int puzzle(int n)
{if (n == 1) return 1;
if (n % 2 == 0)
return puzzle(n/2);
else
return puzzle(3*n+1);
}
void show(int n)
{ System.out.print(n%10);
if(n>0) show(n/10);
}
a. What values of a and b are directly handled by the stopping (base) case?
b. What are the values of mystery(2, 25) and mystery(3, 11)? Given positive integers a and b,
describe what value mystery(a, b) computes. Answer the same question, but replace + with *.
c. For the call mystery(3, 7), how many calls to mystery will be made, including the original call?
void ex237(int n)
{ if (n <= 0) return;
StdOut.println(n);
ex237(n-2);
ex237(n-3);
StdOut.println(n);
}
String ex238(int n)
{
if (n <= 0) return "";
return (ex238(n-3) + n + ex238(n-2) + n);
}
Practical exercises
Write Java programs to perfom the following tasks:
1. Write a recursive function that computes the sum of all numbers from 1 to n, where n is given as parameter.
//return the sum 1+ 2+ 3+ ...+ n
int sum(int n)
2. Write a recursive function that finds and returns the minimum element in an array, where the array and its size
are given as parameters.
//return the minimum element in a[]
int findmin(int a[], int n)
3. Write a recursive function that computes and returns the sum of all elements in an array, where the array and its
size are given as parameters.
//return the sum of all elements in a[]
int findsum(int a[], int n)
4. Write a recursive function that determines whether an array is a palindrome, where the array and its size are
given as parameters.
//returns 1 if a[] is a palindrome, 0 otherwise. The string a is palindrome if it is the same as its reverse.
int ispalindrome(char a[], int n)
5. Write a recursive function that searches for a target in a sorted array using binay search, where the array, its size
and the target are given as parameters.
6. Implement the Greatest Common Divisor algorithm as recursive method GCD. Use recursion. Do NOT use a
loop.
10. Write recursive method addReciprocals that takes an integer as a parameter and returns the sum of the first n
reciprocals.
addReciprocals(n) returns (1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + ... + 1.0/n).
11. Stirling numbers: A stirling number of the first kind is defined as follows
s(0,0) = 1
s(n,0) = 0, for all n > 0
s(n+1,k) = s(n,k-1) - n*s(n,k), for all n ≥0 and k>0