Implementing A Stack Using Array - C# Programming Exercise

In this exercise, you need to implement a stack in C#. A stack is a data structure that follows the LIFO (Last In, First Out) principle, meaning the last element to enter is the first one to exit. In this exercise, you will need to create a class for the stack, allowing you to insert elements at the top of the stack and remove elements from the top. The goal of this exercise is to help you understand how stacks work and how to manage them in C#.

In this exercise, you should implement key methods like Push (to add elements), Pop (to remove elements), and Peek (to view the top element without removing it). Additionally, you will need to handle cases like when the stack is empty or full, and how to manage these events to prevent errors.

By completing this exercise, you will have learned how to use stacks in C# and how to apply them in situations where data access follows a "last in, first out" order, such as in reverse processing or tracking application states.

 Category

Dynamic Memory Management

 Exercise

Implementing A Stack Using Array

 Objective

Implementing a stack

 Write Your C# Exercise

// Importing necessary namespace for basic functionalities
using System; // For basic functionalities like Console

// Class that implements a Stack using an array
class Stack
{
    private int[] stackArray; // Array to hold the stack elements
    private int top;          // Index for the top of the stack
    private int capacity;     // Maximum capacity of the stack

    // Constructor to initialize the stack with a given capacity
    public Stack(int capacity)
    {
        this.capacity = capacity;         // Set the stack's maximum capacity
        stackArray = new int[capacity];   // Initialize the array to hold the stack elements
        top = -1;                         // The stack is initially empty, so top is -1
    }

    // Method to add an element to the stack (Push operation)
    public void Push(int element)
    {
        if (top == capacity - 1) // Check if the stack is full
        {
            Console.WriteLine("Stack is full! Cannot push.");
            return;
        }
        stackArray[++top] = element; // Increment top and add the element to the stack
        Console.WriteLine($"Pushed: {element}");
    }

    // Method to remove the top element from the stack (Pop operation)
    public void Pop()
    {
        if (top == -1) // Check if the stack is empty
        {
            Console.WriteLine("Stack is empty! Cannot pop.");
            return;
        }
        int poppedElement = stackArray[top--]; // Get the top element and decrement top
        Console.WriteLine($"Popped: {poppedElement}");
    }

    // Method to display all elements in the stack
    public void DisplayStack()
    {
        if (top == -1) // Check if the stack is empty
        {
            Console.WriteLine("Stack is empty.");
            return;
        }

        Console.WriteLine("Stack contents:");
        for (int i = top; i >= 0; i--) // Display elements from top to bottom
        {
            Console.WriteLine(stackArray[i]);
        }
    }
}

// Main program to demonstrate the Stack functionality
class Program
{
    static void Main(string[] args)
    {
        // Create a stack with a capacity of 5
        Stack stack = new Stack(5);

        // Menu to allow user to interact with the stack
        while (true)
        {
            Console.WriteLine("\nMenu:");
            Console.WriteLine("1. Push an element");
            Console.WriteLine("2. Pop an element");
            Console.WriteLine("3. Display the stack");
            Console.WriteLine("4. Exit");
            Console.Write("Enter your choice: ");
            string choice = Console.ReadLine();

            if (choice == "1")
            {
                // Prompt user to enter an element to push onto the stack
                Console.Write("Enter an element to push: ");
                int element = int.Parse(Console.ReadLine());
                stack.Push(element); // Push the element onto the stack
            }
            else if (choice == "2")
            {
                // Pop an element from the stack
                stack.Pop(); // Pop the top element from the stack
            }
            else if (choice == "3")
            {
                // Display the current stack
                stack.DisplayStack(); // Show the current elements in the stack
            }
            else if (choice == "4")
            {
                // Exit the program
                break;
            }
            else
            {
                // Invalid choice
                Console.WriteLine("Invalid choice. Please try again.");
            }
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of Dynamic Memory Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Queue Collections

    In this exercise, you need to create a string queue using the Queue class that already exists in the DotNet platform. The Queue class is an implementation of t...

  •  Queue Stack Reverse Polish Notation

    In this exercise, you need to create a program that reads a Reverse Polish Notation (RPN) expression from a text file, such as: 3 4 6 5 - + * 6 + (Result 21). In...

  •  ArrayList

    In this exercise, you need to create a string list using the ArrayList class that already exists in the .NET platform. The ArrayList class allows storing items...

  •  ArrayList duplicate a text file

    In this exercise, you need to create a program that reads from a text file and stores it to another text file by reversing the order of the lines. This exercise will ...

  •  Unlimited sum

    In this exercise, you need to create a program that allows the user to enter an unlimited amount of numbers. Besides entering numbers, the program should allow the user to e...

  •  ArrayList - Text file reader

    In this exercise, you need to create a basic text file reader that displays 21 lines of text and allows the user to navigate using the up and down arrow keys, and exit using...