Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to find sum of digits of a five digit number
In C programming, finding the sum of digits of a five-digit number involves extracting each digit and adding them together. We use the modulo operator (%) to extract the last digit and integer division (/) to remove it from the number.
Syntax
int digitSum = 0;
while (number != 0) {
digitSum += number % 10;
number /= 10;
}
So, if the input is like num = 58612, then the output will be 22 because 5 + 8 + 6 + 1 + 2 = 22.
Algorithm
To solve this, we follow these steps −
- Initialize sum to 0
- While the number is not equal to 0:
- Extract the last digit using modulo operator (num % 10)
- Add this digit to sum
- Remove the last digit by dividing by 10 (num / 10)
- Return the sum
Example
Let us see the following implementation to get better understanding −
#include <stdio.h>
int main() {
int num = 58612;
int sum = 0;
int originalNum = num;
while (num != 0) {
sum += num % 10;
num = num / 10;
}
printf("Number: %d<br>", originalNum);
printf("Sum of digits: %d<br>", sum);
return 0;
}
Number: 58612 Sum of digits: 22
How It Works
The algorithm works by repeatedly extracting the rightmost digit:
- Iteration 1: 58612 % 10 = 2, sum = 2, num = 5861
- Iteration 2: 5861 % 10 = 1, sum = 3, num = 586
- Iteration 3: 586 % 10 = 6, sum = 9, num = 58
- Iteration 4: 58 % 10 = 8, sum = 17, num = 5
- Iteration 5: 5 % 10 = 5, sum = 22, num = 0
Conclusion
This method efficiently calculates the sum of digits using modulo and division operations. The algorithm works for any positive integer, not just five-digit numbers, making it a versatile solution.
