Group
Data Structures: Stacks, Queues in C++
Objective
1. Define a fixed-size array to act as the stack storage.
2. Use a variable to keep track of the top of the stack.
3. Implement a function to push an element onto the stack, checking for overflow.
4. Implement a function to pop an element from the stack, checking for underflow.
5. Allow the user to interact with the stack using a simple menu.
Implement a basic stack with insertion (push) and deletion (pop) operations.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include input/output stream library
using namespace std;
#define MAX 5 // Define maximum size of the stack
// Stack class definition
class Stack {
private:
int arr[MAX]; // Array to store stack elements
int top; // Index of the top element
public:
// Constructor to initialize stack
Stack() {
top = -1; // Stack is empty initially
}
// Function to add an element to the stack
void push(int value) {
if (top >= MAX - 1) {
cout << "Stack Overflow. Cannot push " << value << endl;
} else {
top++; // Move top index up
arr[top] = value; // Store value at new top
cout << "Pushed " << value << " onto the stack." << endl;
}
}
// Function to remove an element from the stack
void pop() {
if (top < 0) {
cout << "Stack Underflow. Nothing to pop." << endl;
} else {
cout << "Popped " << arr[top] << " from the stack." << endl;
top--; // Decrease top index
}
}
// Function to display current stack elements
void display() {
if (top < 0) {
cout << "Stack is empty." << endl;
} else {
cout << "Stack contents: ";
for (int i = 0; i <= top; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
}
};
int main() {
Stack s; // Create a Stack object
int choice, value;
// Loop to show menu and perform stack operations
do {
cout << "\nStack Operations Menu:\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Display Stack\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
s.push(value); // Call push function
break;
case 2:
s.pop(); // Call pop function
break;
case 3:
s.display(); // Call display function
break;
case 4:
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 4); // Continue until user chooses to exit
return 0; // End of program
}
Output
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 1
Enter value to push: 10
Pushed 10 onto the stack.
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 1
Enter value to push: 20
Pushed 20 onto the stack.
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 3
Stack contents: 10 20
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 2
Popped 20 from the stack.
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 4
Exiting program.