bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_2 / eduincs / pgrm_016.cpp

pgrm_016.cpp (1686B)


      1 /* Write a program in c++ to implement stack using a class stack with number variables, functions, constructor, destructor. */
      2 
      3 #include<iostream>
      4 using namespace std;
      5 
      6 class stack {
      7 private: 
      8     int size;
      9     int top;
     10     int *st;
     11 
     12 public: 
     13     stack(int n);
     14     ~stack();
     15     void push(int val);
     16     int pop();
     17     int isFull();
     18     int isEmpty();
     19     void display();
     20 };
     21 
     22 stack::stack(int n) {
     23     size = n;
     24     top = -1;
     25     st = new int[size];
     26 }
     27 
     28 stack::~stack() {
     29     delete[] st;
     30 }
     31 
     32 void stack::push(int val) {
     33     if(isFull())
     34         cout << "Stack is full, insertion not possible.\n";
     35     else {
     36         st[++top] = val;
     37         cout << val << " added to the stack.\n";
     38     }
     39 }
     40 
     41 int stack::pop() {
     42     if(isEmpty()) {
     43         cout << "Stack is empty, deletion not possible.\n";
     44         return -1;
     45     } 
     46     else    
     47         return st[top--];
     48 }
     49 
     50 int stack::isFull() {
     51     if(top == size - 1)
     52         return 1;
     53     else
     54         return 0;
     55 }
     56 
     57 int stack::isEmpty() {
     58     if(top == -1)
     59         return 1;
     60     else
     61         return 0;
     62 }
     63 
     64 void stack::display() {
     65     cout << "\nStack elements are: ";
     66     for(int i = top; i >= 0; i--)
     67         cout << st[i] << "  ";
     68     cout << endl;
     69 }
     70 
     71 int main() {
     72     stack obj(3);
     73     obj.push(10);
     74     obj.push(15);
     75     obj.push(19);
     76     obj.push(20); // trying to overflow
     77     cout << "\n== After pushing all element ==";
     78     obj.display();
     79     cout << "\nPopped element is: " << obj.pop();
     80     cout << "\nPopped element is: " << obj.pop();
     81     cout << "\n\n == After poping two item ==";
     82     obj.display();
     83     cout << "\nPopped element is: " << obj.pop();
     84     cout << "\nPopped element is: " << obj.pop(); // trying to underflow
     85     return 0;
     86 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror