Q:

C++ program to keep calculate the sum of the digits of a number until the number is a single digit

0

C++ program to keep calculate the sum of the digits of a number until the number is a single digit

Given an integer number and we have to keep adding the digits until a single digit is not found.

Example:

Input: Enter a number: 147
Output: 3
Explanation: 147 → 1+4+7 = 12 → 1+2 = 3

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Here is the program for this tricky challenge:

#include <iostream>
using namespace std;

int main() 
{
	int number = 147; //Any number.
	int res;

	if(number)
		res = number % 9 == 0 ? 9 : number % 9 ;
	else 
		res = 0;

	//print the result
	cout<<res;

	return 0;
}

Output

3

Explanation

Yes. This is the complete program for this tricky challenge. Let me explain what is going on under the hood.

There are divisibility rules for every number. For 9, the divisibility rule says, the sum of the digits must be divisible by 9. Now, if the sum is perfectly divisible by 9, then we return 9. Say, 99 for example, 9 + 9 = 18 and 1 + 8 = 9. Hence, the rule follows.

But for non-divisible numbers, we will print the remainder which in case is the sum of the digits, since 9 is the largest single digit number. Applying the modulus 9 on that number, we will get the final remainder which is the sum of the digits. Because, the number 9 is the largest single digit number. So it returns the final sum after applying the modulus.

Now, we are checking if the number is non-zero. If not, check for its divisibility with 9. If it is divisible, pass value 9 otherwise number % 9. If it is 0, then simply print 0.

Do you like this program? Let me know through comments.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ Program to print right angled pyramid of numbe... >>
<< How to skip some of the array elements in C++?...