1 Stack
1 Stack
Objective of Experiment : To implement basic data structures such as arrays, linked lists,
stacks and queues
Outcome of Experiment :
• Students will be able to implement linear data structures & be able to handle
operations like insertion, deletion, searching and traversing on them.
Program:
#include <stdio.h>
#define max 5
int stack[max];
int top = -1;
void push();
void pop();
void display();
void peek();
int main () {
int choice;
while(1)
{
printf ("***** MENU *****\n");
printf ("1. Push an element.\n");
printf ("2. Pop an element.\n");
printf ("3. Top element of the stack is:\n");
printf ("4. Display all the elements of stack.\n");
printf ("5. Quit.\n");
printf ("Enter your choice:");
scanf ("%d",&choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
default:
printf ("Invalid choice");
}
}
}
void push(){
if (top == max -1){
printf ("Stack is overflow,cannot push.\n");
Artificial Intelligence and Data Science Department
Subject/Odd Sem 2023-24/Experiment
} else{
int data;
top++;
printf ("Enter the data to be pushed:");
scanf ("%d",&stack [top]);
}
void pop(){
if (top == -1){
printf ("Stack is underflow, cannot pop.\n");
} else{
printf ("Element poped: %d\n",stack[top]);
top--;
}
}
void peek(){
if (top == -1){
printf ("Stack is underflow, cannot pop.\n");
} else{
printf ("Top element: %d\n",stack[top]);
}
}
void display(){
int i;
if (top == -1){
printf ("Stack is underflow, cannot pop.\n");
} else{
for (i=top; i>=0; i--){
printf ("%d \n",stack[i]);
}
}
}
Artificial Intelligence and Data Science Department
Subject/Odd Sem 2023-24/Experiment
Output Screenshot: