• Follow Us

PUSH and POP Operation in Stack in C Programming Language

Let’s have a C program to implement PUSH and POP Operation in Stack in C. Firstly, we need to create a structure as mentioned below:
struct stack
{
int * a;
int top;
int maxSize;
};

Structure stack has a pointer ‘a’ to a dynamically allocated array, an integer ‘maxSize’ that holds the size of this array. And an integer ‘top’ which stores the array index of the top element in the stack.

Implementation of PUSH and POP Operation in Stack in C

Here we will have a look at how to write a program to implement push and pop operation on the stack and to display the contents of the stack.

#include<stdio.h>
#include<stdlib.h>
struct stack {
	int * a;
	int top;
	int maxSize;
};
void initstack(struct stack * p, int maxSize);
void push(struct stack * p, int item);
void display(struct stack p);
int pop(struct stack * p);
void printMenu();


int main()  {
	struct stack p;
	int data,ch, data1, m;
	printf("Enter the maximum size of the stackn");
	scanf("%d",&m);
	initstack(&p,m);
	do {
	printMenu();	
	printf("Enter your choicen");
	scanf("%d",&ch);
	switch(ch) {
	  case 1:
		printf("Enter the element to be pushedn");
		scanf("%d",&data);
		push(&p, data);
		break;
	  case 2:
		data1 = pop(&p);
		if(data1 != -1000)
		printf("The popped element is %dn",data1);
		break;
	  case 3:
		printf("The contents of the stack are");
		display(p);
		printf("n");
		break;
	  default:
		return 0;
	}
	} while(1);
	return 0;
}

void printMenu()
{
	printf("Choice 1 : Push\n");
	printf("Choice 2 : Pop\n");
	printf("Choice 3 : Display\n");
	printf("Any other choice : Exit\n");
}

void initstack(struct stack * p, int maxSize) {
	//Fill in the code here
 int *newContents;
  newContents=malloc(sizeof(int)*maxSize);
  p->a=newContents;
  p->maxSize=maxSize;
  p->top=-1; 
}

void push(struct stack * p, int item) {
	//Fill in the code here
	 if(p->top >= p->maxSize-1)
    {
      printf("Stack is fulln");
    }
    else
    {
    p->a[++p->top]=item; 
    }
}

void display(struct stack p) {
    
	//Fill in the code here	
	 int i;
  struct stack *b=&p;
  if(b->top<0)
  {
    printf(" {}");
  }
  for(i=0;i<=b->top;i++)   
  {
    printf(" %d",b->a[i]);
  }
}

int pop(struct stack * p) {
	//Fill in the code here if(StackIsEmpty(p))
    if(p->top<0)
    {
      printf("Stack is emptyn");
      return -1000;
    }
  else
    return p->a[p->top--];   
}

 

Leave a Reply

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

Shopping cart