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.

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.

Chandu said:   8 years ago
In the above program, they mention printf only once after performing sumdig functions. Therefore, the program prints the output values of sumdig values only.

Hakesh said:   7 years ago
What to do with return 0 statement?

Deepak Johnson said:   6 years ago
Why the value of b is 6?

Samba sivarao said:   6 years ago
@Deepak and @Debjani.

As we are calling the same function with same parameter in the main.
That value is assigned to 'b'.

So same operation takes place as 'a'.
And then b also get 6.

Samba sivarao said:   6 years ago
@Hakesh.
Return 0 belongs to else part of the function.
If n=0 then value 0 is returned .

In the program, the value n is not equal to 0.
So, if the condition is executed and there is no work with else part.
So the value of s is returned.

Yash Patel said:   3 years ago
@Vivek.

You explained it in a best way. Thank you very much.

Andy said:   1 decade ago
I want to know that at last step where the function is 3+2+1+sumdig(0) , so what is the value of sumdig(0). It's value is 0 how?

Bagesh kumar singh said:   1 decade ago
a=sumdig(123)

n=123 which n!= 0, So n will enter into the loop.

Now in the loop the values of d, n, s are 3(123%10), 12(123/10), 3+sumdig(12) [which will recurcive call].

So finally we will get the value for s is 6(3+2+1).

a=6;

Same as we find the value of b. b=6;

printf("%d%d",a,b); will print 6 and 6.

Bagesh kumar bagi said:   1 decade ago
Both function works as same so the output is 6 and 6..


Post your comments here:

Your comments will be displayed after verification.