Program to find sum of digits of a Number

Following is the program to find out sum of digits of a number using loops.

#include<stdio.h>
#include<conio.h>

int sumOfDigit(int num);

void main()
{
   int num, sum;
   clrscr();
   printf("Enter a number\t");
   scanf("%d", &num);
   sum = sumOfDigit(num);
   printf("The sum of digit %d is %d", num, sum);
   getch();
}

int sumOfDigit(int num)
{
   int s=0, a, r;
   a = num;
   while(a)
   {
      r = a%10;
      s = s+r;
      a = a/10;
   }
  return s;
}

Output

Enter a number 123
The sum of digit 123 is 6	

Program to find sum of digits of a Number using recursion

Following is the same program using recursion.

#include<stdio.h>
#include<conio.h>

int sumOfDigit(int num);

void main()
{
   int num, sum;
   clrscr();
   printf("Enter a number\t");
   scanf("%d", &num);
   sum = sumOfDigit(num);
   printf("The sum of digit %d is %d", num, sum);
   getch();
}


int sumOfDigit(int num)
{
   int s, a;
   s = s+(num%10);
   a = num/10;
   if(a > 0)
   {
      sumOfDigit(a);
   }
  return s;
}

Output

Enter a number 108
The sum of digit 108 is 9