0
0
CsharpProgramBeginner · 2 min read

C# Program to Implement Stack Using Array

You can implement a stack in C# using an array by creating a class with an array and an integer to track the top index, then use Push to add, Pop to remove, and Display to show elements; for example, define int[] stack = new int[size] and int top = -1 to start.
📋

Examples

InputPush 10, Push 20, Pop, Display
OutputPushed 10 Pushed 20 Popped 20 Stack elements: 10
InputPop on empty stack
OutputStack Underflow
InputPush 5, Push 15, Push 25, Display
OutputPushed 5 Pushed 15 Pushed 25 Stack elements: 5 15 25
🧠

How to Think About It

To implement a stack using an array, think of the array as a container with a fixed size. Use a variable called top to keep track of the last added element's position. When you add (push) an item, increase top and store the item there. When you remove (pop) an item, take the item at top and decrease top. Check for overflow when pushing and underflow when popping.
📐

Algorithm

1
Initialize an array with a fixed size and set top to -1.
2
To push an element, check if top is less than size - 1; if yes, increment top and insert the element at top.
3
To pop an element, check if top is -1; if not, return the element at top and decrement top.
4
To display, print all elements from index 0 to top.
💻

Code

csharp
using System;
class Stack {
    private int[] stack;
    private int top;
    private int size;

    public Stack(int size) {
        this.size = size;
        stack = new int[size];
        top = -1;
    }

    public void Push(int item) {
        if (top == size - 1) {
            Console.WriteLine("Stack Overflow");
            return;
        }
        stack[++top] = item;
        Console.WriteLine($"Pushed {item}");
    }

    public void Pop() {
        if (top == -1) {
            Console.WriteLine("Stack Underflow");
            return;
        }
        Console.WriteLine($"Popped {stack[top--]}");
    }

    public void Display() {
        if (top == -1) {
            Console.WriteLine("Stack is empty");
            return;
        }
        Console.Write("Stack elements: ");
        for (int i = 0; i <= top; i++) {
            Console.Write(stack[i] + " ");
        }
        Console.WriteLine();
    }
}

class Program {
    static void Main() {
        Stack s = new Stack(3);
        s.Push(10);
        s.Push(20);
        s.Pop();
        s.Display();
    }
}
Output
Pushed 10 Pushed 20 Popped 20 Stack elements: 10
🔍

Dry Run

Let's trace pushing 10, pushing 20, popping, and displaying the stack.

1

Initialize stack

stack = [_, _, _], top = -1

2

Push 10

top increments to 0, stack[0] = 10

3

Push 20

top increments to 1, stack[1] = 20

4

Pop

Return stack[1] = 20, top decrements to 0

5

Display

Print stack elements from 0 to top: 10

OperationtopStack contents
Initialize-1[]
Push 100[10, _, _]
Push 201[10, 20, _]
Pop0[10, 20, _]
Display0[10, 20, _]
💡

Why This Works

Step 1: Using an array and top index

The array stores stack elements, and top tracks the last added element's position.

Step 2: Push operation

Increase top and place the new element there, checking for overflow to avoid errors.

Step 3: Pop operation

Return the element at top and decrease top, checking for underflow to avoid removing from empty stack.

🔄

Alternative Approaches

Using List<T> instead of array
csharp
using System;
using System.Collections.Generic;
class StackList {
    private List<int> stack = new List<int>();
    private int size;

    public StackList(int size) {
        this.size = size;
    }

    public void Push(int item) {
        if (stack.Count == size) {
            Console.WriteLine("Stack Overflow");
            return;
        }
        stack.Add(item);
        Console.WriteLine($"Pushed {item}");
    }

    public void Pop() {
        if (stack.Count == 0) {
            Console.WriteLine("Stack Underflow");
            return;
        }
        int item = stack[stack.Count - 1];
        stack.RemoveAt(stack.Count - 1);
        Console.WriteLine($"Popped {item}");
    }

    public void Display() {
        if (stack.Count == 0) {
            Console.WriteLine("Stack is empty");
            return;
        }
        Console.Write("Stack elements: ");
        foreach (var item in stack) {
            Console.Write(item + " ");
        }
        Console.WriteLine();
    }
}

class Program {
    static void Main() {
        StackList s = new StackList(3);
        s.Push(5);
        s.Push(15);
        s.Pop();
        s.Display();
    }
}
This approach uses dynamic list resizing but still limits size; easier to manage but slightly more overhead.
Using Linked List for stack
csharp
using System;
class Node {
    public int data;
    public Node next;
    public Node(int data) { this.data = data; next = null; }
}
class StackLinkedList {
    private Node top;

    public StackLinkedList() {
        top = null;
    }

    public void Push(int item) {
        Node newNode = new Node(item);
        newNode.next = top;
        top = newNode;
        Console.WriteLine($"Pushed {item}");
    }

    public void Pop() {
        if (top == null) {
            Console.WriteLine("Stack Underflow");
            return;
        }
        Console.WriteLine($"Popped {top.data}");
        top = top.next;
    }

    public void Display() {
        if (top == null) {
            Console.WriteLine("Stack is empty");
            return;
        }
        Console.Write("Stack elements: ");
        Node current = top;
        while (current != null) {
            Console.Write(current.data + " ");
            current = current.next;
        }
        Console.WriteLine();
    }
}

class Program {
    static void Main() {
        StackLinkedList s = new StackLinkedList();
        s.Push(7);
        s.Push(14);
        s.Pop();
        s.Display();
    }
}
Linked list allows dynamic size without fixed limit but uses more memory per element.

Complexity: O(1) time, O(n) space

Time Complexity

Push and pop operations take constant time O(1) because they only update the top index and array element.

Space Complexity

The stack uses O(n) space where n is the size of the array allocated for the stack.

Which Approach is Fastest?

Array-based stack is fastest for fixed size due to direct indexing; linked list is flexible but uses more memory and slightly more overhead.

ApproachTimeSpaceBest For
Array-based StackO(1)O(n)Fixed size, fast access
List based StackO(1)O(n)Dynamic size with some overhead
Linked List StackO(1)O(n)Dynamic size, no fixed limit
💡
Always check for stack overflow before pushing and underflow before popping to avoid errors.
⚠️
Beginners often forget to update the top index correctly, causing incorrect push or pop behavior.