Were supposed to type in a number and the program should output the numbers separately and display their sum. For example; if I type in 256, the computer should print out 2 5 6 and sum=13. Similarly if I type -256, the computer should print out 2 5 6 and sum=13. The input does not always have to be 3 digits.
I've been trying to solve this problem for the past 4 days.
#include <iostream>
usingnamespace std;
int main()
{
longlong num=0,number=0;
int counter=0;
cin>>num;
number=num;
while(num%10)
{
num=num/10;
counter++;
}
longlong array[counter];
int sum=0;
int num1=0;
for(int count=counter;count>0;count--)
{
array[counter]=number%10;
number=number/10;
cout<<array[counter]<<" ";
sum+=array[counter];
}
cout<<endl;
cout<<"Sum is : "<<sum;
return 0;
}
If i cout the the numbers inside the loop, they print out backward. If I do that outside the loop, the answer is nowhere near accurate.
The first loop is counting the amount of digits I have entered. And then I keep that counter as the capacity of the array.
And I'm sure that this code will print out -2345 as -2 -3 -4 -5
I'm using Visual Studio, and it may just be something with that, but it doesn't like having an array's size be a variable. You may want to change that.
Getting that out of the way, the problems are in your for loop.
Problem 1: You use counter instead of count as accessors for your array.
Problem 2: You need to print the array values in the opposite order that you put them in. So lines 25 & 26 should be in their own for loop, which goes the opposite direction. (After the first for loop concludes.)
I think that it's the same thing if we use counter instead count.
It is not the same thing. If you use counter (an unchanging value), each time you loop in the for loop, you're overwriting the previous value. Second, counter is actually outside the range of array (ranges from 0 to counter - 1). This also means that your for needs to start at (counter-1) & go to (count>=0).
Nice catch! It will not work if any of the digits are 0. So, you need a second condition where it checks if it's zero. Use while(num%10 || num != 0)
I don't particularly like the idea of a fixed length array here. What if the number is more than 30 digits long? What if it is one digit? That's a lot of wasted space.
As far as I'm aware, a variable length array isn't currently standard C++. For that reason, and to keep the code simple I'd just do all the extraction of digits, getting their sum, and storing in the array in a single loop.
Then another loop to display the output.
I'm trying not to say too much as I think I may be distracting rather than helping.
I wrote the code again and I its working perfectly fine now. I changed the names of the variables. And tallyman, I understood what you were trying to say.