STACK ADT USING ARRAY

 #include <iostream>

using namespace std;


#define MAX 100  // Maximum size of the stack


class Stack {

private:

    int top;

    int arr[MAX];

public:

    Stack() : top(-1) {}


    void push();

    void pop();

    void display();

};


void Stack::push() {

    if (top >= MAX - 1) {

        cout << "Stack Overflow\n";

        return;

    }

    int value;

    cout << "Enter the value to push: ";

    cin >> value;

    arr[++top] = value;

    cout << value << " pushed onto stack\n";

}


void Stack::pop() {

    if (top < 0) {

        cout << "Stack Underflow\n";

        return;

    }

    int value = arr[top--];

    cout << value << " popped from stack\n";

}


void Stack::display() {

    if (top < 0) {

        cout << "Stack is empty\n";

        return;

    }

    cout << "Stack elements are:\n";

    for (int i = top; i >= 0; --i) {

        cout << arr[i] << " ";

    }

    cout << "\n";

}


int main() {

    Stack stack;

    int choice;

    cout << "\n Main Menu";

    cout << "\n 1.Push \n 2.Pop \n 3.Display \n 4.Exit";

    do {

        cout << "\nEnter your choice: ";

        cin >> choice;

        switch (choice) {

            case 1: stack.push(); break;

            case 2: stack.pop(); break;

            case 3: stack.display(); break;

            case 4: exit(0);

            default: cout << "Invalid choice, please select between 1-4\n";

        }

    } while (choice != 4);

    return 0;

}

Comments

Popular posts from this blog

LIST ADT USING LINKED LIST

CLASSES CREATION

SORTING PROGRAM