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;
}
Discussion:
51 comments Page 5 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.
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)
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?
Divya gawande said:
7 years ago
Why in output 6, 6 is two times taken? Please explain in detail.
(2)
Noel said:
7 years ago
I think the sticking point for me and others is once you have d = 1%10.
If it were division, the result would be 0. However, with MODULAR MATH, 1%10 is 1.
If it were division, the result would be 0. However, with MODULAR MATH, 1%10 is 1.
(1)
Ram said:
7 years ago
Thanks @Ammu.
(1)
Debjani said:
6 years ago
Why the value of b is 6?
(2)
Deepak Johnson said:
6 years ago
Why the value of b is 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.
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.
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.
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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers