First let us understand what exactly the Stack is, It is a Array in which elements are stored in LIFO manner. It means "Last In First Out". Element which you store in stack at last, will be removed first. In stack we can't add or remove element in between of stack, Adding or deleting element can be done only in sequence of LIFO. Below is a program of stack implementation by which operations like Push (Adding element), Pop (Deleting element), Top (Display top element), Display (To Display all elements in stack) can be performed.
Also read: 3 Ways to Print text without printf()
Program:
#include <stdio.h>
#include <conio.h>
//Stack implementation program by SlashMyCode.com
int stack[20];top=-1;
void push(int);
int pop();
int topp();
void display();
void main()
{
int num1,num2,choice,exit;
while(exit!=1)
{
printf("\n Press 1 to Add element");
printf("\n Press 2 to Delete element");
printf("\n Press 3 to Show Top element");
printf("\n Press 4 to Display elements");
printf("\n Press 5 to EXIT");
printf("\n \n Enter your choice: ");
scanf("%d",&choice);
switch (choice)
{
case 1:
{
printf("Enter the number: ");
scanf("%d",&num1);
push(num1);
break;
}
case 2:
{
num2=pop();
printf("Deleted Element is %d \n",num2);
break;
}
case 3:
{
num2=topp();
printf("Top Element is %d",num2);
break;
}
case 4:
{
printf("Stack Elements Are: \n");
display();
break;
}
case 5:
{
exit=1;
break;
getch();
}
default:
printf("Invalid Choice\n");
}//End of Switch
}//End of While Loop
getch();
}//End of main
//Stack implementation program by SlashMyCode.com
void push(int e)
{
if (top==19)
{
printf("Stack Is Full\n");
getch();
}
else
{
top=top+1;
stack[top]=e;
}
}
int pop()
{
int temp;
if (top==-1)
{
printf("Stack Is Empty \n");
}
else
{
temp=stack[top];
stack[top]=NULL;
top=top-1;
return temp;
}
}
int topp()
{
int temp;
if (top==-1)
{
printf("Stack Is Empty \n");
}
else
{
temp=stack[top];
return temp;
}
}
void display()
{
int i;
if (top==-1)
printf("Stack Is Empty \n");
else
{
for (i=top;i>=0;i--)
{
printf("%d ",stack[i]);
getch();
}
}//Stack implementation program by SlashMyCode.com
}
Output:
This is the output while performing Push and Display operations.
No comments:
Post a Comment
Feel free to ask us any question regarding this post