C Program to Perform Stack Operations Using Pointer

C Program to Perform Stack Operations Using Pointer:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().

#include<stdio.h>
#include<stdlib.h>

int size;

// Defining the stack structure
struct stack
{
   int arr[50];
   int top;
};

// Initializing the stack
void init_stk(struct stack *st)
{
   st->top = -1;
}

// Entering the elements in the stack
void push(struct stack *st,int num)
{
   if(st->top == size-1)
    {
      printf("\nStack is full");
      return;
    }
   st->top++;
   st->arr[st->top] = num;
}

//Deleting element from stack.
int pop(struct stack *st)
{
   int num;
   if (st->top == -1)
    {
      printf("\nStack is empty");
      return NULL;
   }
   num = st->arr[st->top];
   st->top--;
   return num;
}

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

main()
{
   int element,opt,val;
   struct stack ptr;
   init_stk(&ptr);
   printf("Enter Stack Size :");
   scanf("%d",&size);
   while (1) {
      printf("\nMain Menu");
      printf("\n1.PUSH");
      printf("\n2.POP");
      printf("\n3.DISPLAY");
      printf("\n4.EXIT");
      printf("\n");
      printf("\nEnter your option : ");
      scanf("%d",&opt);
      switch (opt)
      {
      case 1:
         printf("\nEnter elements into the stack:");
         scanf("%d",&val);
         push(&ptr,val);
         break;
      case 2:
         element = pop(&ptr);
         printf("\nThe element popped/deleted from stack is : %d",element);
         break;
      case 3:
         printf("\nThe current stack elements are:");
         display(&ptr);
         break;
      case 4:
         exit(0);
      default:
         printf("\nPlease enter correct option");
      }
   }
}

OUTPUT:

Enter Stack Size :5

Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 1

Enter elements into the stack:5

Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 1

Enter elements into the stack:6

Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 1

Enter elements into the stack:8

Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 1

Enter elements into the stack:3

Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 3

The current stack elements are:
3
8
6
5
Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 2

The element popped/deleted from stack is : 3
Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 2

The element popped/deleted from stack is : 8
Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 3

The current stack elements are:
6
5
Main Menu
1.PUSH
2.POP
3.DISPLAY
4.QUIT

Enter your option : 4

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.