naustin288
naustin288

Reputation: 13

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

For Example: Input: 982

Outputs: 9 8 2 Your Total sum is: 19

I see people using input_number % 10 in a loop and then input_number / 10 but I still do not get it. If i did 982 % 10 I would get 2 and then they add it to the sum which is 0 + 2 = 2 and how would that get 19???? and then the input number which is 982/10 is equal to 9.82 how does lead me to my solution of 19?? I am just super confused can someone please explain it to me and try to work out the problem and make it into a simple solution. I appreciate it and try to use the basic stuff like including namespace std and then not using arrays just loops and simple math equations thank you.

Upvotes: 0

Views: 8927

Answers (2)

lenik
lenik

Reputation: 23508

You should input the number as a characters, that you convert into the digits and then individual numbers, that are easy to add or print or whatever. Avoid complicated math when you can totally live without it.

std::string str;
std::cin >> str;

int sum = 0;
for( int i=0; i<str.length(); i++) {
    if( isdigit(str[i]) ) {
        std::cout << str[i] << " ";
        sum += int(str[i] - '0')  // convert a char to int
    }
}
std::cout << std::endl;
std::cout << "Total sum: " << sum << std::endl;

or something like that. Haven't programmed in C++ for a while, there might be minor mistakes in the code, but you get the general idea.

Upvotes: 1

Akshay Jain
Akshay Jain

Reputation: 96

int n,sum=0;
cin>>n;
while(n!=0)
{
  sum=sum+(n%10);
  n=n/10;   
}
/*
Since your n is an integer it will drop the value after decimal. 
Therefore, 982 will run as
Iteration 1 n=982
sum=2
n=982/10=98
Iteration 2
sum=2+(98)%10 = 10
n=98/10= 9
Finaly in iteration 3 
n=9/10=0 hence loop will terminate and sum be 19*/

Upvotes: 2

Related Questions