Implementation of Stack in C

Subject: DataStructures Through C

Contributed By: Nunugoppula Ajay

Created At: April 4, 2025

Question:


C Program for Implementing a stack data structure and its operations

Explanation Video:

Custom Image

Explanation:

What is a Stack?

stack is a linear data structure that follows the LIFO (Last In, First Out) principle. This means the last element added to the stack is the first one to be removed. It is commonly used in scenarios like function call management, undo operations in editors, and expression evaluation.

Stack Data Structure

Key Operations on Stack Data Structure

Stack Data Structure Operations
  1. Push: Adds an element to the top of the stack.

  2. Pop: Removes and returns the top element of the stack.

  3. Peek: Retrieves the top element without removing it.

  4. IsEmpty: Checks if the stack is empty.

  5. IsFull: Checks if the stack is full (in case of a fixed-size stack).

C Program for Implementation of  Stack:

This program implements a stack using an array in C. Below are the key components:

1. Global Variables

  • stack[MAX]: Array to store stack elements.
  • top: Tracks the index of the topmost element in the stack. Initialized to -1 to indicate an empty stack.

2. Functions

  • push(int value): Adds an element to the top of the stack.
    • Checks for overflow (top == MAX-1).
  • pop(): Removes and returns the top element.
    • Checks for underflow (top == -1).
  • peek(): Displays the top element without removing it.
    • Checks if the stack is empty.
  • display(): Prints all elements in the stack from bottom to top.

3. Main Function

  • Accepts initial elements for the stack.
  • Provides a menu-driven interface for performing operations like push, pop, peek, and display.

4. Edge Cases Handled

  • Stack Overflow: Prevents adding elements when top == MAX-1.
  • Stack Underflow: Prevents removing or peeking when top == -1.
  • Empty Stack: Displays appropriate messages when attempting operations on an empty stack.

This implementation is simple and efficient for basic stack operations using a fixed-size array.

Source Code:
#include <stdio.h>
#define MAX 100

int stack[MAX];
int top = -1;

// Push an element onto the stack
void push(int value) {
    if (top == MAX - 1) {
        printf("\nStack Overflow");
    } else {
        stack[++top] = value;
    }
}

// Pop an element from the stack
int pop() {
    if (top == -1) {
        printf("\nStack Underflow");
        return -1;
    } else {
        return stack[top--];
    }
}

// Peek at the top element of the stack
void peek() {
    if (top == -1) {
        printf("\nStack is Empty");
    } else {
        printf("\nTop Element is: %d", stack[top]);
    }
}

// Display all elements in the stack
void display() {
    if (top == -1) {
        printf("\nStack is Empty");
    } else {
        printf("\nStack Elements:\n");
        for (int i = 0; i <= top; i++) {
            printf("%d ", stack[i]);
        }
        printf("\n");
    }
}

int main() {
    int n, value, choice, popped_value;

    // Initial input for stack elements
    printf("Enter the number of elements to add: ");
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        printf("Enter Value-%d: ", i + 1);
        scanf("%d", &value);
        push(value);
    }

    // Menu-driven program for stack operations
    while (1) {
        printf("\n----------------------");
        printf("\n\nStack Operations:\n");
        printf("1. Push\n");
        printf("2. Pop\n");
        printf("3. Peek\n");
        printf("4. Display\n");
        printf("5. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        printf("\n----------------------");

        switch (choice) {
            case 1:
                printf("\nEnter Value: ");
                scanf("%d", &value);
                push(value);
                break;
            case 2:
                popped_value = pop();
                if (popped_value != -1) {
                    printf("\nPopped: %d", popped_value);
                }
                break;
            case 3:
                peek();
                break;
            case 4:
                display();
                break;
            case 5:
                printf("\nExiting program...");
                return 0;
            default:
                printf("\nEnter a Valid Choice...");
        }
    }
}
Output:
Enter the number of elements to add: 3
Enter Value-1: 10
Enter Value-2: 20
Enter Value-3: 30

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4

Stack Elements:
10 20 30 

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3

Top Element is: 30

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2

Popped: 30

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4

Stack Elements:
10 20 

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1

Enter Value: 40

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4

Stack Elements:
10 20 40 

----------------------
Stack Operations:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 5

Exiting program...
Share this Article & Support Us:
Status
printf('Loading...');