Adding numbers in an int

Hello

If I have a number in an int. Let's say the number is 104. I wanna know how to add these numbers like this 1 + 0 + 4 without human interference.
In order to get 5 instead of 104.

Any help is appreciated.
Step 1: You can extract the leading decimal digit by taking the number modulo 10.
Step 2: You can extract the next digit by dividing the number by 10 and going to step 1, unless the number is 0.

Can you explain more? here is my code
1
2
3
4
5
6
7
8
while (number2 != 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || 11 || 12 || 22) {



        
    }



number2 is the int containing 104
Sure.
Assuming number2 is positive:

Step 1: You can extract the leading decimal digit by taking the number modulo 10.
A number x modulo y is the remainder of x divided by y.
https://en.wikipedia.org/wiki/Modulo_operation
http://en.cppreference.com/w/cpp/language/operator_arithmetic#Multiplicative_operators

In other words, the remainder of 104 mod 10 is 4. The result is the digit in the ones place.
Add that result to the sum.

Step 2:
Divide 104 by 10. Since we're dividing using integers, the fraction is discarded. 104 / 10 is 10. Repeat to step 1, except use the result of the division, 10 instead of 104.

1
2
3
4
5
int acc = 0; // accumulator
while (number2 > 0) { 
  acc     += number2 % 10;
  number2 /= 10;
}
Topic archived. No new replies allowed.