AD1

Monday, 14 November 2016

Write a recursive function to calculate the sum of digits of an integer 

write a recursive function that accepts an integer and finds sum of its digits , as example sum(2370) will print 12

solution

#include <stdio.h>
#include <math.h>
int sumofdigits(int n)
{
int sum=0;
if(n>0)
{
sum=(n%10)+sumofdigits(n/10);
}
return(sum);
}
int main()
{
int number;
printf("Enter positive integer\n");
scanf("%d",&number);
if(number>0)
{
printf("sum of digits of %d = %d",number,sumofdigits(number));
}
else
{
printf("Error! you must enter a positive integer");
}
return 0;
}
view raw sumofdigits.c hosted with ❤ by GitHub

No comments:

Post a Comment