Answer to Question #261718 in C++ for Afan

Question #261718

Create a class called Stack for storing integers. The data members are an integer array for storing



the integers and an integer for storing the top of stack (tos). Include member functions for initializing tos



to 0, pushing an element to the stack and for popping an element from the stack. The push() function



should check for “stack overflow” and pop() should check for “stack underflow”.

1
Expert's answer
2021-11-05T18:00:33-0400
#include<iostream>
using namespace std;
#define SIZE 50
class Stack {
    int arr[SIZE];
    int tos;
public:
    Stack() {
        tos = 0;
    }
    push(int value) {


    if (tos < SIZE) {
        arr[tos++] = value;
    }
    else
        cout << "Stack overflow" << endl;


}
    int pop() {
    if (tos == 0) {
        cout << "Stack underflow " << endl;
    }
    else {
        return arr[--tos];
    }


}
    set(int a) {
    tos = a;


}




};








int main() {
    Stack s;
    for (int i = 0; i < 50; i++) {
        s.push(i);
    }
    for (int i = 0; i < 51; i++) {
        cout << s.pop() << " " << i << endl;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS