C Program to implement stack

What is a stack?


A stack is a data structure in which the items entered last will be the first to be removed. It is also known as LIFO (Last In First Out). The entry of a new item is called as PUSH and the removal of an item is called as POP operations respectively.

Explanation of the program


The program displays a menu from which the user can select one of the operations, which includes insert, delete, display and exit. The choice is read into the variable ch. 

If the user selects the insert operation, the stack is checked to see if it is full, by using the statement if(top==max), if so a message is printed to indicate it and the control will be exited from the switch case. If the stack is not full, the new item will be read into the variable item. Then the item is inserted into stack[top] and the value of top will be incremented.  

If the user selects the delete operation, the stack is first checked to see if it is empty, by using the statement if(top==0),  if so a message will be printed to indicate it and the control will be exited from the switch case. If the stack is not empty, the value of top will be decremented.

If the user selects the display operation, the stack is first checked to see if it is empty, by using the statement if(top==0),  if so a message will be printed to indicate it and the control will be exited from the switch case. If the stack is not empty, the contents of the stack will be displayed by using a for loop.

If the user selects the exit operation, the program will be exited. 

   

Program


// Stack Program in c
#include<stdio.h>

#include<process.h>

#include<conio.h>

#define max 5

void main()

{

int stack[max],top=0,ch,item,i;

printf("\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice: ");

scanf("%d",&ch);

while(ch!=4)

{

switch(ch)

{

case 1:

if(top==max)

{

printf("\nStack is Full!!!");

break;

}

else

{

printf("Enter the item: ");

scanf("%d",&item);

stack[top]=item;

top++;

break;

}

case 2:

if(top==0)

{

printf("\nStack is Empty!!!");

break;

}

else

{

item=stack[top-1];

top--;

printf("\nItem deleted is %d",item);

break;

}

case 3:

if(top==0)

{

printf("stack is empty!!!");

break;

}

else

{

for(i=0;i<=top-1;i++)

printf("%d ",stack[i]);

break;

}

case 4:

exit(0);

break;

}

printf("\n\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice: ");

scanf("%d",&ch);

}

}


Output





c program for stack operations
C program to implement stack

No comments: