Stack using array

 1) Stack using Array

Aim

To implement stack operations (Push, Pop, Display) using arrays in C.

Objective

  • To study the LIFO (Last In, First Out) principle.

  • To practice array-based implementation of data structures.

Algorithm

Push:

  1. If top == n-1, then overflow.

  2. Else top = top + 1 and insert element at stack[top].

Pop:

  1. If top == -1, then underflow.

  2. Else delete element from stack[top], then top = top - 1.

Display:

  1. If top == -1, stack empty.

  2. Else print elements from stack[top] to stack[0].

Flowchart 

Flowchart - C Program to implement a Stack

C Code (Stack using Array)

#include <stdio.h>

#define MAX 5

int main() {

    int stack[MAX], top = -1, choice, item, i;

    while (1) {

        printf("\n--- Stack Menu ---\n");

        printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");

        printf("Enter choice: ");

        scanf("%d", &choice);

        if (choice == 1) {

            if (top == MAX - 1)

                printf("Stack Overflow!\n");

            else {

                printf("Enter item to push: ");

                scanf("%d", &item);

                top++;

                stack[top] = item;

            }

        }

        else if (choice == 2) {

            if (top == -1)

                printf("Stack Underflow!\n");

            else {

                printf("Popped: %d\n", stack[top]);

                top--;

            }

        }

        else if (choice == 3) {

            if (top == -1)

                printf("Stack is Empty!\n");

            else {

                printf("Stack elements: ");

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

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

                printf("\n");

            }

        }

        else if (choice == 4) {

            printf("Exiting...\n");

            break;

        }

        else {

            printf("Invalid choice!\n");

        }

    }

    return 0;

}


Comments

Popular posts from this blog

Bubble Sort

Singly linked list implementation