A 5-digit positive integer is entered , write a function to calculate sum of digits of the 5-digit number:
(1) Without using recursion (2) Using recursion
#include <stdio.h>
int add(int);
int recadd(int);
int sum=0;
int r;
int main (int argc, const char * argv[])
{
printf("%d",recadd(12111));
return 0;
}
//without using recursion
int add(int num)
{
while (num>0)
{
r = num%10;
sum = sum +r;
num = num/10;
}
return sum;
}
//using recursion
int recadd(int num)
{
if (num>0)
{
r = num%10;
sum = sum + r;
recadd(num/10);
}
return sum;
}
0 comments:
Post a Comment