Question-A 5-digit positive integer is entered through the keyboard,
write a function to calculate sum of digits of the 5-digit
number:
(1) Without using recursion
(2) Using recursion
Solution-
it's a good question. let's check out the solution. I would like to make more generalized program. like for any digit number. so, check this out.
/*Without using Recursion */
#include<stdio.h>
int main()
{
int n,sum;
printf("Enter any number\n");
scanf("%d",&n);
sum=numsum(n);
printf("Sum=%d\n",sum);
return 0;
}
numsum(int n)
{
int a,sum=0;
for(;n>0;)
{
a=n%10;
sum=sum+a;
n=n/10;
}
return(sum);
}
/*Using Recurrsion */
#include<stdio.h>
int main()
{
int n,sum;
printf("Enter any number\n");
scanf("%d",&n);
sum=numsum(n);
printf("Sum=%d\n",sum);
return 0;
}
numsum(int n)
{
int a,sum=0;
if(n>0)
{
a=n%10;
sum=a+numsum(n/10); /*Here is the recursive call , calling the function again */
}
return(sum);
}
write a function to calculate sum of digits of the 5-digit
number:
(1) Without using recursion
(2) Using recursion
Solution-
it's a good question. let's check out the solution. I would like to make more generalized program. like for any digit number. so, check this out.
/*Without using Recursion */
#include<stdio.h>
int main()
{
int n,sum;
printf("Enter any number\n");
scanf("%d",&n);
sum=numsum(n);
printf("Sum=%d\n",sum);
return 0;
}
numsum(int n)
{
int a,sum=0;
for(;n>0;)
{
a=n%10;
sum=sum+a;
n=n/10;
}
return(sum);
}
/*Using Recurrsion */
#include<stdio.h>
int main()
{
int n,sum;
printf("Enter any number\n");
scanf("%d",&n);
sum=numsum(n);
printf("Sum=%d\n",sum);
return 0;
}
numsum(int n)
{
int a,sum=0;
if(n>0)
{
a=n%10;
sum=a+numsum(n/10); /*Here is the recursive call , calling the function again */
}
return(sum);
}
I am not getting right answer by using recursion
ReplyDelete