Problem about extract individual digits argolithm

I have an exercise which asks me to write a program that input an integer then output the individual digits of the number and the sum of digits. E.g: 1506 -> 1 5 0 6. I design the algorithm by using two loops. It seems to work fine but when I enter input like 4000, the result is 4 which doesn't meet require of the exercise (must be 4 0 0 0). Similarly, 8030 must be turn to 8 0 3 0 but with my code, the result is 8 0 3. Can anyone help me to solve this problem ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
using namespace std;
int main()
{
	int num, sum, num1, div1, div2;
	sum=0;
	cout<<"Enter a number: ";
	cin>>num;
	if (num<0)
		num=-num;
	num1=0;
	while (num!=0)
	{
	div1=num%10;
	num=num/10;
	num1=num1*10+div1;
	sum=sum+div1;
	}
	cout<<"The individual digits of the number is: ";
	while (num1!=0)
	{
	div2=num1%10;
	num1=num1/10;
	cout<<div2<<" ";
	}
	cout<<"\nThe sum is: "<<sum;
	return 0;
}


My friend advises me to use arrays but up to now, I just have learned some control structures lessons such as if else, while, for. So I can not use that method in my exercise.
Last edited on
Your problem is that inverse of input (num1) for 4000 looks like 4.

What if the first loop would simply calculate how many digits the number has? The second loop would then process that many digits.
Wow, I got it. Finally, it works. Thank you so much.
Topic archived. No new replies allowed.