This C program accepts a long integer from the user and returns the sum of its digits. This problem can be breakdown into simple steps as follows:
1. Extract last digit of the given number.
2. Add the extracted last digit to sum (which is initialize to 0 in the beginning ).
3. Remove last digit from given number.
4. Repeat this for all digits.
C program to find sum of digits of a number - Source code
/* C program to find the sum of digits of
long number, digit, sum = 0;
printf("Enter the number \n");
/* Repeat till number becomes 0 */
while (number > 0)
/* Find last digit of number and add to sum */
digit = number % 10;
sum = sum + digit;
/* Remove last digit from num */
number = number / 10;
printf("Sum of the digits of given number = %ld", sum);
Enter the number
Sum of the digits of given number = 24
Enter the number
Sum of the digits of given number = 34
1. Here three variables - number, digit, sum are declared of type long integer. You can choose digit and sum to be of integer type as their value in not going to be so large. Sum is initialized to 0 at the time of declaration.
2. Extraction of the last digit, adding it to sum and removal of the last digit, all the three operations are performed inside the while loop. The while loop terminates when the number becomes less than 0.
3. Modulus operator is used to extract the last digit. The modulus operator (%) divide the entered number by 10 and the remainder value is stored in the variable digit.
4.The value of variable digit is added to sum.
5. In the next step, the last digit is removed from the number by dividing it by 10. Here note that, integer division is performed and hence the returned result is also of integer type (it cut off the fractional part).
6. When the number becomes less than 0, the loop terminates and the value of sum is printed.
Install Computer Science Bits Android app to access all study material on the go.