Data Structure Question-1 Stack

Question on stack using global variable are given below :

// question on stack using global variable

#include<stdio.h>
#include<stdlib.h>
int Stack[5];
int top=-1;
int size = 5;
int isempty()
{
    if(top == -1)
        return 1;
    else
        return 0;    
}
int full()
{
    if(top == size-1)
        return 1;
    else
        return 0;    
}
void push(int data)
{
    if(!full())
    {
        top++;
        Stack[top]=data;
    }
    else{
        printf("stack overflow");
    }
}
int pop()
{
    if(!isempty())
    {
        int data = Stack[top];
        top--;
        return data;
    }
    else
    {
        printf("stack is empty");
        return 0;
    }
}
void main()
{
    int choice,c;
    int data;
    do{
        printf("Enter 1 to push");
        printf("\nEnter 2 to pop");
        printf("\nEnter 3 to display");
        printf("\nEnter 0 to exit\n");
        fflush(stdin);
        scanf(" %d",&choice);
        switch (choice)
        {
        case 1:
            printf("Enter the data to push\n");
            scanf(" %d",&data);
            push(data);
            break;
        case 2:
           data= pop();
           printf("pop data is %d",data);
            break;
        case 3:
            if(!isempty())
            {
                for(int i =0 ;i<=top;i++)
                {
                    printf(" %d ",Stack[i]);
                }
            }
         break;
        default:
           exit(1);
        }
        printf("press 1 to continue\n");
        fflush(stdin);
        scanf(" %d",&c);
    }while(c==1);
}

Output

Enter 1 to push
Enter 2 to pop
Enter 3 to display
Enter 0 to exit
1
Enter the data to push
23
press 1 to continue
1
Enter 1 to push
Enter 2 to pop
Enter 3 to display
Enter 0 to exit
1
Enter the data to push
45
press 1 to continue
1
Enter 1 to push
Enter 2 to pop
Enter 3 to display
Enter 0 to exit
3
23  45 

Leave a Reply

Your email address will not be published. Required fields are marked *

Solverwp- WordPress Theme and Plugin