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