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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
No comments:
Post a Comment