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.

 Live Demo

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

 Live Demo

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

Updated on: 29-Dec-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements