DSA LAB Task 1
DSA LAB Task 1
#include <iostream>
using namespace std;
public:
// Constructor to initialize the stack
Stack() {
top = -1; // Initialize top to -1 (empty stack)
}
// Main function
int main() {
// Create a Stack object
Stack stack;
Page 3 of 7
// Push items onto the stack
stack.push(5);
stack.push(10);
stack.push(20);
stack.push(30);
return 0;
}
Explanation:
1. Header Inclusion and Namespace
#include <iostream>
using namespace std;
Includes the iostream header for input/output operations and brings the standard
library namespace into scope.
2. Constant Definition
class Stack {
private:
int top;
int stack[MAX_SIZE];
Page 4 of 7
public:
// ...
};
Defines a Stack class with private members top (index of the top element) and
stack (array to store elements). Public member functions provide operations on the
stack.
4. Constructor
Stack() {
top = -1;
}
Initializes the stack by setting top to -1, indicating an empty stack.
5. Push Operation
6. Pop Operation
int pop() {
if (top == -1) {
cout << "Stack underflow!" << endl;
return -1;
}
return stack[top--];
}
Removes an item from the stack:
Checks for stack underflow (top is -1).
Returns the top item and decrements top.
Page 5 of 7
7. Peek Operation
int peek() {
if (top == -1) {
cout << "Stack is empty!" << endl;
return -1;
}
return stack[top];
}
Returns the top item without removing it:
Checks if the stack is empty.
Returns the top item.
8. IsEmpty Operation
bool isempty() {
return top == -1;
}
void printStack() {
if (top == -1) {
cout << "Stack is empty!" << endl;
return;
}
cout << "Stack (top to bottom):" << endl;
for (int i = top; i >= 0; i--) {
cout << stack[i] << endl;
}
}
Prints the stack from top to bottom:
Checks if the stack is empty.
Iterates from the top index to 0, printing each element.
Page 6 of 7
10. Main Function
int main() {
// ...
}
Demonstrates the usage of the Stack class:
Stack stack;
Creates a Stack object.
stack.push(5);
stack.push(10);
stack.push(20);
stack.push(30);
Adds four items to the stack.
stack.printStack();
Prints the remaining stack (10 and 5).
Example Output:
Peek: 30
Stack (top to bottom):
10
5
Page 7 of 7