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

Rahiman said:   1 decade ago
sumdig(123) -->returns the sum of the individual digits of a number( here 123 )

The Logic here is simply taking each and every digit at a time and adding of all those digits.

i) first of all modulo division of a number gives remainder(i.e., 3) and normal division is storing in a same 'n'

Repeating the above process until we get zero in a while loop condition.

AKki said:   1 decade ago
You are wrong yash we can't use two return statemt in a common statement.

Yash said:   1 decade ago
Yes we can use two or more return statements in a common function but if there are no conditions then it returns threw the first return statement. The others do not execute.

Pratik said:   1 decade ago
One thng is that why it is returning zero?

Can we two retun statement in a common function defination?

Please give me some sugetion to make my "c" strong?

Sandeep said:   1 decade ago
Vivek explained nice.

Sai said:   1 decade ago
#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;
}

Can anyone pls give the flow of control of this program?

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)

Sowmya said:   1 decade ago
@Hagesh

Can you explain this in clear way?

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

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.


Post your comments here:

Your comments will be displayed after verification.