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 pop(int stack[]);
void display(int stack[]);

int top = -1;

int main()
{
    int stack[size], 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);
                break;
            case 'o':
                data = pop(stack);
                if (data !=  - 1)
                    printf("\n%d deleted", data);
                else
                    printf("\nstack is empty");
                break;
            case 'd':
                display(stack);
                break;
        }
    }
    while (ch != 'q');

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

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

}

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