• edited by
17,950 views
33 33 votes

Consider the following C-program:

void foo (int n, int sum) {
    int k = 0, j = 0;
    if (n == 0) return;
    k = n % 10; j = n/10;
    sum = sum + k;
    foo (j, sum);
    printf ("%d,",k);
}

int main() {
    int a = 2048, sum = 0;
    foo(a, sum);
    printf("%d\n", sum);
}

What does the above program print?

  1. $\text{8, 4, 0, 2, 14}$

  2. $\text{8, 4, 0, 2, 0}$

  3. $\text{2, 0, 4, 8, 14}$

  4. $\text{2, 0, 4, 8, 0}$

5 Answers

Best answer
40 40 votes

Correct Option: D

$foo$ is printing the lowest digit. But the $printf$ inside it is after the recursive call. This forces the output to be in reverse order

$2, 0, 4, 8$

The final value $sum$ printed will be $0$ as $C$ uses pass by value and hence the modified value inside $foo$ won't be visible inside $main$.

• edited by
21 21 votes

Quick soln :-Option Elimination

We will try to analyse o/p from last.

Last line of program is to print sum which is passed by value so it will retain its value 0. So option A & C eliminated.

Now call foo(2048,0) which push 8 into stack first so it will pop at last so 8 will print as 2nd last o/p.

Hence B is eliminated and Option D is Ans.

1 1 vote
the last print statement to be executed is in the main(). Since every time foo() is called, we are doing pass by value, the value stored in variable sum is local to foo() function calls.

So when control returns to main(), the value of sum will be 0. (as initialized in main()'s body). That eliminates (a) & (c).

Recursive calls(values stored in stack -> LIFO) on foo(), when returned is printing k values in the reverse order : 2->0->4->>8

Hence, answer : (d)
1 1 vote
foo(2048,0)

k = 8

j = 204

sum = 8

foo(204,8)

k = 4

j = 20

sum = 12

foo(20,12)

k = 0

j = 2

sum = 12

foo(2,12)

k = 2

j = 0

sum = 14

foo(0,14)

return;

O/P: 2,0,4,8,0
Answer:
Position:
Show:

Related questions

197 197 votes
9 answers 9 answers
77.9k
77.9k views
Kathleen asked Sep 22, 2014
77,910 views
A $5$ stage pipelined CPU has the following sequence of stages:IF – instruction fetch from instruction memoryRD – Instruction decode and register readEX – Execute: ALU op...
69 69 votes
6 answers 6 answers
27.9k
27.9k views
Kathleen asked Sep 22, 2014
27,896 views
double foo(int n) { int i; double sum; if(n == 0) { return 1.0; } else { sum = 0.0; for(i = 0; i < n; i++) { sum += foo(i); } return sum; } }The space complexity of the a...
58 58 votes
7 answers 7 answers
19.1k
19.1k views
go_editor asked Nov 14, 2016
19,055 views
double foo(int n) { int i; double sum; if(n == 0) { return 1.0; } else { sum = 0.0; for(i = 0; i < n; i++) { sum += foo(i); } return sum; } }Suppose we modify the above f...
32 32 votes
3 answers 3 answers
15.3k
15.3k views
gatecse asked Sep 21, 2014
15,339 views
Let $f(x)$ be the continuous probability density function of a random variable $x$, the probability that $a < x \leq b$, is :$f(b-a)$$f(b) - f(a)$$\int\limits_a^b f(x) dx...