C Program Sum of Digit of given Number

C Program Sum of Digit of given Number

This program logic is based on looping structures and mod operator. mod operator % returns the remainder after division of two integers.

  1. Input number of integer type
  2. Obtain its remainder by dividing it by 10.
  3. Add remainder in sum variable.
  4. Divide the given number by 10
  5. Repeat same from step 2 till given number become zero.
  6. Print the output from sum variable and exit.

In above example, variable num to hold given number, variable r to hold remainder after mod operation. initialize variable sum to zero. 

suppose, value of num=368

r= num % 10 ; it returns the remainder after division operation.  i. e  8

sum = sum + r;   add the value of r variable to sum , as sum of digits

num=num / 10;  returns the quotient after division operation. i.e 36

repeat same steps till n is greater than zero. 

if sum is > 9 i.e it is two digit answer so assign value of sum variable to num variable , and repeat same steps. till value of sum become single digit.

SUM-OF-DIGIT.c (7 downloads)