Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer in 932, the sum of all its digits is 14.
(Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932/10 = 93.)
Solution:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int number;
int sep1;
int sep2;
int sep3;
int sep4;
int sum;
cout<<"Enter a number between 0 and 1000: ";
cin>>number;
if(number > 0 && number < 1000)
{
sep1 = number % 10;
sep2 = number/10;
if(number >= 100)
{
sep3 = sep2 % 10;
sep4 = sep2/10;
sum = sep1 + sep3 + sep4;
}
else
{
sum = sep1 + sep2;
}
cout<<"Total: "<<sum<<endl;
}
else
{
cout<<"Invalid Number"<<endl;
}
system("pause");
return 0;
}