help with a stack..

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? :)

thanks in advance ^^
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)
here's the whole version... hope this helps...

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>
#include<stack>

using namespace std;

int main()
{
	stack <int> num;
	int i, n;
	int sum = 0, n2;

	cout<<"Enter 10 numbers:"<<endl;
		for(i=0;i<10;i++) {
			cin>>n;
			num.push(n);
		}


		while(!num.empty()) {
			n2 = num.top();
			sum += n2;
			num.pop();
		}

		cout<<"The sum is: "<<sum<<endl;

		system("pause");
}
closed account (3qX21hU5)
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...

Here is some ways to clean it up a bit though

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
29
30
31
#include<iostream>
#include<stack>

using namespace std;

int main()
{
    stack <int> num;
    int n;
    int sum = 0;

    // Always good to use a const variable for your stuff like this.
    const int 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;
}
Last edited on
Works fine for me...?

http://s12.postimage.org/rjdka00q5/stack.png

@Zereo: You can to shorten it a bit but it'd do exactly the same thing.
Last edited on
@iHutch105... I always get this one...

http://64.19.142.12/s20.postimage.org/smoho7x3d/image.jpg

:(
just gonna update this.. need help on this :) thanks..
closed account (3qX21hU5)
What do you need help on your link doesn't work for me and the code you posted compiles fine for me
i always get zero as the sum of all the numbers i entered...
The code you showed is correct. I executed it at www.ideone.com and got result 55.
Topic archived. No new replies allowed.