Program to Find the Sum of Digits of a Number in C

Finding the Sum of Digits

The sum of digits of a number is calculated by repeatedly extracting each digit and adding it to a sum variable.

We will explore a method to compute the sum of digits using C programming.

Method: Using a while Loop

We extract each digit using the modulus operator and sum them up.

#include <stdio.h>

int main() {
    int num, sum = 0, digit;
    
    // Prompt user for input
    printf("Enter a number: ");
    scanf("%d", &num);
    
    // Loop to extract and sum digits
    while (num > 0) {
        digit = num % 10; // Extract last digit
        sum += digit; // Add digit to sum
        num /= 10; // Remove last digit from number
    }
    
    // Print the result
    printf("Sum of digits = %d", sum);
    
    return 0;
}
            

Output:

Enter a number: 1234
Sum of digits = 10
Easy aceess next quctions
Getting Started

Positive or Negative number: C C++ Java Python

Even or Odd number: C C++ Java Python

Sum of First N Natural numbers: C C++ Java Python

Sum of N natural numbers: C C++ Java Python

Sum of numbers in a given range: C C++ Java Python

Greatest of two numbers: C C++ Java Python

Greatest of the Three numbers: C C++ Java Python

Leap year or not: C C++ Java Python

Prime number: C C++ Java Python

Prime number within a given range: C C++ Java Python

Sum of digits of a number: C C++ Java Python

Reverse of a number: C C++ Java Python

Palindrome number: C C++ Java Python

Armstrong number: C C++ Java Python

Armstrong number in a given range: C C++ Java Python

Harshad number: C C++ Java Python

Abundant number: C C++ Java Python

Friendly pair: C C++ Java Python