How did this give me the sum of the numbers?

Jun 3, 2012 at 7:55am
I earlier posted a topic to help me do this but i didnt have a code. I have finally completed this with a help of a local friend but i dont understand the logic of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
  int number;
  int sum=0;
  
  cout << "Enter an integer:";
  cin >> number;
  
  while(number>0){
  sum=sum+number%10; // sum + 2.1%10 is supposedly the output which is 3? How so
  number=number/10; // number=21/10 which is 2.1
}
  cout << "The sum is" << sum << endl;
    
    system("PAUSE");
    return (0);
}


when I run the code if I input integer for example 21 it will give me 3 as a sum which is correct.

I dont understand how the sum will be 3 if its (0=sum+2.1%10) because 2.1%10 doesnt equal to 3 or does it??
Jun 3, 2012 at 7:57am
number=number/10; // number=21/10 which is 2.1

This actually won't be 2.1. Since you have two integers (number and 10), you are doing integer division so the result is truncated, and you get 2.
Jun 3, 2012 at 8:03am
oh I see but then how is the sum 3? if the result is 2 it is (sum=sum+2%10)

which i just tested and 2%10 is 2 so (sum=0+2) which (sum=2) but then how is it equal to 3
Jun 3, 2012 at 8:36am
Number starts at 21 so the first time through the loop you have:

sum += num % 10; //sum += 2
number /= 10; //num is now 1

Next loop, num is > than 1 so you are ok

...
Topic archived. No new replies allowed.