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:
52 comments Page 1 of 6.

Ammu said:   9 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:   8 years ago
Why in output 6, 6 is two times taken? Please explain in detail.
(2)

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

Ram said:   8 years ago
Thanks @Ammu.
(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)

Noel said:   8 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)

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)

Arck said:   10 years ago
If I take 1234 as an input I want 234 as an output. How can I do it?

Sudhakar said:   10 years ago
None of Them is correct answer.

According to mine at last step condition will fail and else part will be executed which will return 0, both time.

Answer should be 0, 0.

What others think?

Shubham Singh said:   1 decade ago
Can anyone tell me that in this program as we know that "if" is executed only once but it will between executed again and again. It is due to sumdig (n) or any other reason.


Post your comments here:

Your comments will be displayed after verification.