print stack without pop c++

To print the elements of a stack without popping them in C++, you can use a while loop to iterate through the stack until it becomes empty. Here is an example:

#include <iostream>
#include <stack>

int main() {
    std::stack<int> myStack;

    myStack.push(10);
    myStack.push(20);
    myStack.push(30);
    myStack.push(40);
    myStack.push(50);

    while (!myStack.empty()) {
        std::cout << myStack.top() << " ";
        myStack.pop();
    }

    return 0;
}

In the code above, we first include the necessary headers <iostream> and <stack>. Then, we create a stack called myStack to store integers.

We push some elements into the stack using the push() function. In this example, we push the integers 10, 20, 30, 40, and 50.

Next, we enter a while loop that continues until the stack becomes empty. The condition !myStack.empty() checks if the stack is not empty.

Inside the loop, we use the top() function to access the top element of the stack, and cout to print it. The top() function returns a reference to the top element without removing it from the stack.

After printing the top element, we use the pop() function to remove it from the stack.

Finally, we return 0 to indicate successful execution of the program.

When you run this code, the output will be: 50 40 30 20 10. This represents the elements of the stack printed in reverse order, as the last element pushed is the first one to be printed.

Note: It's important to include the necessary headers and use the std namespace to access the stack and stream functions.