Page 423 - Cs_withBlue_J_C11_Flipbook
P. 423
B. Fill in the blanks:
1. Fill in the blanks to print the sum of the digits of a number ‘num’ using the recursive method int sumofdigit(int n).
int sumofdigit(int n)
{
int dig;
if(a. …………………)
return b. …………………;
else
{
dig=c. …………………;
return dig + d. …………………;
}
}
2. Fill in the blanks to return the product of all the numbers in an array using the recursive method.
int prod(int arr[],int i)
where arr[]={15, 3, 21, 7, 18} and i=0.
int prod(int arr[], int i)
{
if(a. …………………)
b. …………………;
else
c. …………………;
}
3. Fill in the blanks to count the frequency of ‘A’ in a String using the recursive method int count(String s, int p) where s="ABRACADABRA"
and p=0.
int count(String s, int p)
{
if(a. …………………)
b. …………………;
else if(c. …………………)
return 1+ d. …………………;
else
e. …………………;
}
Answers
1. a. n==0 b. 0 c. n%10 d. dig + sumofdigit(n/10)
2. a. i==arr.length b. return 1 c. return arr[i]*prod(arr,i+1)
3. a. p==s.length() b. return 0 c. s.charAt(p)==‘A’ d. count(s,p+1) e. return count(s,p+1)
C. Answer the following questions:
1. Write two uses of recursion.
Ans. Two uses of recursion are as follows:
• Recursion is used extensively in the backtracking algorithm.
• It can easily solve algorithms like tree traversal, tower of hanoi.
421
Recursion 421

