hi.. so we're having this program using an array implementation to a stack, and we were asked to get the sum of all the numbers in the stack.. so here's a portion my code for finding the sum...
1 2 3 4 5 6 7 8 9 10 11 12
//get the sum
while(!num.empty()) {
n2 = num.top();
sum += n2;
num.pop();
}
//display the sum
cout<<"The sum is: "<<sum<<endl;
//the name of the stack here is num
i ran the program and the sum always displays 0, which should be displaying the sum of all the numbers in that stack.. is there something wrong in my code? :)
It's hard to tell what's going on. Please put more code.
I can see 3 possibilities:
1. All elements in the stack are 0.
2. push() isn't working (i.e. there are 0 elements)
3. empty always returns true (regardless of whether stack is actually empty or not)
I personally haven't learned about stacks or worked with them in long time but wouldn't you want to do something like this instead?
1 2 3 4 5
while(!num.empty())
{
sum += num.top();
num.pop();
}
Again I'm not to good with stacks, but otherwise I have no clue why you are getting 0 what you posted works fine for me and gives the correct output...
#include<iostream>
#include<stack>
usingnamespace std;
int main()
{
stack <int> num;
int n;
int sum = 0;
// Always good to use a const variable for your stuff like this.
constint numbers = 5;
cout<<"Enter " << numbers << "numbers."<<endl;
for(int i = 0; i < numbers; ++i)
{
cin>>n;
num.push(n);
}
// Took out the not needed step
while(!num.empty())
{
sum += num.top();
num.pop();
}
cout<<"The sum is: "<< sum <<endl;
return 0;
}