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 ?
#include<iostream>
usingnamespace 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.