Program to find sum of digits of a number

Program to find sum of digits of a number

 

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

CODE:

# include <stdio. h>

# include <conio. h>

int sum (int num);

void main ()

{

   int num, sum1;

   clrscr ();

   printf (“Enter a number”);

   scanf (“%d”, &num);

   sum1 = sum (num);

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

   getch ();

}

int sum (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 124

The sum of digit 124 is 7