Facebook

Pop operation in Stack

POP Operation

In this  operation topmost element is deleted from the stack.Before deleting check if TOP = NULL.If yes,it means that stack is empty and no deletion can be done.If an attempt to delete element is made in this case the UNDERFLOW message will be printed on screen.If no,then element is deleted then value of TOP is decremented by 1.

For example

  • We want to delete/pop 100 from this stack(Fig 9).
  • TOP = 4
  • TOP is not equal to null.
  • 100 is popped out/deleted.
  • TOP variable gets decremented to 3.

 

Program 2

#include<stdio.h>

int main()
{
	int max;
	int stack[10];
	int num,val,i,temp;
	int top = -1;
	//printf("Enter the maximum size of stack");
	scanf("%d",&max);
	//printf("Enter the no of elements in stack");
	scanf("%d",&num);
	//printf("Enter the elements of stack");
	for(i=0;i<num;i++)
	{
		scanf("%d\n",&stack[i]);
		top++;
	}
	temp =top;
	if(top == -1)
	{
		printf("Underflow");
	}
	else
	{
		top =top -1;
		printf("The stack after pop operation is \n");
		for(i=0;i<temp;i++)
		{
		 printf("%d\n",stack[i]);
		top++;
	}
	}
	return 0;
}

Run
 Illustration of Program 2

  • Refer Program 1 for working of for loop and consider the same values.
  • top = 4
  • temp = top i.e temp = 4
  • if( top ==-1) i.e if no element is present in the stack then Underflow message will be printed on screen as no element is present to pop out.
  • top = top -1 =4-1=3.
  • for(i=0;i<temp;i++) - i would iterate till it is less than temp(4).
  • Elements of stack after pop operation is printed.
Rate this post

Comments

So empty here ... leave a comment!

Leave a Reply

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

Sidebar