# Digital Root (repeated digital sum) of the given large integer in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to find the digital root of a given number.

The digital root is the sum of a number of digits (until the sum of the digits becomes a single digit).

We are given an integer in string format. And we have to find the sum of the digits repeatedly until the sum becomes a single digit.

Let's see the steps to solve the problem.

• Initialize an integer in the string format.

• Iterate through the number and add each digit to the sum variable.

• If the sum is 0, then print 0.

• Else if the sum is divisible by 9, then the answer is 9.

• Else the answer is sum modulo 9.

## Example

Let's see the code.

Live Demo

#include<bits/stdc++.h>
using namespace std;
int digitalRoot(string n) {
int digitsSum = 0;
for (int i = 0; i < n.length(); i++) {
digitsSum += n[i] - '0';
}
if (digitsSum == 0) {
return 0;
}
return digitsSum % 9 == 0 ? 9 : digitsSum % 9;
}
int main() {
string n = "12345";
cout << digitalRoot(n) << endl;
return 0;
}

## Output

If you run the above code, then you will get the following result.

6

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Published on 27-Jan-2021 12:39:47