Index « Previous Next »

Question

In computer science, a stack is a data structure that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed. Write a program to implement push and pop operations of stack in an array.

Source Code

#include <stdio.h>
#include <stdlib.h>

#define size 5

void push(int stack[], int item, int *top);
int pop(int stack[], int *top);
void display(int stack[], int *top);

int main()
{
    int stack[size], Top =  - 1, data;
    char ch;
    do
    {
        printf(
            "\n\nStack options\np. for push \no. for Pop \nd. for Display \nq. for quit \nEnter choice : ");
        fflush(stdin);
    
		scanf("%c", &ch);
        switch (ch)
        {
            case 'p':
                printf("\nEnter number : ");
                scanf("%d", &data);
                push(stack, data, &Top);
                break;
            case 'o':
                data = pop(stack, &Top);
                if (data !=  - 1)
                    printf("\n%d deleted", data);
                else
                    printf("\nstack is empty");
                break;
            case 'd':
                display(stack, &Top);
                break;
        }
    }
    while (ch != 'q');

    return 0;
}
void push(int stack[], int item, int *top)
{
    if (*top == size - 1)
    {
        printf("stack is full");
    }
    else
    {
        (*top)++;
        stack[ *top] = item;
    }
}

int pop(int stack[], int *top)
{
    int value;
    if (*top ==  - 1)
    {
        return  - 1;
    }
    else
    {
        value = stack[ *top];
        (*top)--;
        return value;
    }

}

void display(int stack[], int *top)
{
    int i;
    for (i =  *top; i >= 0; i--)
    {
        printf("\n%d", stack[i]);
    }
}