Sum of Digits in C Programming

(Last Updated On: March 1, 2019)

Program to calculate sum of digits in C of a number using loop, explained logic and test cases.

Example,

Input number: 123
Output = 1+2+3 =6

Logic to find sum of digits:

  • Have two variables” sum” and “remainder” with initial value 0.
  • loop through the number
  • Get remainder of the number with modulus 10. e.g. 123 % 10 =3(last digit) and store in remainder.
  • add value of variable “sum” and remainder e.g. 0+3
  • Remove the last digit as it is processed and get the number again by dividing 10. e.g. 123/10 =12.
  • process the number 12 again in the loop and so on until value of input number becomes 0
  • loop end
  • sum variable will contain final result.

 

Program to calculate sum of digits in C

 

Test Cases

Input:12345
Output = 15

Input: -12345
Output = -15

Input: 0
Output = 0

 

NOTES:

Within the while loop in C program above, the remainder statement can be eliminated as below