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 3 of 6.

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

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

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?

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.

Chatrapathi said:   1 decade ago
First :

a = sumdig(123)==>> sumdigt function.

d = n%10==> remainder 3 i.e d=3.
Then it go's to n= n/10==> n= 12.

s=d+sumdigit()==> sumdigit again called does the same here.
n=12 now.

d=n%10 => d=2.
n= n/10 => n=1.

Finally s=3+2+1=6.

Shrenu said:   1 decade ago
What is the value of 1%10 and 1/10. Can anyone explain this please. I can't understand this step?

Siribujje@gmail.com said:   1 decade ago
See @Vijaya. There are two return statements..but one for else..that means,

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;
}

And make sure that its if condition not while loop.

Vijaya said:   1 decade ago
If we have two return stmts without any condition then the first return statement is executed the next one is ignored. In the above program why the output 0 and 0 can anyone explain me.

Srinivas kumar said:   1 decade ago
d%10 gives the last number of a given number i.e., for example for number 123 last number is 3 and n/10 gives the except last number it gives whole number i.e., for example for number last number is 3 and remaining are 12.

Like that you can solve the code.

Taher Ali said:   1 decade ago
Initially n,d contains garbage value,

step-1-> N(start)=123 D=3 N=12 S=3+step2
step-2-> N(start)=12 D=2 N=1 S=2+step3
step-3-> N(start)=1 D=1 N=0 s=1+step4
step-4-> If condition is violated return 0.

So, while returning.

step-4=0
s=1+step4 becomes 1 which is step3
s=2+step3 becomes 3 which is step2
s=3+step2 becomes 6 which is returned to main.

Yasin said:   1 decade ago
@ Auto Variable Initialization

S value is initialized with Garbage value.

But, this value is over written with s=d+sumdig(N);


Post your comments here:

Your comments will be displayed after verification.