C Program to Implement Stack Using Arrays

1. Introduction

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first element to be removed. In this post, we will implement a stack using arrays, covering basic operations like push (to add an element to the stack) and pop (to remove the top element from the stack).

2. Program Overview

In this program, we will:

1. Define the maximum size of the stack.

2. Implement the following stack operations:

- Push: To add an element to the top of the stack.

- Pop: To remove the top element from the stack.

- Peek: To get the top element without removing it.

- Display: To display the elements of the stack.

3. Code Program

#include <stdio.h>
#define MAX_SIZE 10

// Stack and its top element
int stack[MAX_SIZE];
int top = -1;

// Function to push an element to the stack
void push(int value) {
    if (top == MAX_SIZE - 1) {
        printf("Stack Overflow!\n");
        return;
    }
    stack[++top] = value;
}

// Function to pop an element from the stack
int pop() {
    if (top == -1) {
        printf("Stack Underflow!\n");
        return -1;
    }
    return stack[top--];
}

// Function to get the top element of the stack
int peek() {
    if (top == -1) {
        printf("Stack is empty!\n");
        return -1;
    }
    return stack[top];
}

// Function to display the stack
void display() {
    if (top == -1) {
        printf("Stack is empty!\n");
        return;
    }
    for (int i = top; i >= 0; i--) {
        printf("%d ", stack[i]);
    }
    printf("\n");
}

int main() {
    push(10);
    push(20);
    push(30);
    printf("Top element: %d\n", peek());
    display();
    printf("Popped element: %d\n", pop());
    display();
    return 0;
}

Output:

Top element: 30
30 20 10
Popped element: 30
20 10

4. Step By Step Explanation

1. We define a stack array of MAX_SIZE and initialize the top pointer to -1 indicating an empty stack.

2. The push function adds an element to the top of the stack. Before adding, it checks if the stack is already full (Stack Overflow).

3. The pop function removes and returns the top element from the stack. Before removing, it checks if the stack is empty (Stack Underflow).

4. The peek function returns the top element without removing it from the stack. It checks if the stack is empty before proceeding.

5. The display function prints the current elements of the stack from top to bottom.

6. In the main function, we demonstrate pushing elements onto the stack, viewing the top element, popping an element, and displaying the stack.

Comments