Print element of stack

How to print element of the stack without popping element from the stack…

In the following code we are deleting element from stack while printing element of stack

void traverse(stacks)
{
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
}

Suppose the stack is like:
1
2
3
4
5
from top to down, s.top() has 1 so when you print s.top() it prints 1, then it does s.pop() it pops 1, the stack is now like:
2
3
4
5
now the s.top() is 2, we print s.top() and s.pop() so it removes 2, and leaves the stack like:
3
4
5
ans so on, till 5 gets popped and stack gets empty and loop stops

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.