
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of Digits of a Five-Digit Number in C
Suppose we have a five-digit number num. We shall have to find the sum of its digits. To do this we shall take out digits from right to left. Each time divide the number by 10 and the remainder will be the last digit and then update the number by its quotient (integer part only) and finally the number will be reduced to 0 at the end. So by summing up the digits we can get the final sum.
So, if the input is like num = 58612, then the output will be 22 because 5 + 8 + 6 + 1 + 2 = 22.
To solve this, we will follow these steps −
- num := 58612
- sum := 0
- while num is not equal to 0, do:
- sum := sum + num mod 10
- num := num / 10
- return sum
Example
Let us see the following implementation to get better understanding −
#include <stdio.h> int main(){ int num = 58612; int sum = 0; while(num != 0){ sum += num % 10; num = num/10; } printf("Digit sum: %d", sum); }
Input
58612
Output
Digit sum: 22
Advertisements