Program to find sum of digits of a number using recursion

Program to find sum of digits of a number using recursion


Consider the following example to find sum of digits of a number using recursion:

CODE:

# include <stdio. h>

# include <conio. h>

int sum (int num);

void main ()

{

   int num, sum1;

   clrscr ();

   printf (“Enter a number\t”);

   scanf (“%d”, &num);

   sum1 = sum (num);

   printf (“The sum of digit %d is %d”, num, sum);

   getch ();

}

int sum (int num)

{

   int s, a;

   s = s + (num % 10);

   a = num / 10;

   if (a > 0)

   {

      sum (a);

   }

  return s;

}

OUTPUT:

Enter a number 124

The sum of digit 124 is 7