1.
Stack operations
#include <iostream>
using namespace std;
class Stack {
private:
int stackArray[100]; // Fixed-size array for stack
int top; // Top of the stack
int maxSize; // Maximum size of the stack
public:
// Constructor
Stack(int size) {
maxSize = size;
top = -1;
}
void push();
int pop();
void display();
};
// Function definitions
void Stack::push() {
if (top == maxSize - 1) {
cout << "Stack overflow! Cannot push more elements." << endl;
} else {
int value;
cout << "Enter a value to push: ";
cin >> value;
stackArray[++top] = value;
cout << value << " pushed onto the stack." << endl;
}
}
int Stack::pop() {
if (top == -1) {
cout << "Stack underflow! Cannot pop." << endl;
return -1;
} else {
return stackArray[top--];
}
}
void Stack::display() {
if (top == -1) {
cout << "Stack is empty." << endl;
} else {
cout << "Stack elements: ";
for (int i = top; i >= 0; i--) {
cout << stackArray[i] << " ";
}
cout << endl;
}
}
int main() {
int size, choice;
cout << "Enter the size of the stack: ";
cin >> size;
Stack stack(size); // Create stack object with given size
do {
cout << "\nMenu:\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
stack.push();
break;
case 2:
cout << "Popped element: " << stack.pop() << endl;
break;
case 3:
stack.display();
break;
case 4:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice! Please try again." << endl;
}
} while (choice != 4);
return 0;
}