RECURSION
1. Consider the following C-program: (GATE-2005)
void foo(int n, int sum)
{
int k = 0, j = 0; intmain ()
if (n == 0) {
return; int a = 2048, sum = 0;
k = n % 10; foo (a, sum);
j = n / 10; printf ("%d\n", sum);
sum = sum + k; getchar();
foo (j, sum); }
printf ("%d,", k);
}
What does the above program print?
a) 8, 4, 0, 2, 14 b) 8, 4, 0, 2, 0 c) 2, 0, 4, 8, 14 d) 2, 0, 4, 8, 0
COMMON DATA QUESTIONS
Consider the following recursive C function that takes two arguments (GATE-2011)
unsigned int foo(unsigned int n, unsigned int r)
{
if (n > 0)
return (n%r + foo (n/r, r ));
else
return 0;
2. 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
3. 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
4. Consider the following C function. (GATE 2015)
int fun (int n)
{
int x = 1, k;
if (n==1) return x;
for (k = 1; k < n; ++k )
x= x+fun( k ) * fun (n-k) ;
return x;
}
The return value of fun (5) is
5. Consider the C functions foo and bar given below: (GATE 2017)
int foo(intval)
{
int x=0;
while(val> 0)
{
x = x + foo(val--);
}
returnval;
}
int bar(intval)
{
int x = 0;
while(val> 0)
{
x= x + bar(val-1);
}
returnval;
}
Invocations of $foo(3)$ and $bar(3)$ will result in:
A) Return of 6 and 6 respectively.
B) Infinite loop and abnormal termination respectively.
C) Abnormal termination and infinite loop respectively.
D) Both terminating abnormally.
6. Consider the following two functions (GATE 2017)
void fun1(int n)
{
if(n == 0)
return;
printf(“%d”, n);
fun2(n-2);
printf(“%d”, n);
}
void fun2(int n)
{
if(n == 0) return;
printf(“%d”, n);
fun1(++n);
printf(“%d”, n);
}
The output printed when fun1 (5) is called is
(A) 53423122233445 (B) 53423120112233
(C) 53423122132435 (D) 53423120213243