sum of stack c++

To calculate the sum of a stack in C++, you can follow these steps:

  1. Create a stack: Start by creating an empty stack. In C++, you can use the std::stack container from the Standard Template Library (STL). Include the <stack> header to use this container.

cpp #include <stack> // ... std::stack<int> myStack;

  1. Push elements onto the stack: Add elements to the stack using the push() function. For example, if you want to add the numbers 5, 10, and 15 to the stack, you can use the push() function three times.

cpp myStack.push(5); myStack.push(10); myStack.push(15);

  1. Calculate the sum: Iterate over the elements in the stack and add them together. To do this, you need to pop each element from the stack and accumulate their values.

```cpp int sum = 0;

while (!myStack.empty()) { sum += myStack.top(); myStack.pop(); } ```

The top() function retrieves the value of the top element in the stack, and pop() removes the top element from the stack.

  1. Print the sum: Finally, you can print the calculated sum using the std::cout stream.

cpp std::cout << "Sum of stack: " << sum << std::endl;

Remember to include the <iostream> header to use the std::cout stream.

Here is the complete example:

#include <iostream>
#include <stack>

int main() {
    std::stack<int> myStack;
    myStack.push(5);
    myStack.push(10);
    myStack.push(15);

    int sum = 0;

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

    std::cout << "Sum of stack: " << sum << std::endl;

    return 0;
}

This code will output:

Sum of stack: 30

Let me know if you have any further questions.