Experiment 1
Experiment 1
Experiment 1
1
Stack ADT using Array
Write a program to implement Stack ADT using Array
#include <stdio.h>
#define SIZE 5 // Define the maximum size of the stack
// Stack structure
struct Stack {
int items[SIZE];
int top;
};
while (1) {
printf("\nStack Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to push: ");
scanf("%d", &value);
push(&stack, value);
break;
case 2:
pop(&stack);
break;
case 3:
value = peek(&stack);
if (value != -1) {
printf("Top element is %d\n", value);
}
break;
case 4:
display(&stack);
break;
case 5:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Please try again.\n");
break;
}
}
}
OUTPUT
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack is empty
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack is empty
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the value to push: 56
Pushed 56 onto the stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the value to push: 56
Pushed 56 onto the stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the value to push: 48
Pushed 48 onto the stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the value to push: 78
Pushed 78 onto the stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack elements are: 78 48 56 56
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2
Popped 78 from the stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2
Popped 48 from the stack
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3
Top element is 56
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack elements are: 56 56
Stack Menu:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: . 5
Exiting...