C Program to Calculate Sum of Digits of a Number
1. Introduction
Calculating the sum of digits is a common beginner-level C programming problem. It helps students understand loops, arithmetic operations, and number manipulation.
2. Problem Statement
Question: Write a C program to calculate the sum of digits of a number.
Example: If the number is 987, the sum is 9 + 8 + 7 = 24.
3. Logic
To calculate the sum of digits:
- Accept an integer number from the user.
- Extract the last digit using the modulus operator (
% 10). - Add the digit to a sum variable.
- Remove the last digit using division (
/ 10). - Repeat the process until the number becomes 0.
- Display the final sum.
4. Source Code
Here is a beginner-friendly C program:
#include <stdio.h>
int main() {
int number, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &number);
while(number != 0) {
digit = number % 10; // Extract last digit
sum = sum + digit; // Add digit to sum
number = number / 10; // Remove last digit
}
printf("Sum of digits = %d\n", sum);
return 0;
}
5. Sample Output
Enter a number: 987
Sum of digits = 24
Enter a number: 1234
Sum of digits = 10
6. Viva Questions
- Q: Which operator is used to extract the last digit of a number?
A: The modulus operator%. - Q: Why do we divide the number by 10 in each iteration?
A: To remove the last digit from the number. - Q: Which loop is used in this program?
A:whileloop. - Q: Can this program work for negative numbers?
A: It can, but typically we convert the number to positive usingabs(). - Q: What is the time complexity of this program?
A: O(n), where n is the number of digits in the number.
