Subject Name :OOP 1
Practical 3.1
Definition :-Write a program to implement push and pop operations
import java.util.Scanner;
class Stack {
static final int MAX = 5;
int top = -1;
int[] stack = new int[MAX];
public void push(int value) {
if (top >= MAX - 1) {
System.out.println("Stack Overflow! Cannot push " + value);
} else {
stack[++top] = value;
System.out.println("Pushed " + value + " onto the stack");
}
}
public void pop() {
if (top < 0) {
System.out.println("Stack Underflow! Cannot pop");
} else {
System.out.println("Popped " + stack[top--] + " from the stack");
}
Enrolment No.230470107069
Page 1
Subject Name :OOP 1
public void display() {
if (top < 0) {
System.out.println("The stack is empty.");
} else {
System.out.print("Stack elements: ");
for (int i = 0; i <= top; i++) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
}
public class Stackexample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack stackObj = new Stack();
while (true) {
System.out.println("\nStack Operations Menu:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display Stack");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
Enrolment No.230470107069
Page 2
Subject Name :OOP 1
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value to push: ");
int value = scanner.nextInt();
stackObj.push(value);
break;
case 2:
stackObj.pop();
break;
case 3:
stackObj.display();
break;
case 4:
System.out.println("Exiting program.");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
Enrolment No.230470107069
Page 3
Subject Name :OOP 1
Output:
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 1
Enter value to push: 15
Pushed 15 onto the stack
Stack Operations Menu:
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice: 3
Stack elements: 15
Enrolment No.230470107069
Page 4