Pre Selection Comp Project

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

Pre-Selection

Computer Science
Project

Shashank Mishra
XII A

12th Grade Computer Science


Q1. Write a Java program to create a class called Animal with a method called makeSound(). Create a
subclass called Cat that overrides the makeSound() method to bark.

Code:
public class Animal
{
public void makeSound()
{
System.out.println("The animal makes a sound.");
}
}
public class Cat extends Animal
{
public void makeSound()
{
System.out.println("The cat quarrels.");
}
}
public class Main
{
public static void main()
{
Animal animal = new Animal();
Cat cat = new Cat();
animal.makeSound();
cat.makeSound();
}
}

Output:
The animal makes a sound.
The cat quarrels.
Algorithm:
1. Start.
2. A public class Animal is made
3. In the Animal class, a public function voidMakesound() is made.
4. Inside Makesound(), the statement “The animal makes a sound” is printed
5. A public child class Cat is made which inherits the elements from the parent class Animal.
6. A public function void Makesound() is made where the statement “The cat quarrels” is printed.
7. A main class is made.
8. Void main() is made inside the main class
Animal class and Cat class are called.
9. MakeSound functions are also called.
10. Stop.

Q2. Write a Java program to create a class called Vehicle with a method called drive(). Create a
subclass called Car that overrides the drive() method to print "Repairing a car".

Code:
class Vehicle
{
public void drive()
{
System.out.println("Repairing a vehicle");
}
}
class Car extends Vehicle
{
public void drive()
{
System.out.println("Repairing a car");
}
}
public class Main
{
public static void main()
{
Vehicle vehicle = new Vehicle();
Car car = new Car();
vehicle.drive();
car.drive();
}
}

Output:
Repairing a vehicle.
Repairing a car.

Algorithm:
1. Start.
2. A public class Vehicle is made.
3. A public function void Drive() is made
4. Inside void Drive(), the statement, “Repairing a vehicle” is printed.
5. A child class Car is made which inherits the elements of Vehicle class.
6. A public function, void Drive() is made where the statement “Repairing a car” is printed.
7. A Main class is made where Vehicle class and Car class are called
8. Vehicle.drive and car.drive are also called.
9. Stop.

Q3. Write a Java program to create a class called Shape with a method called getArea(). Create
a subclass called Rectangle that overrides the getArea() method to calculate the area of a
rectangle.

Code:
public class Shape
{
public double getArea()
{
return 0.0;
}
}
public class Rectangle extends Shape
{
private double length;
private double width;

public Rectangle(double length, double width)


{
this.length = length;
this.width = width;
}
public double getArea()
{
return length * width;
}
}
public class Main
{
public static void main()
{
Rectangle rectangle = new Rectangle(3.0, 10.0);
double area = rectangle.getArea();
System.out.println("The area of the rectangle is: " + area);
}
}

Output:
The Area of the rectangle is : 30

Algorithm:
1. Start
2. A class Shape is made
3. A function void GetArea is made where 0.0 is initially returned
4. A child class Rectangle is made which inherits the elements from the Shape class
5. Two private double variables, length and width are taken.
6. A parameterised constructor is made where length and width are initialised to this.length and
this.width.
7. A function Double GetArea() is made where the area is calculated by returning the value of
length*width.
8. A main class is made where the parent and child classes are called, the constructor is called
and the functions are called.
9. The area of the rectangle is printed in the main class.
10. Stop.

Variable list:

Data name Data type Use


width double For storing Width of the rectangle.
length double For storing Length of the rectangle.

Q4. Write a Java program to create a class called Employee with methods called work() and
getSalary(). Create a subclass called HRManager that overrides the work() method and adds a new
method called addEmployee().

Code:
public class Employee
{
private int salary;

public Employee(int salary)


{
this.salary = salary;
}

public void work()


{
System.out.println("working as an employee!");
}
public int getSalary()
{
return salary;
}
}
public class HRManager extends Employee
{
public HRManager(int salary)
{
super(salary);
}

public void work()


{
System.out.println("\nManaging employees");
}

public void addEmployee()


{
System.out.println("\nAdding new employee!");
}
}
public class Main
{
public static void main()
{
Employee emp = new Employee(40000);
HRManager mgr = new HRManager(70000);

emp.work();
System.out.println("Employee salary: " + emp.getSalary());

mgr.work();
System.out.println("Manager salary: " + mgr.getSalary());
mgr.addEmployee();
}
}

Output:
Working as an employee!
Employee salary: 40000

Managing employees
Managing salary: 70000

Adding new employee!

Algorithm:
1. Start
2. A class Salary is made where an integer variable ‘salary’ is made.
3. A constructor is made where the ‘salary’ variable is initialised.
4. A public function void work is made where the statement “working as an employee!” is printed.
5. A function GetSalary is made where the salary is returned.
6. A child class HRManager is made which inherits the elements of the Salary class
7. A constructor is made where super(salary) is used and it is initialised.
8. Void work is made where the statement “managing employees” is printed on the next line.
9. Void AddEmployee is made where the statement “Adding new employee” is printed on the next
line.
10. A class main is made where void main is made
11. Inside void main, Employee class and HRManager class is called and the salaries of employee
and HR Manager are printed.
12. Stop.
Variable List:

Data name Data type Use


salary int Stores salary of employee
emp address Memory space for salary
mgr address Memory space for salary

Q5. Write a Java program to create a class known as "BankAccount" with methods called
deposit() and withdraw(). Create a subclass called SavingsAccount that overrides the
withdraw() method to prevent withdrawals if the account balance falls below one hundred.

Code:
public class BankAccount
{
private String accountNumber;
private double balance;

public BankAccount(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

public void deposit(double amount)


{
balance += amount;
}

public void withdraw(double amount)


{
if (balance >= amount)
{
balance -= amount;
}
else
{
System.out.println("Insufficient balance");
}
}

public double getBalance() {


return balance;
}
}
public class SavingsAccount extends BankAccount
{
public SavingsAccount(String accountNumber, double balance) {
super(accountNumber, balance);
}

public void withdraw(double amount)


{
if (getBalance() - amount < 100)
{
System.out.println("Minimum balance of $100 required!");
}
else
{
super.withdraw(amount);
}
}
}
public class Main
{
public static void main()
{
System.out.println("Create a Bank Account object (A/c No. BA1234) with initial balance of $500:");

BankAccount BA1234 = new BankAccount("BA1234", 500);

System.out.println("Deposit $1000 into account BA1234:");


BA1234.deposit(1000);
System.out.println("New balance after depositing $1000: $" + BA1234.getBalance());
System.out.println("Withdraw $600 from account BA1234:");
BA1234.withdraw(600);
System.out.println("New balance after withdrawing $600: $" + BA1234.getBalance());

System.out.println("\nCreate a SavingsAccount object (A/c No. SA1234) with initial


balance of $450:");
SavingsAccount SA1234 = new SavingsAccount("SA1234",450);

SA1234.withdraw(300);
System.out.println("Balance after trying to withdraw $300: $" + SA1234.getBalance());

System.out.println("\nCreate a SavingsAccount object (A/c No. SA1000) with initial


balance of $300:");
SavingsAccount SA1000 = new SavingsAccount("SA1000",300);

System.out.println("Try to withdraw $250 from SA1000!");


SA1000.withdraw(250);
System.out.println("Balance after trying to withdraw $250: $" + SA1000.getBalance());
}
}

Algorithm:
1. Start
2. Class BankAccount is made
3. Variables String accountNumber and double balance is taken
4. A parameterised constructor is made where the variables are initialised by this.accountNumber
and this.balance.
5. A parameterised function void deposit is made where balance = +amount is done
6. A parameterised function void withdraw is made where it is checked that if balance is less than
that of required amount then money cannot be withdrawn
7. If sufficient balance is there, then money can be withdrawn, which is done by the function double
getBalance().
8. A child class SavingsAccount is made which inherits all the elements of the class
CurrentAccount.
9. Variables accountNumber and balance are called from parent class by using “super” in the
parameterised constructor
10. A parameterised function void Withdraw is made which checks whether there is a balance of at
least 100 in the bank account or not. If not then money cannot be withdrawn.
11. Main class is made
12. In the main function, Account number is printed, initial balance is printed and withdrawn amount
is printed from both savings account and current account.
13. Stop.

Variable list:

Data name Data Type Use


Account number String Account number is stored
balance Double Balance is stored which is present in
savings account and current account
amount Double Amount withdrawn in savings account
and current account

Q6. Write a Java program to create a class called Animal with a method named move(). Create a
subclass called Cheetah that overrides the move() method to run.

Code:
class Animal {
public void move() {
System.out.println("Animal moves");
}
}
class Cheetah extends Animal {
public void move() {
super.move();
System.out.println("This cheetah is running!");
}
}
Output:
Animal moves
This cheetah is running!

Algorithm:
1. Start
2. create a class Animal
3. in void main, print “Animal moves”
4. create a child class called Cheetah
5. in void main, call move() of parent class and print “This cheetah is running”
6. Stop

Q7. Write a Java program to create a class known as Person with methods called getFirstName() and
getLastName(). Create a subclass called Employee that adds a new method named getEmployeeId() and
overrides the getLastName() method to include the employee's job title.

Program:
public class Person {
private String firstName;
private String lastName;

public Person(String firstName, String lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {


return firstName;
}

public String getLastName() {


return lastName;
}
}
public class Employee extends Person {
private int employeeId;
private String jobTitle;

public Employee(String firstName, String lastName, int employeeId, String jobTitle) {


super(firstName, lastName);
this.employeeId = employeeId;
this.jobTitle = jobTitle;
}

public int getEmployeeId() {


return employeeId;
}

public String getLastName() {


return super.getLastName() + ", " + jobTitle;
}
public static void main() {
Employee employee1 = new Employee("Saptak", "Bhattacharya", 4451, "HR Manager");
System.out.println(employee1.getFirstName() + " " + employee1.getLastName() + " (" +
employee1.getEmployeeId() + ")");
Employee employee2 = new Employee("Junior", "Philipa", 4452, "Software Manager");
System.out.println(employee2.getFirstName() + " " + employee2.getLastName() + " (" +
employee2.getEmployeeId() + ")");
}
}

Output:
Saptak Bhattacharya, HR Manager (4451)
Junior Philipa, Software Manager (4452)

Algorithm:
1. Start
2. create a class person and make two variables for storing first and last name of the employee
3. create a parameterised constructor to initialise the variables
4. create methods to store first and last name of the employee
5. create a child class called Employee
6. create variables for storing employee id and job title
7. create a parametrised constructor to initialise first and last name, id and title of employee
8. create methods for storing employee id and title
9. create main function to display employee name, id and position
10. Stop

Variables list:

Data name Data type Description

firstName String Stores first name of the


employee

lastName String Stores last name of the


employee

employeeId Integer Stores id of the employee

jobTitle String Stores job title of the


employee

Q8. A line on a plane can be represented by coordinates of the two-end points p1 and p2 as
p1(x1, y1) and p2(x2, y2).
A superclass Plane is defined to represent a line and a subclass Circle to find the length of the
radius and the area of the circle by using the required data members of the superclass. Some
of the members of both classes are given below:
Class name: Plane
Data members/instance variables:
x1: to store the x-coordinate of the first endpoint
y1: to store the y-coordinate of the first endpoint
Member functions/methods:
void input (): input x and y
void show(): to display the coordinates
Class name: Circle
Data members: x2: to store the x-coordinate of the second endpoint
y2: to store the y-coordinate of the second endpoint
radius: double variable to store the radius of the circle
area: double variable to store the area of the circle Member functions/methods
Circle(…): parameterized constructor to assign values to data members of both the classes
void findRadius(): to calculate the length of the radius using the formula: assuming that x1, x2,
y1, y2 are the coordinates of the two ends of the diameter of a circle
voidfindArea(): to find the area of a circle using the formula: πr2 . The value of pie(π) is 22/7
or 3.14
void show(): to display both the coordinates along with the length of the radius and area of the
circle
Specify the class Plane giving details of the constructor and void show() Using the concept of
inheritance, specify the class Circle giving details of the constructor, void findRadius(), void
find Area() and voidShow()

Program:
class Plane {
int x1; int y1;
public Plane(int nx, int ny) {
x1=nx; y1=ny;
}
public void show() {
System.out.println("P1: "+x1 +", "+y1);
}
}
class Circle extends Plane {
int x2; int y2; double radius; double area;
public Circle(int nx1, int ny1, int nx2, int ny2) {
super(nx1, nx2);
x2=nx2; y2=ny2;
}
public void fmdRadius() {
radius=Math.sqrt(Math.pow((x2-x1), 2)+Math.pow((y2-y1), 2))/2.0;
}
public void findArea() {
area=Math.pow(radius,2)*(22/7)*radius*radius;
}
public void show(){
super. show();
System.out.println("P2: "+x2+", "+y2);
System.out.println("Radius:"+radius);
System.out.println("Area: "+area);
}
public static void main(String args[]) {
Circle obj=new Circle(2, 3, 4, 5);
obj.findRadius();
obj.findArea();
obj.show();
}
}

Output:
P1: 5,6
P2: 8,10
Radius: 5.0
Area: 78.571428571428571

Algorithm:
1. Start
2. create a class plane and make two variables for storing coordinates
3. create a parameterised constructor to initialise the variables
4. print the coordinates
5. create a child class called Circle
6. create variables for second coordinate, area and radius of the circle
7. create a parameterised constructor to initialise both the coordinates
8. create methods to calculate radius and are of the circle
9. print the coordinates, radius and area of the circle
10. create a class to call all member methods
11. Stop

Variables list:

Data name Data type Description

x1 Integer Stores x coordinate

y1 Integer Stores y coordinate

nx Integer Used to initialise x


coordinate

ny Integer Used to initialise y


coordinate

x2 Integer Stores 2nd x coordinate

y2 Integer Stores 2nd y coordinate

radius Integer Stores radius of the


circle

area Integer Stores area of the circle

nx1 Integer Used to initialise 1st x


coordinate

nx2 Integer Used to initialise 2nd x


coordinate

ny1 Integer Used to initialise 1st y


coordinate

ny2 Integer Used to initialise 2nd y


coordinate
Q.9 Class name Data members result to enter values for nl and n2. to display the values of n1
and n2. dervPro float variables whose product is to be determined Member
Functions/methods : void prod(): void disp(): to accept values for n1 and n2 and to calculate
their product using the concept of Inheritance. to display the values of n1, n2 and their product.
Specify the class basePro giving details of the functions void enter() and void show(). Using the
Concept of Inheritance specify the class dervPro, giving the details of the functions void prod( )
and void disp( ).

Program:
class basePro {
float n1, n2;
void enter(float num1, float num2) {
n1 = num1;
n2 = num2;
}
void show() {
System.out.println("n1 = " + n1);
System.out.println("n2 = " + n2);
}
}
class dervPro extends basePro {
float result;
void prod() {
result = n1 * n2;
}
void disp() {
show();
System.out.println("Product = " + result);
}
public static void main() {
dervPro obj = new dervPro();
obj.enter(3.5f, 2.0f);
obj.prod();
obj.disp();
}
}

Output:
n1 = 3.5
n2 = 2.0
Product = 7.0

Algorithm:

1. Start
2. create a class basePro, and make two variables for numbers
3. create num1 and num2 in parameter using them initialise numbers
4. print both numbers
5. create a child class called dervPro
6. create a variable to store product, make a method to calculate their product and display the
numbers and their product

Variables list:

Data name Data type Description

n1 Float Stores 1st number

n2 Float Stores 2nd number

num1 Float Used to initialise 1st number

num2 Float Used to initialise 2nd number

result Float Stores product of two numbers

Program 10: Write a Java program to create a class called Animal with a method named move().
Create a subclass called Cheetah that overrides the move() method to run.
Program:
class Animal {
public void move() {
System.out.println("Animal moves");
}
}
class Cheetah extends Animal {
public void move() {
super.move();
System.out.println("This cheetah is running!");
}
}

Output:
Animal moves
This cheetah is running!

Algorithm:
Start:
Step 1: create a class Animal
Step 2: in void main, print “Animal moves”
Step 3: crate a child class called Cheetah
Step 4: in void main, call move() of parent class and print “This cheetah is ruuning”
Stop

Program 11: Write a Java program to create a class known as Person with methods called
getFirstName() and getLastName(). Create a subclass called Employee that adds a new method
named getEmployeeId() and overrides the getLastName() method to include the
employee's job title.
Program:
public class Person {
private String firstName;
private String lastName;

public Person(String firstName, String lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {


return firstName;
}
public String getLastName() {
return lastName;
}
}
public class Employee extends Person {
private int employeeId;
private String jobTitle;

public Employee(String firstName, String lastName, int employeeId, String jobTitle) {


super(firstName, lastName);
this.employeeId = employeeId;
this.jobTitle = jobTitle;
}

public int getEmployeeId() {


return employeeId;
}

public String getLastName() {


return super.getLastName() + ", " + jobTitle;
}
public static void main() {
Employee employee1 = new Employee("Shashank", "Mishra", 4451, "HR Manager");
System.out.println(employee1.getFirstName() + " " + employee1.getLastName() + " (" +
employee1.getEmployeeId() + ")");
Employee employee2 = new Employee("Junior", "Philipa", 4452, "Software Manager");
System.out.println(employee2.getFirstName() + " " + employee2.getLastName() + " (" +
employee2.getEmployeeId() + ")");
}
}

Output:
Shashank Mishra, HR Manager (4451)
Junior Philipa, Software Manager (4452)

Algorithm:
Start:
Step 1: create a class person and make two variables for storing first and last name of the
employee
Step 2: create a parameterised constructor to initialise the variables
Step 3: create methods to store first and last name of the employee
Step 4: create a child class called Employee
Step 5: create variables for storing employee id and job title
Step 6: create a parametrised constructor to initialise first and last name, id and title of
employee
Step 7: create methods for storing employee id and title
Step 8: create main function to display employee name, id and position
Stop

Variables list:
Data name Data type Description
firstName String Stores first name of the
employee
lastName String Stores last name of the
employee
employeeId Integer Stores id of the employee
jobTitle String Stores job title of the
employee

Program 12: A line on a plane can be represented by coordinates of the two-end points p1 and p2
as p1(x1, y1) and p2(x2, y2).
A superclass Plane is defined to represent a line and a subclass Circle to find the length of the
radius and the area of the circle by using the required data members of the superclass. Some of
the members of both classes are given below:
Class name: Plane
Data members/instance variables:
x1: to store the x-coordinate of the first endpoint
y1: to store the y-coordinate of the first endpoint
Member functions/methods:
void input (): input x and y
void show(): to display the coordinates
Class name: Circle
Data members: x2: to store the x-coordinate of the second endpoint
y2: to store the y-coordinate of the second endpoint
radius: double variable to store the radius of the circle
area: double variable to store the area of the circle Member functions/methods
Circle(…): parameterized constructor to assign values to data members of both the classes void
findRadius(): to calculate the length of the radius using the formula: assuming that x1, x2, y1, y2 are the
coordinates of the two ends of the diameter of a circle
voidfindArea(): to find the area of a circle using the formula: πr2 . The value of pie(π) is 22/7 or 3.14
void show(): to display both the coordinates along with the length of the radius and area of the circle
Specify the class Plane giving details of the constructor and void show() Using the concept of
inheritance, specify the class Circle giving details of the constructor, void findRadius(), void find Area()
and voidShow()
Program:
class Plane {
int x1; int y1;
public Plane(int nx, int ny) {
x1=nx; y1=ny;
}
public void show() {
System.out.println("P1: "+x1 +", "+y1);
}
}
class Circle extends Plane {
int x2; int y2; double radius; double area;
public Circle(int nx1, int ny1, int nx2, int ny2) {
super(nx1, nx2);
x2=nx2; y2=ny2;
}
public void fmdRadius() {
radius=Math.sqrt(Math.pow((x2-x1), 2)+Math.pow((y2-y1), 2))/2.0;
}
public void findArea() {
area=Math.pow(radius,2)*(22/7)*radius*radius;
}
public void show(){
super. show();
System.out.println("P2: "+x2+", "+y2);
System.out.println("Radius:"+radius);
System.out.println("Area: "+area);
}
public static void main(String args[]) {
Circle obj=new Circle(2, 3, 4, 5);
obj.findRadius();
obj.findArea();
obj.show();
}
}

Output:
P1: 5,6
P2: 8,10
Radius: 5.0
Area: 78.571428571428571
Algorithm:
Start
Step 1: create a class plane and make two variables for storing coordinates
Step 2: create a parameterised constructor to initialise the variables
Step 3: print the coordinates
Step 4: create a child class called Circle
Step 5: create variables for second coordinate, area and radius of the circle
Step 6: create a parameterised constructor to initialise both the coordinates
Step 7: create methods to calculate radius and are of the circle
Step 8: print the coordinates, radius and area of the circle
Step 9: create a class to call all member methods
Stop

Variables list:
Data name Data type Description
x1 Integer Stores x coordinate
y1 Integer Stores y coordinate
nx Integer Used to initialise x coordinate
ny Integer Used to initialise y coordinate
x2 Integer Stores 2nd x coordinate
y2 Integer Stores 2nd y coordinate
radius Integer Stores radius of the circle
area Integer Stores area of the circle
nx1 Integer Used to initialise 1st x
coordinate
nx2 Integer Used to initialise 2nd x
coordinate
ny1 Integer Used to initialise 1st y
coordinate
ny2 Integer Used to initialise 2nd y
coordinate

Program 13: Class name Data members result to enter values for nl and n2. to display the values of n1
and n2. dervPro float variables whose product is to be determined Member Functions/methods : void
prod(): void disp(): to accept values for n1 and n2 and to calculate their product using the concept of
Inheritance. to display the values of n1, n2 and their product. Specify the class basePro giving details of
the functions void enter() and void show(). Using the Concept of Inheritance specify the class dervPro,
giving the details of the functions void prod( ) and void disp( ).
Program:
class basePro {
float n1, n2;
void enter(float num1, float num2) {
n1 = num1;
n2 = num2;
}
void show() {
System.out.println("n1 = " + n1);
System.out.println("n2 = " + n2);
}
}
class dervPro extends basePro {
float result;
void prod() {
result = n1 * n2;
}
void disp() {
show();
System.out.println("Product = " + result);
}
public static void main() {
dervPro obj = new dervPro();
obj.enter(3.5f, 2.0f);
obj.prod();
obj.disp();
}
}

Output:
n1 = 3.5
n2 = 2.0
Product = 7.0

Algorithm:
Start
Step 1: create a class basePro, and make two variables for numbers
Step 2: create num1 and num2 in parameter using them initialise numbers
Step 3: print both numbers
Step 4: create a child class called dervPro
Step 5: create a variable to store product, make a method to calculate their product and display the
numbers and their product

Variables list:
Data name Data type Description
n1 Float Stores 1st number
n2 Float Stores 2nd number
num1 Float Used to initialise 1st number
num2 Float Used to initialise 2nd number
result Float Stores product of two
numbers

Program 14: Queue


Algorithm:
Start
Step 1: Create a `Queue` class with instance variables `f`, `r`, `cap`, and `array`.
Step 2: Define a constructor `Queue(int max)` that initializes the instance variables with the given
values.
Step 3: Implement a method `capacity()` that returns the capacity of the queue.
Step 4: Implement a method `insert(int elem)` to insert an element into the queue:
Check if the rear pointer `r` is equal to the capacity minus one.
If true, print "Queue Overflow" and exit the program.
If the front pointer `f` and rear pointer `r` are both -1, set them to 0.
Increment the rear pointer `r` by 1.
Assign the element `elem` to the array at index `r`.
Step 5: Implement a method `delete()` to delete an element from the queue:
Check if the front pointer `f` is -1.
If true, print "Queue Underflow" and exit the program.
Otherwise, print "Element deleted = " followed by the value at the front of the array.
If the front pointer `f` is equal to the rear pointer `r`, set both pointers to -1.
Otherwise, increment the front pointer `f` by 1.
Step 6: Implement a method `displayQueue()` to display the elements of the queue:
Print "The Queue is: ".
Check if the front pointer `f` is greater than or equal to 0 and the rear pointer `r` is greater than
or equal to the front pointer `f`.
If true, iterate from the front pointer `f` to the rear pointer `r` and print each element in the array.
Step 7: In the `main` method:
10. End

Code:
import java.util.Scanner;
public class Queue {
int f, r, cap;
int[] array;
Queue(int max) {
this.cap = max;
this.array = new int[this.cap];
this.f = -1;
this.r = -1;
}
int capacity(){
return this.cap;
}

void insert(int elem) {


if(this.r == this.cap - 1) {
System.out.println("Queue Overflow.");
System.exit(1);
} else if(this.f == -1 && this.r == -1) {
this.f = 0;
this.r = 0;
} else {
this.r++;
}
this.array[r] = elem;
}

void delete(){
if(f == -1) {
System.out.println("Queue Underflow.");
System.exit(1);
} else {
System.out.println("Element deleted = " + this.array[this.f]);
if(this.f == this.r){
this.f = -1;
this.r = -1;
} else {
this.f++;
}
}
}

void displayQueue() {
System.out.println("The Queue is : ");
if(f >= 0 && r >= f) {
for (int i = f; i <= r; ++i)
System.out.print(this.array[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter capacity = ");
Queue queue = new Queue(sc.nextInt());
System.out.println("Enter integer followed by p to push to queue/ followed by d to delete from
queue/ x to stop = ");
String n = "", op = "";
while(!op.equalsIgnoreCase("x")) {
n = sc.next();
op = sc.next();
if(op.equalsIgnoreCase("p")){
queue.insert(Integer.parseInt(n));
} else if(op.equalsIgnoreCase("d")) {
queue.delete();
}
queue.displayQueue();
}
}

}
Variable List:

Variabl
e Data Type Description
f int Pointer to the front of the queue
r int Pointer to the rear of the queue
cap int Capacity of the queue
array int[] Array to store the elements of the queue

Program 15: Employee


Code:
import java.util.Scanner;
public class Bank
{
String name;
int accno ;
double p ;
Bank(String n, int a, double pp)
{
name=n;
accno =a;
p =pp;
}
void display( )
{
System.out.println( "Name = "+name);
System.out.println("Accout no = "+accno);
System.out.println("Principal amount = " +p;
}
}

public class Account extends Bank


{
static Scanner sc=new Scanner(System.in);
double amt;
Account(String n, String a, double pp)
{
super(n,a,pp);
amt=0.0;
}
void deposit( )
{
System.out.print("\n Enter amount");
amt=sc.nextDouble();
p=p-amt;.
}
void withdraw()
{
System.out.print("\n Enter amount");
amt=sc.nextDouble();
if(amt>p)
System.out.println("INSUFFICIENT BALANCE");
else
{
p=p-amt;
if(p<500)
p=p-(500-p)/10;
}
}
void display()
{
super.display();
System.out.println("Enter amount = "+amt);
}
ALGORITHM :
Start
Step 1: Define a Bank class:
Step 2: Declare instance variables name, accno, and p for storing account information.
Step 3: Create a parameterized constructor Bank(String n, int a, double pp) to initialize the instance
variables.
Step 4: Define a method display():
Step 5: Define an Account class that inherits from the Bank class:
Step 6: Define methods for deposit and withdrawal:
Step 7: Create a method deposit():
Step 8: Override the display() method:
Step 9: Inside the main method or a separate main class:
Create an instance of the Account class by calling its constructor with appropriate values.
End

Variable
Name Type Description
Holds the name of the account
name String
holder.

accno int Stores the account number.

p double Stores the principal amount.

amt double Stores the transaction amount.

sc Scanner Scanner object for user input.

Program 16: ASCII of each character


Algorithm:
1. Start
2. Accept and store the word entered by the user.
3. Using a for-loop, iterate over each letter in the word and type-cast to integer and print this
integer.
4. E ccnd.
Code:
import java.util.*;
class String1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word = ");
String w = sc.next();
System.out.println("Given word is : " + w);
for(int i = 0; i < w.length(); ++i) {
System.out.println("The ASCII of " + w.charAt(i) + " = " + (int)(w.charAt(i)));
}
}
}
Variable List

Name Data Type Description


w String Stores the input word
i int Used for iteration

Program 17: Index of First Vowel


Algorithm:
1. Start
2. Accept and store the word entered by the user and convert it to uppercase to make it easier for
comparison.
3. Initialize a character array with 5 vowels in uppercase.
4. For each element in the character array check its index using inbuilt function, if it returns a
non-negative result then print it as the index of the first vowel and exit the function.
5. Report absence of vowels.
6. End
Code:
import java.util.*;
class String2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word = ");
String w = sc.next().toUpperCase();
final char[] vowels = {'A', 'E', 'I', 'O', 'U'};
for(int i = 0; i < vowels.length; ++i) {
if(w.indexOf(vowels[i]) != -1){
System.out.println("First vowel " + ch + " at = " + w.indexOf(ch));
return;
}
}
System.out.println("Sorry no vowel");
}S
}
Variable List:

Name Data Type Description


wo log String Accepts and stores the word entered by the user.
vowels char[] Stores all the possible vowels in the English alphabet in uppercase.
i int Used for iteration

Program 18: Array to Stack conversion.


Algorithm:
1. Start
2. The constructor accepts the maximum limit of the array as an argument.
3. The capacity variable is assigned with the value of the max.
4. The variable called top which points to the top of the stack is assigned the value of -1 as the
stack is empty.
5. Two integer arrays of the same length as capacity are initialized.
6. End
Method push_marks (argument : integer mark)
1. Start
2. If top is equal to capacity minus 1 print stack overflow and exit the program
3. Else
4. Assign the top-th element of the st array with the value of mark.
5. Increment top by 1.
6. End
Method pop_marks returns integer
1. Start
2. If top is equal to minus 1 then print stack underflow and exit the program
3. Else
4. Decrement top by minus 1
5. Return the top-th element of the st
6. End
Method input
1. Start
2. Input the number of elements in m and push them one by one in the stack
3. End
Code:
import java.util.Scanner;
public class ArrayToStack {
int[] st, m;
int cap, top;
ArrayToStack(int max) {
this.cap = max;
this.top = -1;
this.st = new int[this.cap];
this.m = new int[this.cap];
}
void push_marks(int mark) {
if(this.top == this.cap - 1) {
System.out.println("Stack OVERFLOW!");
System.exit(-1);
}
this.st[++top] = mark;
}
int pop_marks() {
if(this.top == -1) {
System.out.println("Stack UNDERFLOW");
return -999;
} else {
return this.st[top--];
}
}
void input() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of " + this.cap + " students = ");
for(int i = 0; i < this.cap; ++i){
this.m[i] = sc.nextInt();
}
sc.close();
for(int i = 0; i < this.cap; ++i){
int k = i;
for(int j = i + 1; j < this.cap; ++j){
if(this.m[k] < this.m[k])
k = j;
}
this.push_marks(this.m[k]);
}
}

}
Variable List

Name Data Type Description


cap int Stores the maximum capacity of the stack.
st int[] This is the array used as the stack.
m int[] This is the array which accepts the elements entered by the user.
top int Points to the top of the stack
i int Used to iterate over the array.
j int Used in the inner loop.
k int It is used to temporarily store the index value.
mark int It is an argument used to accept the mark to be pushed to the stack.
Program 19: Book Management System Library
Algorithm:
1. Start
2. Declare a class named "Book" with instance variables: "max" (integer), "point" (integer), and "name"
(array of strings).
3. Define a constructor for the "Book" class that takes an integer parameter "cap".
4. Inside the constructor:
a. Assign the value of "cap" to the "max" variable.
b. Set "point" to -1.
c. Create a new string array "name" with a size equal to "max".
5. Define a method named "add" that takes a string parameter "v".
6. Inside the "add" method:
a. Check if "point" is equal to "max - 1".
i. If true, display the message "STACK IS FULL CANNOT ADD ANYMORE".
ii. If false, proceed to the next step.
b. Assign a new instance of the "String" class with the value of "v" to "name[point++]".
7. Define a method named "tell".
8. Inside the "tell" method:
a. Check if "point" is equal to -1.
i. If true, display the message "STACK IS EMPTY NO BOOKS".
ii. If false, proceed to the next step.
b. Display the message "Last book entered: " concatenated with "name[point]".
9. Define a method named "display".
10. Inside the "display" method:
a. Display the message "Books present now: ".
b. Use a loop from 0 to "point" (inclusive) with a variable "i".
i. Display "name[i]" followed by a space character.
c. Display a new line character.
11. End
Code:
class Book {
int max, point;
String[] name;
Book(int cap){
max = cap;
point = -1;
name = new String[max]; }
void add(String v) {
if(point == max - 1){
System.out.println("STACK IS FULL CANNOT ADD ANYMORE");
} else {
name[point++] = new String(v);
}}
void tell() {
if(point == -1) {
System.out.println("STACK IS EMPTY NO BOOKS");
} else {
System.out.println("Last book entered : " + name[point]);
}}
void display() {
System.out.println("Books present now : ");
for(int i = 0; i <= point; ++i) {
System.out.print(name[i] = " ");
}
System.out.println();
}}
Variable Data Type Description
max int Maximum capacity of the stack
point int Index of the last book in the stack
name String[] Array to store book names
cap int Capacity parameter for the constructor
v String Book name to be added
i int Loop variable for display method

THE END

You might also like