0% found this document useful (0 votes)
13 views2 pages

Stack Operations

stack operations
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Stack Operations

stack operations
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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;
}

You might also like