C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Stack Using Array

C Program: Stack using array

C

#include <stdio.h>

#include <stdlib.h>

 

#define MAX 5  // Maximum size of stack

 

int stack[MAX];

int top = -1;

 

// Function to push an element into the stack

void push(int value) {

    if (top == MAX - 1) {

        printf("\nStack Overflow! Cannot push %d\n", value);

    } else {

        top++;

        stack[top] = value;

        printf("\n%d pushed to stack.\n", value);

    }

}

 

// Function to pop an element from the stack

void pop() {

    if (top == -1) {

        printf("\nStack Underflow! No elements to pop.\n");

    } else {

        printf("\n%d popped from stack.\n", stack[top]);

        top--;

    }

}

 

// Function to display stack elements

void display() {

    if (top == -1) {

        printf("\nStack is empty.\n");

    } else {

        printf("\nStack elements are:\n");

        for (int i = top; i >= 0; i--) {

            printf("%d\n", stack[i]);

        }

    }

}

 

// Function to view the top element

void peek() {

    if (top == -1) {

        printf("\nStack is empty.\n");

    } else {

        printf("\nTop element is: %d\n", stack[top]);

    }

}

 

// Main function (menu-driven)

int main() {

    int choice, value;

 

    printf("=== STACK IMPLEMENTATION USING ARRAY ===\n");

 

    while (1) {

        printf("\nMenu:\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);

 

        switch (choice) {

            case 1:

                printf("Enter value to push: ");

                scanf("%d", &value);

                push(value);

                break;

            case 2:

                pop();

                break;

            case 3:

                peek();

                break;

            case 4:

                display();

                break;

            case 5:

                printf("\nExiting program.\n");

                exit(0);

            default:

                printf("\nInvalid choice! Try again.\n");

        }

    }

 

    return 0;

}

Output

 
OUTPUT :

=== STACK IMPLEMENTATION USING ARRAY ===

Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed to stack.

Enter your choice: 1
Enter value to push: 20
20 pushed to stack.

Enter your choice: 4
Stack elements are:
20
10

Enter your choice: 2
20 popped from stack.

Enter your choice: 3
Top element is: 10

Explanation

Operation

Description

Push

Adds an element to the top of the stack if it’s not full.

Pop

Removes the top element if the stack is not empty.

Peek

Displays the top element without removing it.

Display

Prints all stack elements from top to bottom.