

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Digital Root (repeated digital sum) of the given large integer in C++ Program
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.
#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.
- Related Questions & Answers
- Digital root sort algorithm JavaScript
- C++ Program to find Numbers in a Range with Given Digital Root
- Difference Between Digital Signature and Digital Certificate
- What is digital certificate and digital signature?
- How does the IPsec use digital certificates and digital signatures?
- Digital Subscriber Lines
- Digital Integrated Circuits
- Find Nth positive number whose digital root is X in C++
- Opportunities in Digital India
- Digital Read in Arduino
- What are the application of Digital Watermarking?
- Print a number containing K digits with digital root D in C++
- Analog & Digital Multimeter
- What is Digital Electronics?
- Bitcoins – The New Digital Currency!