Facebook

Push operation in Stack

Push Operation

In this operation,the element is inserted at the top of stack(Fig 4). In order to insert element we need to check whether TOP = MAX-1. If  yes,then insertion  is not possible. If  element is still  tried for insertion , OVERFLOW message will be printed on screen as the stack do not have extra space to handle new element. If space is present and element is inserted,then the value of top will be incremented by 1 .

For example

  • Say we want to insert/push 800 in the following stack(Fig 1).
  • TOP = 4(index starts from 0)
  • MAX= 13
  • The value of TOP is 4 and MAX-1 is 13-1=12.TOP and MAX are not equal,thus element 800 can be pushed into the stack.
  • After insertion value of TOP gets incremented t0 5.
Fig 1:Push 800

Program 1

#include<stdio.h>
int main()
{
	int stack[10];
	int max;
	int num;
	int top = -1;
	int i;
	int item;
	//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++)//Fig 7
	{
		scanf("%d\n",&stack[i]);
		top++;
	}

	if(top == max -1)//Fig 8
	{
		printf("Overflow");
	}
	else
	{
		//printf("Enter the item you want to insert\n");
		scanf("%d",&item);
		top = top + 1;//Fig 6
		stack[top] = item;
		printf("The stack after push operation is \n");
		for(i=0;i<=num;i++)
	{
	 printf("%d\n",stack[i]);
		top++;
	}
	}

	return 0;
}

Run

 Illustration of Program 1

  • Integer array of stack with size 10 is defined.
  • max is the maximum capacity of stack(Say 10).
  • num is the actual number of elements in stack(Say 5).
  • Variable top is initialized to -1.
  • i is used in for loop and item is the element we want to push in stack.
  • for loop(Fig 4) and scanf are used to read the values of stack.
Fig 2 : Push 30

 

Fig 3 : Working of for loop
Fig 4 : Working of if statement

 

 

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