class Stack {
int top;
int maxSize;
int[] stack;
// Constructor
Stack(int size) {
maxSize = size;
stack = new int[maxSize];
top = -1; // stack is empty
}
// PUSH operation
void push(int value) {
if (top == maxSize - 1) {
System.out.println("Stack Overflow! Cannot insert " + value);
} else {
top++;
stack[top] = value;
System.out.println(value + " pushed into stack");
}
}
// POP operation
void pop() {
if (top == -1) {
System.out.println("Stack Underflow! Stack is empty");
} else {
System.out.println(stack[top] + " popped from stack");
top--;
}
}
// PEEK operation
void peek() {
if (top == -1) {
System.out.println("Stack is empty");
} else {
System.out.println("Top element: " + stack[top]);
}
}
// Display stack
void display() {
if (top == -1) {
System.out.println("Stack is empty");
} else {
System.out.print("Stack elements: ");
for (int i = top; i >= 0; i--) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
}
}
// Step 2: Main Class to Run Program
public class Main {
public static void main(String[] args) {
Stack s = new Stack(5);
s.push(10);
s.push(20);
s.push(30);
s.display();
s.peek();
s.pop();
s.pop();
s.display();
}
}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.