Write a C++ program for Finding sum of digits of a number until sum becomes single digit.
Answers
Answer:
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 co de.
________________________
#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;
<< endl;}int main()
{
int n = 4543;
findTheSingleDigit(n);
return 0;
}
_________________________
️️
️️
• Output
you execute the above program, then you will get the following result.
______________
_______________
⭐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.