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?
$\text{8, 4, 0, 2, 14}$
$\text{8, 4, 0, 2, 0}$
$\text{2, 0, 4, 8, 14}$
$\text{2, 0, 4, 8, 0}$
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$.
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.
Since one recursion call is there, we can use stack approach
64.3k questions
77.9k answers
244k comments
80.0k users