how to find the sum of elements in a stack in cpp

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

  1. Create a stack: Start by creating a stack using the std::stack container class from the C++ Standard Library. The stack should be of the appropriate data type for the elements you want to store.
std::stack<int> myStack;
  1. Push elements into the stack: Use the push() function to add elements to the stack. For example, if you want to add the numbers 1, 2, and 3 to the stack, you would push them in the following way:
myStack.push(1);
myStack.push(2);
myStack.push(3);
  1. Calculate the sum: To find the sum of all elements in the stack, you need to iterate over the stack and add up the values. However, since stacks are LIFO (Last-In-First-Out) data structures, you cannot directly access elements in the middle or at the beginning. Instead, you need to pop elements from the stack until it becomes empty while keeping track of the sum.
int sum = 0;
while (!myStack.empty()) {
    sum += myStack.top();
    myStack.pop();
}
  1. Access the top element and pop: During each iteration, you can access the top element of the stack using the top() function, which returns a reference to the top element. Add the value to the sum variable and then use the pop() function to remove the top element from the stack.

  2. Display the sum: After the loop ends, you will have the sum of all elements in the stack stored in the sum variable. You can then display the sum as needed.

Here's the complete code:

#include <iostream>
#include <stack>

int main() {
    std::stack<int> myStack;
    myStack.push(1);
    myStack.push(2);
    myStack.push(3);

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

    std::cout << "Sum of elements in the stack: " << sum << std::endl;

    return 0;
}

This code creates a stack with three elements (1, 2, and 3), calculates their sum, and then displays the result as "Sum of elements in the stack: 6".