Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I could use some help on this Write a program that prompts the user to input an

ID: 3618295 • Letter: I

Question

I could use some help on this

Write a program that prompts the user to input an integer and thenoutputs both the individual digits of the number and the sum of thedigits. For example, it should output the individual digits of 3456as 3 4 5 6, [...], output 4000 as
4 0 0 0, and the individual digits of -2345 as 2 3 4 5.

Here's my code so far

#include <iostream>
using namespace std;

int main (){
    int num, n;
    int sum = 0;
    int rev = 0;
    cout << "Enter any integer: ";
    cin >> num;
    if (num < 0)
        num*=-1;
    while (num > 0){
        rev *= 10;
        rev += (num % 10);
        num /= 10;
    }
    cout << "The digits are: ";
    while (rev > 0){
        n = rev % 10;
        rev = rev/10;
        sum += n;
        cout << n << "";
    }
    cout << endl << "Sum of digits: "<< sum << endl;
}


My problem is that when I enter an integer with trailing zeroessuch as 4000, I only get the digit 4. I'm thinking it's because Iset my num and rev so it won't operate with zero, but when I do, ofcourse it'll just loop forever. Can anyone please help me withthis? Am I going about this problem the right way?

Explanation / Answer

#include <iostream> using namespace std; int main (){    int num,n;    int sum = 0;    cout << "Enter any integer: ";    cin >> num;    if (num < 0)    num*=-1;    cout << "The digits are: ";    while (num >9){    n=num%10;    num=num/10;    cout << n << "";    sum+=n;    } n=num%10;    cout << n << " ";    sum+=n;
   cout << endl << "Sum of digits:" << sum << endl;
}

However digits are displayed in reverse.
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote