rajiv mishra rajiv mishra - 1 month ago 7
C++ Question

How to make sum in a single digit?

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
it'll give me as an output
7
.

But I want to make it in a single digit of every sum, let's say as I type
147
. It gives me an output
10
but I want
1
as an output.

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
it gives me an output
1
.. But I want the whole sum of digit.

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
.. So please help me to resolve this kind of issue.

Answer

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.

Comments