### Problem with modulus division

Can someone help me figure out how to use my modulus division for the thousands and hundreds within my code I think they're wrong.

#include <iostream>
using namespace std;
int main()
{
int num, ones, tens, hundreds, thousands;
int sum;
cout<<"enter an integer: ";
cin>>num;
while ((num<0)&&(num<=10000))
{
cout<<"enter an integer"<<endl;
cin>> num;
}
if (num >= 0 && num <= 9)
{
sum = num;
}
if (num >= 10 && num <= 99)
{
tens = ((num - (num%10)) / 10);
ones = (num - (tens * 10));
sum = tens + ones;
}
if (num >= 100 && num <= 999)
{
hundreds = ((num - (num%10)) / 100);
tens = ((num - (num%10)) / 10);
ones = (num - (tens * 10));
sum = hundreds + tens + ones;
}
if (num >= 1000 && num <= 9999)
{
thousands = ((num - (num%10)) / 1000);
hundreds = ((num - (num%10)) / 100);
tens = ((num - (num%10)) / 10);
ones = (num - (tens * 10));
sum = thousands + hundreds + tens + ones;
}
cout << "The sum of the digits is: " << sum << endl;
system("pause");
return(0);
}
Last edited on
You have an extra parentheses here:

tens = (num - (num%10)) / 10);
If you have any insight into modulus division can you please tell me what I've done wrong for my hundreds and thousands.
if (num >= 100 && num <= 999)
{
hundreds = ((num - (num%10)) / 100);

tens = ((num - (num%10)) / 10);
ones = (num - (tens * 10));
sum = hundreds + tens + ones;
}
if (num >= 1000 && num <= 9999)
{
thousands = ((num - (num%10)) / 1000);
hundreds = ((num - (num%10)) / 100);

tens = ((num - (num%10)) / 10);
ones = (num - (tens * 10));
sum = thousands + hundreds + tens + ones;
}
Using that general style of code, there isn't even a need for the modulus operator.

For example, a 3-digit value would work like this:
 ``1234567`` `````` if (num >= 100 && num <= 999) { hundreds = num / 100; tens = (num - hundreds*100) / 10; ones = num - hundreds*100 - tens*10; sum = hundreds + tens + ones; }``````

But that's doing far too much work.
You could do the whole thing using a loop

 ``123456789`` `````` int sum=0; while (num > 0) { int digit = num%10; sum += digit; num/=10; } cout << "The sum of the digits is: " << sum << endl;``````

Thank you for the help I got my program to work properly two ways now. It's much appreciated help.
Actually, in the first version, there are separate cases and lots of "if" statements. You could probably just use the last version `if (num >= 1000 && num <= 9999)` even if the number has fewer than four digits it should still work. (Some values will of course be zero).