C Program to find Sum of Digits

Last Updated:

Find Sum of Digits

In the following example, we will add all the digits in the given number (12345) for just one time.

For example, 12345 = 1 + 2 + 3 + 4 + 5
i.e., 12345 = 15

Example

C Compiler
#include <stdio.h> int main() { int num = 12; int copyNum = num; int total = 0; // Add Each digit from last digit while(copyNum != 0) { total += copyNum % 10; copyNum = copyNum / 10; } // result printf("The sum of digit %d: %d", num, total); return 0; }

Find Sum of any given Digits

In the following example, we will find the sum of any given digits.

Example

C Compiler
#include <stdio.h> int main() { int num, total = 0; printf("Enter a (int) number: "); scanf("%d", &num); int copyNum = num; // Add Each digit from last digit while(copyNum != 0) { total += copyNum % 10; copyNum = copyNum / 10; } // result printf("The sum of digit %d: %d", num, total); return 0; }

Share this Page

Meet the Author