Practice-06 Recursion in C
Practice-06 Recursion in C
Topic: Recursion in C
Date: 30-01-2017
1. What string does the following program print?
#include <stdio.h>
#include <string.h>
int main ()
{
char A[10] = "PDS 2005";
strFunc2(A,strlen(A));
printf("%s", A);
}
(a) 5002 SDP
(b) 5DS 200P
(c) PDS 2005
(d) SDP 2005
2. In this exercise, we deal with complex numbers of the form ( ) + i( ) with a, b, c, d
integers such that b and d positive. The following structure represents such a complex
number.
typedef struct {
int a; /* Numerator of the real part */
int b; /* Denominator of the real part */
int c; /* Numerator of the imaginary part */
int d; /* Denominator of the imaginary part */
} complexNumber;
Our aim is to compute the sum and product of two such complex numbers with each
fraction reduced to the standard form (i.e., reduced to the form with gcd(m, n) = 1, n
> 0).
void sum(int a1, int b1, int a2, int b2, int *a, int *b)
/* (a1/b1)+(a2/b2) */
{
*a = a1*b2 + a2*b1; *b = b1*b2;
reduce( ___________, _________);
}
void mul(int a1, int b1, int a2, int b2, int *a, int *b)
/* (a1/b1)*(a2/b2) */
{
*a = a1 * a2; *b = b1 * b2;
reduce( __________, __________);
}
3. What value does the call h(5) return, where h is defined as follows?
int h ( int n )
{
if (n == 0) return 1;
return 2*h(n-1);
}
(a) 25
(b) 32
(c) 64
(d) 120
Page | 1
4. Let the function g be defined as follows:
int g ( int n )
{
if (n < 2) return n;
return g(n/2);
}
(a) 0
(b) 1
(c) 2
(d) 71428
5. A two-dimensional character array is used to store a list of names. Each name is stored
in a row. An empty string indicates the end of the list. Complete the recursive function
printNames() to print the names stored in the two-dimensional array supplied as
p.
int main()
{
char names[20][100] = {"Bombay", "Delhi", "Guwahati",
"Kanpur","Kharagpur", "Madras", "Roorkee", "" };
printNames(names);
return 0;
}
int findMed (int A[], int startidx, int endidx, const int
medidx);
Here, the second and the third parameters are the start and end indices of the current
partition; the fourth parameter is the index of the median in the sorted version of A and
is kept constant across the calls.
(a) How many times is S(…) called (including the outermost call) to compute
S(5,3)?
(b) What is the value returned by S(5,3)? Show your calculations.
(c) Write a recursive function SMul() to count the number of multiplications in
the call S(n,k).
10. Complete the following recursive function that returns the floating point value of a
continued fraction <a0, a1, . . . , an−1>.
Note that <ai, ai+1, . . . , an−1> = ai +1/(<ai+1, ai+2, . . . , an−1> ) for i = 0, 1, . . . , n − 2.
if ( i == ________) return__________ ;
/* The terminating case, no recursive call */
return_________ ;
/* Make a recursive call and return */
}
The outermost call for computing <a0, a1, . . . , an−1> should be:
cfracrec( ___,___ )
int F[10];
int fib(int n)
{
printf(“*”);
if (n <= 1) return 1;
if (F[n] != 0) return F[n];
F[n]=(fib(n-1) + fib(n-2));
return F[n] ;
}
int main( )
{
int j;
for (j=0; j< 10; j++) F[j] = 0;
fib(5);
}
Use this observation to write a recursive function that, given a positive real number a
and a non-negative integer n, computes an.
The function should be efficient in terms of the total number of multiplications required
to find the answer.
13. The following incomplete code is for a recursive function RecursiveArraySum, which
calculates the sum of all the n-elements of an array passed as function argument.
Write the missing pieces of the code such that the sum is calculated by recursively
calling the function. The function RecursiveArraySum is invoked with a 4-element
array of [5, 10, 20, 40] as argument. The base address of the array is at 10,000
(decimal). At every recursive call, write the values of the parameters passed and the
return value from the function.
Ans.
if (n == 0) return 0;
else
return (a[0] + RecursiveArraySum(a+1,n-1));
OR
return (a[n-1] + RecursiveArraySum(a,n-1));
Page | 4
14. The following function is expected to compute the factorial of a positive number n. Is
the given code error free? If not, then using one sentence state the reason why it will
not work and also give the corrected code.
long fact(int n)
{
long k=1;
do
k*=fact(i--);
while(n>0);
return k;
}
15. What value will the following function return when called as recur(3)?
k=(data>2)?(recur(data-1)-recur(data-2)):1;
return k;
}
What is the maximum height to which the recursion stack grows when the outermost
call is f(10)? Assume that the stack is empty just before this outermost call.
(a) 5
Page | 5
(b) 9
(c) 13
(d) 32
17. Mathematically express the return value f (n) of the function supplied below. Your
mathematical expression for f (n) must hold for all integers n > 0.
F(0) = 0,
F(1) = 1,
F(n) = F(n-2)+F(n-1) for n > 2.
19. Convert the recursive program in the left box to an iterative program in the right box.
int sum(int n)
{
if (n < 1) return 0;
return sum(n - 1) + sum(n - 2) + n;
}
#include<stdio.h>
Page | 6
t(n-1,fp,ap,tp);
printf(“%c%c”,fp,tp);
t(n-1,ap,tp,fp); return;
}
void main()
{
t(2,'x','y','z');
}
21. If our universe consists of only the set of nonnegative integers, the even and odd
numbers can be characterized as follows: a number is even if its predecessor is odd, a
number is odd if is not even, the number 0 is even by definition. Complete the C
functions below which return 1 when the input number n is even or odd respectively.
Both the functions are defined in the same program and they call each other.
22. A recursive algorithm may require more computation time and memory than its
iterative version.
(a) TRUE
(b) FALSE
(a) Write a recursive C function to compute xn based on the above definition. Clearly
mention suitable base cases.
(b) Find out how many function calls are made to compute x16 using your function.
int f(int n)
{
static int i = 1;
if (n >= 5)
Page | 7
return n;
n = n+i;
i++;
return f(n);
}
(a) 5
(b) 6
(c) 7
(d) 8
int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf ("%d\n", sum);
getchar();
}
(a) 8, 4, 0, 2, 14
(b) 8, 4, 0, 2, 0
(c) 2, 0, 4, 8, 14
(d) 2, 0, 4, 8, 0
#include <stdio.h>
int f(int n)
{
static int r = 0;
if (n <= 0) return 1;
if (n > 3)
{
Page | 8
r = n;
return f(n-2)+2;
}
return f(n-1)+r;
}
int main()
{
printf("%d", f(5));
}
(a) 5
(b) 7
(c) 9
(d) 18
27. Consider the following recursive C function that takes two arguments
What is the return value of the function foo when it is called as foo(345, 10) ?
(a) 345
(b) 12
(c) 5
(d) 3
28. Consider the same recursive C function that takes two arguments
What is the return value of the function foo when it is called as foo(513, 2)?
(a) 9
(b) 8
(c) 5
(d) 2
int f(int j)
{
static int i=50;
int k;
if(i==j)
{
Page | 9
printf("something");
k=f(i);
return 0;
}
else
return 0;
}
Give a value q (to 2 decimals) such that f(q) will return q:_____.
(a) 0
(b) 26
(c) 51
(d) 71
32. Consider the following recursive C function. If get(6) function is being called in main()
then how many times will the get() function be invoked before returning to the main()?
(a) 15
Page | 10
(b) 25
(c) 35
(d) 45
if (n == 0) return 0;
t = foo6(A,n-1);
if ( ((A[n-1]>='a') && (A[n-1]<='z')) ||
((A[n-1]>='A') && (A[n-1]<='Z')) ||
((A[n-1]>='0') && (A[n-1]<='9')) )
++t;
return t;
}
2. A rational number is defined by a pair of integers (a,b) with b > 0 and is interpreted to
stand for a/b. A rational number a/b is said to be in the reduced form if gcd(a,b)=1.
Page | 11
a. Define a structure to represent a rational number.
b. Write a function that returns the rational number 0/1. This function can be used to
initialize a rational number variable.
c. Write a function that, given a rational number, returns its reduced form.
d. Write a function that, upon input of two rational numbers, returns the sum of the
two input numbers in the reduced form.
e. Repeat the previous part for subtraction, multiplication and division of rational
numbers.
4. A circle in the X-Y plane is specified by three real numbers a,b,c. The real numbers may
be interpreted in two possible ways. The first possibility is that (a,b) represents the center
and c the radius of the circle. In the second representation, we refer to the equation of the
circle as:
X2 + Y2 + aX + bY + c = 0.
So a structure holding three double variables together with a flag indicating the
particular interpretation suffices to store a circle.
a. Write a function that converts a circle structure from the first to the second
representation.
b. Write a function that converts a circle structure from the second to the first
representation.
c. Write a function that, upon input a circle and two real numbers x,y, checks
whether the point (x,y) lies inside, on or outside the circle. Note that the input
circle may be of any of the two representations.
d. Write a function that, upon input two circles each with any representation,
determines whether the circles touch, intersect or do not intersect.
e. Write a function that, upon input a circle in any representation, returns the side of
a square that has the same area as the input circle.
5. Write a recursive function that computes the binomial coefficient C(n,r) using the
inductive definition:
Page | 12
6. Write a Function to recursively compute the harmonic mean of an array of numbers. In
the main function, create an array of size 10. Input integers from the user till a negative
number is given as input or the 10 elements have been filled up. Find the harmonic
mean of the elements of this array.
7. Write a function to recursively compute the sum of digits of a positive integer. The
function has to be recursive. Function Protype : int sum(int n);
8. A rectangle in the X‐Y plane can be specified by eight real numbers representing the
coordinates of its four corners. Define a structure to represent a rectangle using eight
double variables. Notice that here we do not assume the sides of a rectangle to be
necessarily parallel to the X and Y axes. Notice also that by a rectangle we mean only the
boundary (not including the region inside).
a. Write a function that, upon input a structure of the above kind, determines
whether the structure represents a valid rectangle.
b. Write a function that, upon input a valid rectangle, determines the area of the
rectangle.
c. Write a function that, upon input a valid rectangle and two real numbers x, y,
determines whether the point (x,y) lies inside, on or outside the rectangle.
Assume data for all the 10 customers of the bank are stored in the structure array :
The function, transaction, is used to perform a customer request for withdrawal or deposit
to her account. Every such request is represented by the following three quantities:
Account number of the customer, request type (0 for deposit and 1 for withdrawal) and
amount. The function prototype is as follows:
The transaction function returns 0 if the transaction fails and 1 otherwise. The transaction
fails only when the account balance is less than the withdrawal amount requested.
The array bank (defined above) is another input to the transaction function and is suitably
updated after every request. In case of a failed transaction no change is made in the bank
array.
Write a main() function which populates the array bank with values for 5 customers. Also,
the main() should take a withdrawal request from the user (i.e., read values for account
Page | 13
number, amount), and call the transaction function, and thereby print if it is a valid
transaction. If valid, it should print the balance after the withdrawal.
with F1 = F0 = 1
Write a recursive function int Fibonacci(int n) , which would return the n‐th Fibonacci
number when you call it from main for an input n .
11. Read any two positive numbers a and b. Write a recursive function int gcd(int a, int b),
which would return the greatest common divisor of a and b. You should read the
numbers a and b in the main function and call gcd(a,b) in the main.
--*--
Page | 14