Click here to Skip to main content
15,120,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So, I have a small coding problem that has one minor thing that needs fixing
Basically you prompt the user to input an integer, and it outputs the sum as well as the individual digits.

So, it goes like this. If you input 123 it should output "1 2 3" and return a sum of 6
The problem is the code will output the numbers in reverse. I.e if I input 789 it will output 9 8 7. The sum output works just fine however. Just that little thing I need help with. The code's down below. I'm looking for another perspective on it :)
C++
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    //hold the number input, number and sum
    int num_input, sum, num, pwr;

    cout << "Enter a number" << endl;
    cin >> num_input;

    
    num_input = abs(num_input); //handle the negative numbers
    sum = 0;

    do
    {

        num = num_input % 10;
        sum += num;
        num_input = num_input / 10;
        cout << num << " ";

    } while (num_input > 0);

    cout << "The sum of the numbers are: " << sum << endl;
}


What I have tried:

Using arrays, while loops, for loops, vectors
Posted
Updated 5-Oct-21 18:48pm
Comments
Afzaal Ahmad Zeeshan 5-Oct-21 18:51pm
   
One simple way would be to print it in the reverse order; use stack?

If you know how to use std::vector you should also know how to reverse iterate over it using rbegin() and rend(). Put the digits of the number in a vector<int>, then use a for() loop with reverse iterators to print the digits. Or, you could use reverse() from the algorithms header on the vector. Or convert the number to an string, reverse it, and print the chars one by one.
   
v2
Quote:
The problem is the code will output the numbers in reverse. I.e if I input 789 it will output 9 8 7.

The modulo (%) operator gets digits from right to left but you want digits from left to right.
If you handle input as an integer:
- To reverse the list of digits, you can use an array, a stack, a vector ...
- You can also use a recursive function to treat the input.
:You can also handle the input as a string
- and treat each char of the string individually.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900