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

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

Shahid said:   8 years ago
@Taher Ali.

Awesome solution. It works for (- and *).

Shahid said:   8 years ago
@Vivek.

The same logic can't be applied for (d*sumdig(n));

Answer for this (0,0) and (d-(sumdig(n));answer for this (2,2).

Poongodi said:   9 years ago
How comes the value of s=3+2+1,6?

Please explain, & clear it.

Siva said:   9 years ago
Good explanation @Taher Ali.

Trupti said:   9 years ago
Good explanation @Vivek.

Amisha aggarwal said:   9 years ago
Super @Vivek, your approach is nice.

Megha said:   9 years ago
But in the program, there is no while loop simple if condition is given. Then how it works?

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

Sudhakar said:   9 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?


Post your comments here:

Your comments will be displayed after verification.