We can ask the user to enter a number. We will use one while loop to find out each digit present in the number.
Each step of the loop will collect one digit ( right most ) by dividing the number with 10 and storing the reminder. Each time ( loop ) reminder we will add up by storing in a variable sum.
#include <stdio.h>
int main()
{
int n, sum = 0, remainder;
printf("Enter an integer");
scanf("%d",&n);
while(n != 0)
{
remainder = n % 10;
sum = sum + remainder;
n = n / 10;
}
printf("Sum of digits of entered number = %dn",sum);
return 0;
}
Example: Recursive Function to Sum Digits
Shows how recursion can be used to sum digits.
#include <stdio.h>
int sumDigits(int num) {
if (num == 0)
return 0;
return (num % 10) + sumDigits(num / 10);
}
int main() {
int number = 12345;
printf("Sum of digits: %d\n", sumDigits(number));
return 0;
}
Output
Sum of digits: 15
Example: Sum of Digits for an Array of Numbers
Demonstrates how to compute the sum of digits for multiple numbers in an array.
#include <stdio.h>
int sumDigits(int num) {
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
int main() {
int numbers[] = {123, 456, 789, 12};
int size = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < size; i++) {
printf("Sum of digits of %d is: %d\n", numbers[i], sumDigits(numbers[i]));
}
return 0;
}
Output
Sum of digits of 123 is: 6
Sum of digits of 456 is: 15
Sum of digits of 789 is: 24
Sum of digits of 12 is: 3
Example: Sum of Digits Handling Negative Numbers
Ensures negative numbers are handled correctly by using abs().
#include <stdio.h>
#include <stdlib.h>
int sumDigits(int num) {
num = abs(num); // Handle negative numbers by taking absolute value
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
int main() {
int number = -12345;
printf("Sum of digits of %d is: %d\n", number, sumDigits(number));
return 0;
}