Stack.Pop() method with example in C#

C# Stack.Pop() strategy: Here, we will find out about the Pop() technique for Stack class in C#.

C# Stack.Pop() strategy

Stack.Pop() strategy is utilized to expel an item from the highest point of the stack. The technique expels and restores the article from the top.

Syntax:

    Object Stack.Pop();

Parameters: None

Return value: Object – it restores the items to be expelled from the top.

Example:

    declare and initialize a stack:
    Stack stk = new Stack();

    insertting elements:
    stk.Push(100);
    stk.Push(200);
    stk.Push(300);
    stk.Push(400);
    stk.Push(500);

    popping stack elements:
    stk.Pop();
    stk.Pop();
    stk.Pop();
    
    Output:
    200 100

C# example to expel an item from the stack utilizing Stack.Pop() technique:

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print stack elements
        static void printStack(Stack s)
        {
            foreach (Object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //declare and initialize a stack
            Stack stk = new Stack();

            //insertting elements
            stk.Push(100);
            stk.Push(200);
            stk.Push(300);
            stk.Push(400);
            stk.Push(500);

            //printing stack elements
            Console.WriteLine("Stack elements before popping are...");
            printStack(stk);

            //popping stack elements
            object item = 0;
            item = stk.Pop();
            Console.WriteLine(item + " is popped");
            item = stk.Pop();
            Console.WriteLine(item + " is popped");
            item = stk.Pop();
            Console.WriteLine(item + " is popped");

            //printing stack elements
            Console.WriteLine("Stack elements after popping are...");
            printStack(stk);

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output:

Stack elements before popping are...
500 400 300 200 100
500 is popped
400 is popped
300 is popped
Stack elements after popping are...
200 100

Leave a Comment

error: Alert: Content is protected!!