Stack Operations

Algorithm

Push(stack, top, maxstk, item)// inserts an item onto the stack
1.	[stack already filled?]
If top = maxstk then : print : OVERFLOW and return.
2.	Set top : = top +1 . [increases top by 1]
3.	 Set stack[top] := item [inserts item in new TOP position]
4.	Return.

Pop(stack, top, item)//deletes top element from stack and assign it to the variable item.
1.	[Stack has an item to be removed?]
If top := 0, then : print : UNDERFLOW  and return.
2.	Set item := stack[top]. [assigns top element to item].
3.	Set top := top -1.[decreases top by 1].
4.	Return


Algorithm Description

C Code


#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#define MAXSIZE 10
using namespace std;
int a[MAXSIZE];
void showstack(int);
int main()
{
	int n;
	int top=-1;
	while(1)
	{
		printf("           Stack\n\n\n");
		printf("1. Push\n");
		printf("2. Pop\n");
		printf("3. Find size\n");
		printf("4. isEmpty\n");
		printf("5. isFull\n");
		printf("6. Exit\n\n\n");
		printf("enter choice(1-6)\n");
		scanf("%d",&n);
		switch(n)
		{
			case 1:
			if(top==MAXSIZE-1)
			{
				printf("Overflow\n");
				break;
			}
			else
			{
				printf("enter the element\n");
				scanf("%d",&a[++top]);
			}
			showstack(top);
			break;
			case 2:
			if(top==-1)
			{
				printf("Underflow\n");
				break;
			}
			else
			{
				printf("popped out element is %d\n",a[top--]);
			}
			showstack(top);
			break;
			case 3:
			printf("Size of stack is %d",top+1);
			break;
			case 4:
			if(top==-1)
				printf("yes!! stack is empty\n");
			else
				printf("no!! stack is not empty\n");
			break;
			case 5:
			if(top==MAXSIZE-1)
				printf("yes!! stack is full\n");
			else
				printf("no!! stack is not full\n");
			break;
			case 6:
			     exit(0);
		}
	}
	return 0;
}
void showstack(int top)
{
	int i;
	if(top==-1)
		printf("stack is empty\n");
	else
	{
		printf("elements on stack are:\n");
		for(i=top;i>=0;i--)
			printf("%d\n",a[i]);
	}
}