C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 6)
6.
What will be the output of the program?
#include<stdio.h>
int sumdig(int);
int main()
{
    int a, b;
    a = sumdig(123);
    b = sumdig(123);
    printf("%d, %d\n", a, b);
    return 0;
}
int sumdig(int n)
{
    int s, d;
    if(n!=0)
    {
        d = n%10;
        n = n/10;
        s = d+sumdig(n);
    }
    else
        return 0;
    return s;
}
4, 4
3, 3
6, 6
12, 12
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
51 comments Page 1 of 6.

Ammu said:   8 years ago
step 1: d=123%10==3
n=123/10==12
s=3+sumdig(12)since n==12.
step 2: d=12%10==2
n=12/10==1
s=5(since 3+2)+sumdig(1).
step 3: d=1%10==1
n=n/10==0
s=5+1==6
so s==6.
(7)

Divya gawande said:   7 years ago
Why in output 6, 6 is two times taken? Please explain in detail.
(2)

Debjani said:   6 years ago
Why the value of b is 6?
(2)

Noel said:   7 years ago
I think the sticking point for me and others is once you have d = 1%10.

If it were division, the result would be 0. However, with MODULAR MATH, 1%10 is 1.
(1)

Shalom chauhan said:   1 decade ago
step1:-> call to function sumdig with parameter 123,now n=123
step2:-> function starts
step3:-> declaration of s & d and contains null value
step4:-> 123!=0 condition true, loop starts
step5:-> d=123%10, d=3
step6:-> n=123/10, n=12
step7:-> s=d+sumdig(12),call to function sumdig with parameter 12, n=12 & s=3+sumdig(12)
step8:->step1 with value of n=12
step8:->finally s=3+2+1,6
step9:->now (n!=0) condition false come out of loop and return value 6
step10:->same execution for b=sumdig(123)
by shalom chauhan
(1)

Ram said:   7 years ago
Thanks @Ammu.
(1)

Vivek said:   1 decade ago
step1:-> call to function sumdig with parameter 123,now n=123
step2:-> function starts
step3:-> declaration of s & d and contains null value
step4:-> 123!=0 condition true, loop starts
step5:-> d=123%10, d=3
step6:-> n=123/10, n=12
step7:-> s=d+sumdig(12),call to function sumdig with parameter 12, n=12 & s=3+sumdig(12)
step8:->step1 with value of n=12
step8:->finally s=3+2+1,6
step9:->now (n!=0) condition false come out of loop and return value 6
step10:->same execution for b=sumdig(123)
(1)

N DAMODHAR said:   9 years ago
Can anyone explain this the program.

I don't understand the step in s = d+sumdig(n);

Shahid said:   8 years ago
@Taher Ali.

Awesome solution. It works for (- and *).

Divya said:   1 decade ago
Can someone explain, when n=0 after n=n/1;if (n!=0) condition becomes false.

So, it should return 0. How can it even reach the statement returns?


Post your comments here:

Your comments will be displayed after verification.