in Algorithms edited by
13,050 views
26 votes
26 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}$

in Algorithms edited by
13.1k views

2 Comments

Can anyone please tell me where does the return statement in the foo function returns?

If it returns to the end of the foo program then how and when is the printf statement being executed?

If it returns to the printf statement then the first value of k has to be zero right(since the k is being overwritten by the statement int k=0)? so the output would be like 0,2,0,4,8,0 right?
0
0
foo(2048,0) will print $2,0,4,8$ after this when function returns to the main () it will print sum variable which is local variable and it’s value is $0$. so the final output will be $2,0,4,8,0$
0
0

4 Answers

31 votes
31 votes
Best answer

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
by

4 Comments

@Arjun sir plzz elaborate this solution.
0
0
@Neha Singh

just execute a program in pen and paper u will get D as an answer...
1
1
But then no concept of static scoping will come? Plz elaborate when static scoping comes into play...
0
0
The sum is not a global variable, however, in the case of dynamic scoping, it would be 14.
3
3
16 votes
16 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.

2 votes
2 votes

Since one recursion call is there, we can use stack approach

1 vote
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 comment

I don't understand plz explanation give properly
0
0
Answer:

Related questions