# C++ program to find sum of digits of a number until sum becomes single digit

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this article, we will be discussing a program to find the sum of digits of a number until the sum itself becomes a single digit and cannot be done summation of further.

For example, take the case of a number 14520. Adding the digits of this number we get 1 + 4 + 5 + 2 + 0 = 12. Since this is not a single digit number, we would further add the digits of the number received. Adding them we get, 1 + 2 = 3.

Now, 3 is the final answer because it is a single digit number itself and its digits cannot be added further.

To solve this, we would use the approach that the sum of digits of a number divisible by 9 is equal to 9 only. For the numbers that are not divisible by 9, we can divide them by 9 so as to get the remaining digit which would be the final sum of the given number.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
//function to check the divisibility by 9
int sum_digits(int n) {
if (n == 0)
return 0;
else if (n%9 == 0)
return 9;
else
return (n%9);
}
int main() {
int x = 14520;
cout<<sum_digits(x)<<endl;
return 0;
}

## Output

3