I'm working on an assignment for Computer Science 121. The assignment is to write a program that prompts a user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6 and the sum as 18. I can't seem to get it working properly; I think my algorithm is wrong. I tried rewriting the algorithm, but I keep getting stuck in it. Can someone help me out? Here's what I have so far:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int num, num2, sum = 0, dig;
cout << "Please enter a number" << endl;
cin >> num;
if(num < 0)
num = -num;
num2 = num;
dig = num;
do
{
do
{
dig = dig / 10;
}
while (dig >= 10);
cout << dig << " ";
if (num > 100)
num = num - (100*(num/100));
else
num = num - (10*(num/10));
sum = sum + num2 % 10;
num2 = num2 / 10;
dig = num;
}
while (num2 > 0);
cout << endl;
cout << "The sum of the digits is " << sum << endl;
return 0;
}
Thank you for the help :)