lab03.cpp
Problem Statement
lab03.cpp
Write a program in C++ to implement Array Representation of Stack using class, constructor, member variables, member functions, and destructor.
Source Code
cpp
#include<iostream>
using namespace std;
template <class T>
class stack {
private:
T *arr;
int n;
int top = -1;
public:
stack(int size) {
n = size;
arr = new T[n];
cout << "Array created with capacity " << n;
}
void push(T elem) {
if(top == n - 1 ) {
cout << "Stack overflow.";
}
else {
arr[++top] = elem;
cout << "Pushed: " << elem;
}
}
void pop() {
if(top == -1 ){
cout << "Unable to delete, stack is empty.";
}
else {
cout << "Popped: " << arr[top--];
}
}
void display() {
cout << "\nCurrent array: ";
for(int i = 0; i <= top; i++) {
cout << arr[i] << " ";
}
}
~stack() {
delete[] arr;
cout << "\nMemory Cleared.";
}
};
int main() {
int size;
int choice;
int elem;
cout << "Enter the size: ";
cin >> size;
stack<int> obj(size);
while(true) {
cout << "\n1. Push, 2. Pop, 3. Display, 0. Exit";
cout << "\nEnter your choice: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Enter the element: ";
cin >> elem;
obj.push(elem);
break;
case 2:
obj.pop();
break;
case 3:
obj.display();
break;
case 0:
return 0;
default:
cout << "\nWrong choice.";
}
}
}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
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