Skip to main content

Program in C to implement stack using array

 #include <stdio.h>
#define MAX 6
int top = -1;
int A[MAX];
void push(int data)
{
    if (top > MAX)
    {
        printf("Stack Overflow");
        return;
    }
    else
    {
        top = top + 1;
        A[top] = data;
    }
}
void pop()
{
    if (top == -1)
    {
        printf("Stack Underflow");
        return;
    }
    else
    {
        int data = A[top];
        --top;
        printf("Removed element is %d", data);
    }
}
void peek()
{
    if (top == -1)
    {
        printf("Stack is empty");
    }
    else
    {
        printf("Recent entered value is %d", A[top]);
    }
}
void display()
{
    int i;
    if (top == -1)
    {
        printf("Stack is empty");
    }
    else
    {
        printf("\nElements in the stack are:\n");
        for (i = top; i >= 0; i--)
        {
            printf("%d\n", A[i]);
        }
    }
}
int main()
{
    int ch; // choice variable
    int value; // to store value from the user
    while (1) // 1 true
    {
        printf("Enter 1 for adding element\nEnter 2 for removing element");
        printf("\nEnter 3 for displaying recent element\nEnter 4 for display entire stack\n");
        printf("Enter 5 to exit\n");
        scanf("%d", &ch);
        if (ch == 1)
        {
            printf("Enter data:");
            scanf("%d", &value);
            push(value);
        }
        else if (ch == 2)
        {
            pop();
        }
        else if (ch == 3)
        {
            peek();
        }
        else if (ch == 4)
        {
            display();
        }
        else if (ch == 5)
            break;
    }
    return 0;
}

Popular posts from this blog