Answer to Question #262921 in C++ for sam

Question #262921

Q#4). 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-08T17:33:40-0500
#include <iostream>


using namespace std;
#define SIZE 50
class Stack{
int stackArray[SIZE];
int tos;
public:
    Stack(){
    tos=0;
    }
    void push(int);
    int pop();
    void set(int);
};
void Stack::push(int value){
if(tos<SIZE){
    stackArray[tos++]=value;
}else
cout<<"Stack overflow"<<endl;
}
void Stack::set(int a){
tos=a;
}
int Stack::pop(){
if (tos==0){
    cout<<"Stack underflow"<<endl;
}else {
return stackArray[--tos];
}
}
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