C# program to stack with Push & Pop operation
In C#, you can use the built-in System.Collections.Generic.Stack class from the .NET Framework to implement a stack with Push and Pop operations. Here's an example program:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Push(4);
stack.Push(5);
Console.WriteLine("Popped: " + stack.Pop()); // Pop and print the top item
Console.WriteLine("Popped: " + stack.Pop());
}
}
In this program, we create an instance of the generic Stack class from the System.Collections.Generic namespace. We use the Push method to add elements to the stack, and the Pop method to retrieve and remove elements from the top of the stack.
The Stack class has the following methods:
-
Push(T item): Pushes an item onto the stack.
-
Pop(): Pops and returns the top item from the stack.
In the Main method, we create a Stack object. We then push some integers onto the stack and subsequently pop the top items and print them to the console.
Note that this implementation uses the built-in Stack class, which internally uses an array to store the stack elements.