Stack program with Pointer and structure in C

Stack program with Pointer and structure in C


book stack
The stack is the most important concept of computer science everything works on the stack it is a data structure which is used to store data is a particular order that is LIFO (Last In First Out). it has two functions PUSH and POP. 
PUSH function takes value from the users and inserts it into the stack, where POP function takes the value out of the stack. But now the question is which value? It's simple, the POP function will pop the last value inserted into the stack and then pop the second last and so on. 
stack dig
Point to be noted here is that, it is contradictory to say that POP function will take out the element or you might be thinking it will remove the element from the stack. NO, it's not like that it will just display the element and the reduce the counter by 1 and all the elements will be there as it is.

#include <stdio.h>
#define MAX 10
 struct stack{
       int arr[MAX];
       int top;
       };
       // function prototype
       void push(struct stack*,int );// it will push value to stack.
       int pop(struct stack*);// it will pop value from stack.
int main()
{
     int n,top=-1,x, opt;
     struct stack stk;
   
     printf("Enter 1 to push\n");
     printf("Enter 2 to pop\n");
     printf("Enter 3 to Exit\n");
   
   
     while(1)
     {
         printf("\nEnter Your Choice\n");
         scanf("%d",&opt);
             switch(opt)
             {
                        case 1:
                                printf("Enter the Value");
                                scanf("%d",&n);
                                push(&stk,n);
                                break;
                        case 2:
                               x= pop(&stk);
                               printf("%d",x);
                               break;
                        case 3:
                             exit(0);
                           
             }
     }
   
     return 0;
}
void push(struct stack *p,int n)
{
     if(p->top== (MAX -1))
     {
                 printf("STACK OVERFLOW");
     }
     else
     {
         p->top++;
         p->arr[p->top]=n;
     }
     return;
}
int pop(struct stack *p)
{
    int val;
    if(p->top== -1)
    {
                printf("STACK UNDERFLOW");
    }
    else
    {
        val= p->arr[p->top];
        p->top--;
    }
    return (val);
}

If you need any Help pls comment below.

0 comments :

Post a Comment