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