Stack Operations (push,pop,display and search) using Array in C Programming Language






#include<stdio.h>

#include<conio.h>
#define SIZE 10
void push(int);
void pop();
void display();
void search(int);
int stack[SIZE], top = -1;

void main()
{
    int value, choice;
    clrscr();
    while(1)
    {
        printf("\n\n***** MENU *****\n");
        printf("\n ------------------------------");
        printf("\n 1. Push");
        printf("\n 2. Pop");
        printf("\n 3. Display");
        printf("\n 4. Search");
        printf("\n 5. Exit");
        printf("\nEnter your choice: ");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1:
                    printf("Enter the value to be insert: ");
                    scanf("%d",&value);
                    push(value);
                    break;
            case 2:
                    pop();
                    break;
            case 3:
                    display();
                    break;
            case 4:
                    printf("Enter the value to be search: ");
                    scanf("%d",&value);
                    search(value);
                    break;
            case 5:
                    exit(0);
            default:
                    printf("\nWrong selection!!! Try again!!!");
        
    }
}
void push(int value)
{
    if(top == SIZE-1)
    {    
        printf("\n Stack is Full!!! Insertion is not possible!!!");
        return;
    }
    else
    {
        top++;
        stack[top] = value;
        printf("\n Insertion successful!!!");
    }
}
void pop()
{
    if(top == -1)
    {
        printf("\nStack is Empty!!! Deletion is not possible!!!");
        return;
    }
    else
    {
        printf("\n %d Deleted",stack[top]);
        top--;
    }
}
void display()
{
    if(top == -1)
    {
        printf("\nStack is Empty!!!");
        return;
    }
    else
    {
        int i;
        printf("\nStack elements are: ");
        for(i=top; i>=0; i--)
            printf("%d ",stack[i]);
    }
}
void search(int value)
{
    if(top == -1)
    {
        printf("\n Stack is Empty!!! Searching is not possible!!!");
        return;
    }
    else
    {
        int i, found=0;
        for(i=0;i<=top;i++)
        {
            if(value==stack[i])
            {
                found=1;
                break;
            }
        }
        if(found==1)
            printf("\n %d found", value);
        else
            printf("\n %d not found",value);
     
      }
    getch();
}

Post a Comment

0 Comments