- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding sum of digits of a number until sum becomes single digit in C++
In this tutorial, we are going to write a program that sums digits of the given number until it becomes a single digit. Let's see an example.
Input −4543
Output −7
Let's see the steps to solve the problem.
Initialize a number.
Initialize the sum to 0.
Iterate until the sum is less than 9.
Add each digit of the number to the sum using modulo operator
Print the sum
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; void findTheSingleDigit(int n) { int sum = 0; while(n > 0 || sum > 9) { if(n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } cout << sum << endl; } int main() { int n = 4543; findTheSingleDigit(n); return 0; }
Output
you execute the above program, then you will get the following result.
7
We have another simple method to solve the problem. If the given number is divisible by 9, then the answer is 9. Else the number if n % 9.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; void findTheSingleDigit(int n) { if (n == 0) { cout << 0; } else if (n % 9 == 0) { cout << 9 << endl; } else { cout << n % 9 << endl; } } int main() { int n = 4543; findTheSingleDigit(n); return 0; }
Output
If you run the above code, then you will get the following result.
7
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Articles
- C++ program to find sum of digits of a number until sum becomes single digit
- Maximum of sum and product of digits until number is reduced to a single digit in C++
- Sum up a number until it becomes one digit - JavaScript
- Sum up a number until it becomes 1 digit JavaScript
- Program to find sum of digits until it is one digit number in Python
- Summing up all the digits of a number until the sum is one digit in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- C program to find sum of digits of a five digit number
- C Program to sum the digits of a given number in single statement
- Count of n digit numbers whose sum of digits equals to given sum in C++
- Reduce sum of digits recursively down to a one-digit number JavaScript
- Print all n-digit numbers whose sum of digits equals to given sum in C++
- Find sum of digits in factorial of a number in C++
- Minimum number of single digit primes required whose sum is equal to N in C++
- Find smallest number with given number of digits and sum of digits in C++

Advertisements