Recursion Exercise PDF
Recursion Exercise PDF
Exercise: Recursion
We have gone through many examples in the class and those examples are available in the slides
and uploaded codes. Try to test those codes and modify as you wish for getting more clarification.
1) What would be the output of the following recursive function if we call rec2(5) ?
void rec2(int x)
{
if (x==0)
return;
rec2(x-1);
printf("%d ", x);
}
Answer:
2) Write a recursive function that calculates the sum 11 + 22 +33 +…+nn, given an integer value of n
in between 1 and 9. You can write a separate power function in this process and call that power
function as needed:
3) Given the function below, what would the function call question3(10, 101) return?
int zeros(int n)
{
int res = 0;
while (n!=0)
{
res += n/5;
n /= 5;
}
return res;
}
6. Write a recursive function that returns the product of the digits of its integer input parameter, n.
You omay assume that n is non-negative. For example, productDigits(243) should return 24, since 2
x 4 x 3 = 24.
7. Let us define the weighted sum of an integer array a[0], a[1], a[2], …, a[n-1] be a[0]*1 + a[1]*2 +
a[2]*3 + …+a[n-1]*n. For example, the weighted sum of the array [5,2,6] would be 5*1+2*2+6*3 =
27. Write a recursive function that takes in an array numbers and its length n, and returns its
weighter sum. You can assume n is non-negative integer.
10. Draw the recursion tree to find out the value of f(5)
int f(int n)
{
int ans;
int i;
if(n<3)
return n;
ans = f(n/2);
for(i=0; i<n; i++)
ans += f(i);
return ans;
}
11. Write a recursive function that returns 1 if an array of size n is in sorted order and 0 otherwise. Note: If
array a stores 3, 6, 7, 7, 12, then isSorted(a, 5) should return 1 . If array b stores 3, 4, 9, 8, then isSorted(b,
4) should return 0.