×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

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

In this program, we are going to implement logic to find sum of digits until the number is a single digits in C++ programming language.
Submitted by Abhishek Pathak, on October 05, 2017 [Last updated : February 26, 2023]

Problem statement

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

Calculating the sum of the digits of a number until the number is a single digit

Tricky programs are what make up programmers lunch. This is a famous interview question where we have to keep calculate the sum of the digits of the number until the number becomes a single digit number.

For example, the number is 147. Adding the digits we get 12. Now again add the digits of this number, which is 3. Therefore 3 is the result. Sounds interesting? Yes it is and while you might think the answer will comprise of multiple loops, hold on.

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

#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.

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.