rajiv mishra - 1 year ago 35

C++ Question

I'm making a program to sum a digits, Have a look into this program:

`#include<iostream>`

using namespace std;

int main(){

int i, j;

int sum=1;

cout<<"Enter your sum: "<<endl;

cin>>i;

while(i>0){

j=i%10;

sum=sum+j;

i=i/10;

}

cout<<"Sum: "<<sum;

cout<<endl;

}

So, as I type into output as

`25`

`7`

But I want to make it in a single digit of every sum, let's say as I type

`147`

`10`

`1`

I know it could be done as:

`while(i>0){`

j=i%10;

sum=sum+j;

i=i/10;

}

cout<<"Sum: "<<sum/10;

and surely it'll give me an output as

`1`

But as I type a number

`185`

`1`

I want that program into which if i type

`185`

Output must suppose to be as

`1+8+5=14`

1+4=5

And output must be

`5`

Answer Source

You can try this:

```
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
if (i == 0 && sum >= 10) // if all the digits of previous number is processed and sum is not a single digit
{
i = sum;
sum = 0;
}
}
```

Note that there is no nested loop!

Do not forget to initialize `sum`

to `0`

instead of `1`

.