Greetings Stack Overflow community. I’m trying to make a function that can pop all the values in a stack, add them and then push them back. I’ve so far been successful in adding, subtracting, dividing and multiplying two values by just popping them twice to local variables, performing the operation and then pushing back the completed value. But to add all I would require to pop from the stack until its empty.
I’ve tried adding a loop to popping two values and pushing the result back. This is what I have in mind
push these numbers 1 , 2 , 3, 4 ,5
pop 5
pop 4
add 5 + 4 = 9
push 9
stack (1,2,3,4,9)
pop 9
pop 4
add 9+4 = 13
push 13
and so on. I’ve tried using the isEmpty function for the loop and trying to make it that it stops when one of the values is not NULL. But I have no idea how to stop or start the loop so it keeps going until its empty. Here is what I have written.
void MathStack::addAll()
{
int num = 0,num2 = 0, sum = 0;
while(!isEmpty())
{
//Pop the first two values off the stack.
pop(num);
cout << "Popping " << num << "\n";
pop(num2);
cout << "Popping " << num2 << "\n";
//Add the two values, store in sum.
sum = num + num2;
cout << "Sum is " << sum;
//Push sum back onto the stack.
push(sum);
num =0;
num2 = 0;
}
}
Any suggestions?
There is no reason to push the intermediate sum back onto the stack. Just keep the sum in a local, and pop the values off of the stack one at a time: