Data structures-Lab-Programs-II BCA A-PROGRAM 1
Data structures-Lab-Programs-II BCA A-PROGRAM 1
ON
2024
Material Prepared
By
Algorithm:
SOURCE CODE:
#include <iostream>
#define MAX 5 // Define the maximum size of the stack
class Stack {
int top; // Index of the top element in the stack
int arr[MAX]; // Array to store stack elements
public:
Stack() : top(-1) {} // Constructor to initialize the stack
// Function to add an element to the stack
void push(int x) {
if (top >= MAX - 1) {
std::cout << "Stack Overflow\n"; // Check for stack overflow
} else {
arr[++top] = x; // Increment top and add element to stack
std::cout << x << " pushed into stack\n";
}
}
// Function to remove an element from the stack
void pop() {
if (top < 0) {
std::cout << "Stack Underflow\n"; // Check for stack underflow
} else {
std::cout << arr[top--] << " popped from stack\n"; // Remove and return top element
}
}
// Function to view the top element of the stack
void peek() {
if (top < 0) {
std::cout << "Stack is Empty\n"; // Check if the stack is empty
} else {
std::cout << "Top element is " << arr[top] << std::endl; // Display top element
}
}
// Function to check if the stack is empty
bool isEmpty() {
return top < 0;
}
};
int main() {
Stack stack; // Create a stack object
int choice, value;
while (true) {
// Display menu
std::cout << "Array Implementation of Stack\n";
std::cout << "-------------------------------\n";
std::cout << "1. Push \n2. Pop \n3. Peek \n4. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
if (choice == 4) {
std::cout << "Exiting!!!\n"; // Exit the program
break;
}
switch (choice) {
case 1:
std::cout << "Enter value to push: ";
std::cin >> value;
stack.push(value); // Push value to stack
break;
case 2:
stack.pop(); // Pop value from stack
break;
case 3:
stack.peek(); // Peek at the top value of stack
break;
default:
std::cout << "Invalid choice, please try again.\n"; // Handle invalid input
}}}
OUTPUT:
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 1
Enter value to push: 50
50 pushed into stack
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 1
Enter value to push: 60
60 pushed into stack
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 1
Enter value to push: 70
70 pushed into stack
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 3
Top element is 70
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 2
70 popped from stack
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 3
Top element is 60
Array Implementation of Stack
-------------------------------
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice: 4
Exiting!!!
---------