You are on page 1of 5

PRESIDENCY UNIVERSITY

Bengaluru, Karnataka
Computer Science & Engineering
School of Computer Science & Engineering

Subject: CSE2001 - Data Structures & Algorithms Semester: III


Lab Session : Ex 2 Date: 21/09/2023

Implementation of stack using array


import java.util.*;
public class stack_operations
{
static int value, top=-1,stack[]=new int[5],ch,i,choice;
static void push()
{
if(top<4)
{
Scanner sc1=new Scanner(System.in);
System.out.println("Enter the value to be inserted");
value=sc1.nextInt();
top=top+1;
stack[top]=value;
}
else
{
System.out.println("Stack Overflow-Stack is Full");
}
}
public void pop()
{
if(top==-1)
{
System.out.println("Stack Underflow");

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 1
}
else
{
System.out.println("Element popped is:"+stack[top]);
top=top-1;
}
}

public void display()


{
if(top==-1)
{
System.out.println("Stack is empty");
}
else
{
System.out.println("The elements of stack are");
for(i=top;i>=0;i--)
{
System.out.println(stack[i]);
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
stack_operations obj=new stack_operations();
System.out.println("Implementation of Stack operations");
ch=1;
while(ch==1)
{
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 2
System.out.println("Enter your choice");
System.out.println("1.Push\n2.Pop\n3.Traversal\n4.Exit");

choice=sc.nextInt();
switch(choice)
{

case 1: obj.push();
break;
case 2: obj.pop();
break;
case 3: obj.display();
break;
case 4: System.out.println("Enter 1 to continue or 0 to exit");
ch=sc.nextInt();
break;
}
}

}
}
Output:

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 3
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 4
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 5

You might also like