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

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.

Madhu said:   1 decade ago
@Teja. You make a small mistake.

In first executing loop you have written that sumdig (n) =0;.

Why it is zero. ?

It is not zero. It will execute sumdig (n) function again.

Satyanarayana said:   1 decade ago
Very nice vivek.

Kantasiva said:   1 decade ago
Here in this program this function (sumdig(123)) will be continue .it is nothing but the recursion function here we are using .
So
if(n!=0)
{
here n=123, 2nd loop n=12,3rd loop n=1, 4th loop =0 then the condition break;
s=d+sumdig(n) , lst time .3+2,5+1=6;

Piyush Sinha said:   1 decade ago
Actually u people are missing a small thing... the output is 3+2+1+0. as the return 0 is in else part which comes when if(n!=0) becomes false and then it return s. I hope everything will be clear now. :)

8246 said:   1 decade ago
First d=3 and n=12.

Next d=2 and n=1.

Next d=1 and n=0.

Therefore answer is 3+2+1=6.

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

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.

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.

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.


Post your comments here:

Your comments will be displayed after verification.