
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 Until Single Digit in C++
In this article, we will be discussing a program to find the sum of digits of a number until the sum itself becomes a single digit and cannot be done summation of further.
For example, take the case of a number 14520. Adding the digits of this number we get 1 + 4 + 5 + 2 + 0 = 12. Since this is not a single digit number, we would further add the digits of the number received. Adding them we get, 1 + 2 = 3.
Now, 3 is the final answer because it is a single digit number itself and its digits cannot be added further.
To solve this, we would use the approach that the sum of digits of a number divisible by 9 is equal to 9 only. For the numbers that are not divisible by 9, we can divide them by 9 so as to get the remaining digit which would be the final sum of the given number.
Example
#include<bits/stdc++.h> using namespace std; //function to check the divisibility by 9 int sum_digits(int n) { if (n == 0) return 0; else if (n%9 == 0) return 9; else return (n%9); } int main() { int x = 14520; cout<<sum_digits(x)<<endl; return 0; }
Output
3