title: How to pop all values from a stack and push them back as the sum of all the values?
body: <p>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. </p>
  
  <p>I've tried adding a loop to popping two values and pushing the result back. This is what I have in mind</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>void MathStack::addAll()
  {
      int num = 0,num2 = 0, sum = 0;
  
      while(!isEmpty())
      {
      //Pop the first two values off the stack.
      pop(num);
      cout &lt;&lt; "Popping " &lt;&lt; num &lt;&lt; "\n";
      pop(num2);
      cout &lt;&lt; "Popping " &lt;&lt; num2 &lt;&lt; "\n";
  
      //Add the two values, store in sum.
      sum = num + num2;
      cout &lt;&lt; "Sum is " &lt;&lt; sum;
      //Push sum back onto the stack.
      push(sum);
      num =0;
      num2 = 0;
      }
  
  
  }
  </code></pre>
  
  <p>Any suggestions? </p>