0% found this document useful (0 votes)
7 views

Computer PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Computer PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

CONTENTS -

Page Teach
Sl. No. Date Topics / Program Statements
No. er’s
Signa
ture
1. Introduction to Object Oriented Programming 5
1.1 - Object in OOP 5

1.2 - Data Abstraction 5

1.3 - Abstract Class 5

1.4 - Inheritance 5

1.5 - Final Class 5

1.6 - Encapsulation 5

1.7 - Modularity 5

1.8 - Polymorphism 5

2. Introduction to Programming in Java 6


2.1 - Concept of Compilers and Interpreters 6
2.2 - Byte Code 6

2.3 - JVM – Java Virtual Machine 6

3. Introduction to Constructors in Java 7

3.1 - Use of the “static” keyword 7

3.2 - Use of the “this” keyword 7

4. Java Programs Based on Constructor 9

4.1 - Assignment 1 9

4.2 - Assignment 2 12

4.3 - Assignment 3 15

4.4 - Assignment 4 18

4.5 - Assignment 5 21

Number based Programs in Java 24


5.

5.1 - Assignment 1 24

5.2 - Assignment 2 27

5.3 - Assignment 3 30

Page 1 of 127
5.4 - Assignment 4 33

5.5 - Assignment 5 36

6. Series Based Programs in Java 40

6.1 - Assignment 1 40

6.2 - Assignment 2 43

6.3 - Assignment 3 46

6.4 - Assignment 4 49

6.5 - Assignment 5 52

7. Method Overloading Programs in Java 55

7.1 - Assignment 1 55

7.2 - Assignment 2 58

7.3 - Assignment 3 51

7.4 - Assignment 4 54

7.5 - Assignment 5 57

8. String Based Programs in Java 60

8.1 - Assignment 1 60

8.2 - Assignment 2 63

8.3 - Assignment 3 66

8.4 - Assignment 4 69

8.5 - Assignment 5 72
Java Programs Based on Arrays, Searching 75
9.
and Sorting in an Array
9.1 - Assignment 1 75

9.2 - Assignment 2 78

9.3 - Assignment 3 81

9.4 - Assignment 4 84

9.5 - Assignment 5 87

10. Conclusion 90

11. Bibliography 91

Page 2 of 127
2. INTRODUCTION TO OBJECT ORIENTED
PROGRAMMING
Write at least one paragraph on the following topics –
- 2.1 - Object in OOP
In object-oriented programming (OOP), objects are the things you think about first in designing a program
and they are also the units of code that are eventually derived from the process.
- 2.2 - Data Abstraction
Data abstraction is the reduction of a particular body of data to a simplified representation of the whole.
Abstraction, in general, is the process of removing characteristics from something to reduce it to a set of
essential elements. To this end, data abstraction creates a simplified representation of the underlying data,
while hiding its complexities and associated operations. In computing, data abstraction is commonly used in
object-oriented programming (OOP) and when working with a database management system (DBMS).
- 2.3 - Abstract Class
An abstract class is a class that contains at least one abstract method. An abstract method is a method that is
declared, but not implemented in the code.
- 2.4 – Inheritance
When a class derives from another class. The child class will inherit all the public and protected properties and
methods from the parent class. In addition, it can have its own properties and methods. An inherited class is
defined by using the extends keyword.
- 2.5 - Final Class
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be
overridden by subclasses. Preventing the class from being subclassed could be particularly useful if you write
APIs or libraries and want to avoid being extended to alter base behaviour.
- 2.6 – Encapsulation
Object-oriented computer programming (OOP) languages, the notion of encapsulation (or OOP Encapsulation)
refers to the bundling of data, along with the methods that operate on that data, into a single unit. Many
programming languages use encapsulation frequently in the form of classes.
- 2.7 – Modularity
Modularity is the process of decomposing a problem (program) into a set of modules so as to reduce the
overall complexity of the problem. Booch has defined modularity as − “Modularity is the property of a system
that has been decomposed into a set of cohesive and loosely coupled modules.”
- 2.8 – Polymorphism
Polymorphism is one of the core concepts of object-oriented programming (OOP) and describes situations in
which something occurs in several different forms. In computer science, it describes the concept that you can
access objects of different types through the same interface. Each type can provide its own independent
implementation of this interface.

Page 3 of 127
3. INTRODUCTION TO PROGRAMMING IN
JAVA
- 3.1 - Concept of Compilers and Interpreters and the Program Execution Process in Java

i. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an output of low-level la
nguage i.e. machine or assembly language.

 A compiler is more intelligent than an assembler it checks all kinds of limits, ranges, errors, etc.
 But its program run time is more and occupies a larger part of memory. It has a slow speed because a compiler
goes through the entire program and then translates the entire program into machine codes.

ii. Interpreter:
An interpreter is a program that translates a programming language into a comprehensible
language. –

 It translates only one statement of the program at a time.


 Interpreters, more often than not are smaller than compilers.

- 3.2 - Byte Code

Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source
code(JAVA Program). This intermediate code makes Java a platform-independent language.

- 3.3 - JVM – Java Virtual Machine

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which
java bytecode can be executed.

Page 4 of 127
4. INTRODUCTION TO CONSTRUCTORS IN
JAVA
- 4.1 – Use of the “static”
Keyword

In Java, the static keyword is primarily used for memory management. We can use the static keyword
with variables, methods, blocks, and classes. Using the static class is a way of grouping classes
together. It is also used to access the primitive member of the enclosing class through the object
reference.

4.2 – Use of the “this” keyword

The this keyword refers to the current object in a method or constructor. The most common use of the
this keyword is to eliminate the confusion between class attributes and parameters with the same
name (because a class attribute is shadowed by a method or constructor parameter).
-

Page 5 of 127
OUTPUT-

Page 6 of 127
5. JAVA PROGRAMS BASED ON CONSTRUCTORS
5.1 - Assignment 1:
Excel Transport Limited charges for the parcels of its customer as per the following
specificationsgiven below:

Class name: ETLimited

Member variables:
String cname – to store the name of the customer
int wt – to store the weight of the parcels in kilogram (kg)
double charges – to store the charges for the parcel

Member functions:
void accept ( )– to accept the name of the customer, weight of the parcel from the user
(usingScanner class)
void calculate ( ) – to calculate the charges as per the weight of the parcelas per the
following criteria.

Weight in kg Charges per kg (in Rs.)


Up to 20 kgs 50 per kg
Next 30 kgs 30 per kg
Above 50 kgs 20 per kg
A surcharge of 5 % is charged on the bill.

void display ( ) – to print the name of the customer, weight of the parcel, total bill
amountinclusive of surcharge in a tabular form in the following format :
Name Weight Bill amount

Define a class with the above mentioned specifications, create the main method,
create anobjectand invoke the member functions.

INPUT
Enter the name of the customer : Devjit
Mondal Enter the weight of the parcels in
kilogram (kg) : 13
Page 7 of 127
OUTPUT
Name Weight Bill amount
Devjit Mondal 13 ₹ 682.5

INPUT
Enter the name of the customer : Rahul
Banerjee Enter the weight of the parcels in
kilogram (kg) : 25

OUTPUT
Name Weight Bill amount
Rahul Banerjee 25 ₹ 1207.5

INPUT
Enter the name of the customer : Aman
Mukherjee

Enter the weight of the parcels in kilogram


(kg) : 64

OUTPUT
Name Weight Bill amount
Aman Mukherjee 64 ₹ 2289.0

import java.util.Scanner;
public class ETLimited
{
private String cname;
private int wt;
private double charges;
private double char1;
void accept()
{
Scanner sc =new Scanner(System.in);
System.out.print("Enter the name of customer: ");
cname = sc.nextLine();
System.out.print("Enter the weight of the parcel: ");
wt = sc.nextInt();
Page 8 of 127
}
void calculate()
{
{
if(wt<=20)
charges = wt * 50;
else if(wt<=50)
charges = 1000 +((wt-20)*30);
else
charges = 1000 + 900 + ((wt-50)*20);
}
char1= (5/100) * charges ;
charges = charges + char1;
}
void display()
{
System.out.println(" Name Weight
BillAmount");
System.out.println(""+cname+ " " +wt+ "
" +charges);
}
public static void main(String args[])
{
asg5_1 ob = new asg5_1();
ob.accept();
ob.calculate();
ob.display();
}

Page 9 of 127
VDT-

Variable name Type Purpose


wt Int To accept the weight of the
parcel
charges double to store the charges for the
parcel
char1 double For calculate the charges
cname String To accept the name of
customer

Page 10 of 127
OUTPUT-

Page 11 of 127
5.2 - Assignment 2:
Write a menu driven program to perform the conversion of temperature from one system
ofmeasurement to another. Use constructor to initialize member variables.
The user is given the following options:
(i) Convert from Celsius to Fahrenheit
(ii) Convert from Fahrenheit to Celsius
(iii) Convert from Celsius to Kelvin
For option (i), accept the temperature in Celsius (C). Convert and print the
temperatureinFahrenheit (F)
For option (ii), accept the
temperature inFahrenheit (F).
Convert and print the
temperature inCelsius (C)
For option (iii), accept the temperature in Celsius (C). Convert and print the
temperature inKelvin using the formula: K = C + 273.15
For an incorrect option, an appropriate error message should be displayed

INPUT
User Menu
1. Convert from Celsius to Fahrenheit
2. Convert from Fahrenheit to Celsius
3. Convert from Celsius to KelvinEnter your Choice : 1
Enter the Temperature in Celsius : 40

OUTPUT
Resultant Temperature in Fahrenheit : 104.0

INPUT
User Menu
1. Convert from Celsius to Fahrenheit
2. Convert from Fahrenheit to Celsius
3. Convert from Celsius to KelvinEnter your Choice : 2
Enter the Temperature in Fahrenheit : 86

OUTPUT
Resultant Temperature in Celsius : 30.0

import java.util.Scanner;
class asg4_2
{
public static void main(String args[])
Page 12 of 127
{

Scanner sc=new Scanner(System.in);


int ch;
double temp;
System.out.println("Enter your choice");
System.out.println("========================");
System.out.println("1. Covert from Celsius to Fahrenheit");
System.out.println("2. Convert from Fahrenheit to Celsius");
System.out.println("3. Convert from Celsius to Kelvin");
System.out.println("========================");
ch = sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter Temperature in Celsius");
temp = sc.nextDouble();
System.out.println("Temperature in Fahrenheit = " + (temp*1.8+32));
break;
case 2:
System.out.println("Enter Temperature in Fahrenheit");
temp = sc.nextDouble();
System.out.println("Temperature in Celsius = " + ((temp-32)/1.8));
break;
case 3:
System.out.println("Enter Temperature in Celsius");
temp = sc.nextDouble();
System.out.println("Temperature in Kelvin = " + (temp+273.15));
break;
default:
System.out.println("Incorrect Choice");
}
}
}

Page 13 of 127
VTD-

Variable name Type Purpose


ch Int To accept the weight of the
parcel
temp double To calculate ,accept and store
the given temperatue

Page 14 of 127
OUTPUT-

Page 15 of 127
5.3 - Assignment 3:
Define a class Telephone having the following description :

Instance Variables / Data Members :


String name – to store name of the customer
int calls – to store the number of calls made
double amt – to store the total amount to be paid

Member Methods :
void input ( ) – to input the name of the customer and number of calls made
user(usingScanner class)
void cal ( ) – to calculate the amount and total amount to be paid
void display ( ) – to display the name of the customer, calls made, amount and total amount to
bepaidin the following format :

Name Calls Made Total Amount


…….. ………….. ………………
Write a program to compute the monthly bill to be paid according to the given conditions :

Number of Calls Rate


0 to 100 calls No charge
101 to 200 calls 90 paisa per call
201 to 400 calls 80 paisa per call
401 and above calls 70 paisa per call

However every customer has to pay ₹ 180per month as monthly rent for availing the service.
INPUT
Enter the name of the customer : Arjab
Mitra

Enterthe number of calls made : 55

OUTPUT
Name Calls Made Total Amount

Page 16 of 127
Arjab Mitra 55 ₹ 180.0
INPUT
Enter the name of the customer : Arfin
Rana

Enterthe number of calls made : 175

OUTPUT
Name Calls Made Total Amount
Arfin Rana 175 ₹ 247.5

import java.util.Scanner;

class Telephone {
String name;
int calls;
double amt;

void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the name of the Customer: ");
name = sc.nextLine();
System.out.print("Enter the number of calls made: ");
calls = sc.nextInt();
}

void cal() {
double monthlyRent = 180.0;
if (calls <= 100) {
amt = monthlyRent;
} else if (calls <= 200) {
amt = monthlyRent + (calls - 100) * 0.90;
} else if (calls <= 400) {
amt = monthlyRent + 100 * 0.90 + (calls - 200) * 0.80;
} else {
amt = monthlyRent + 100 * 0.90 + 200 * 0.80 + (calls - 400) * 0.70;
}
}

void display() {
System.out.println("Name\tCalls Made\tTotal Amount");
System.out.println(name + "\t" + calls + "\t " + amt);
}
public static void main(String[] args)
Page 17 of 127
{
Telephone ob = new Telephone();
ob.input();
ob.cal();
ob.display();
}
}

Page 18 of 127
VTD-

Variable name Type Purpose


calls Int
to store the number of calls
made

amt double to store the total amount to be


paid
name String To accept the name of
customer
monthyrent double To pay 180 rupees monthly for
every customer

Page 19 of 127
OUTPUT-

Page 20 of 127
5.4 - Assignment 4:
Write a menu driven program to perform the calculation of the volume of geometrical
structures.Theuser is given the following options: Implement the concept of overloaded
constructors.
(i) Volume of Cube
(ii) Volume of Cone
(iii) Volume of Sphere
(iv) Volume of Cuboid
(v) Volume of Cylinder
For option (i), accept the side (s) of a cube. Calculate and print the volume of cube
For option (ii), accept the radius (r) and height (h) of a cone. Calculate and print the
volume ofconeFor option (iii), accept the radius (r) of a sphere. Calculate and print the
volume of sphere
For option (iv), accept the length (l), breadth (b) and height (h) of a cuboid. Calculate and print
thevolumeof cuboid
For option (v), accept the radius (r) and height (h) of a cylinder. Calculate and print the
volume ofcylinderFor an incorrect option, an appropriate error message should be displayed.

INPUT
User Menu
1. Volume of Cube
2. Volume of Cone
3. Volume of Sphere
4. Volume of Cuboid
5. Volume of Cylinder

Enter your Choice : 1


Enter the Side of Cube : 3.1

OUTPUT
Volume of Cube : 29.791

INPUT

Page 21 of 127
User Menu
6. Volume of Cube
7. Volume of Cone
8. Volume of Sphere
9. Volume of Cuboid
10. Volum
e of CylinderEnter
your Choice : 3
Enter the Radius of Sphere : 1.1

OUTPUT
Volume of Sphere : 5.57752381

INPUT
User Menu
1. Volume of Cube
2. Volume of Cone
3. Volume of Sphere
4. Volume of Cuboid
5. Volume
of Volume of Choice :
4
Enter the Length of Cuboid :
1.1 Enter theBreadth of Cuboid
: 2.2Enter the Height of Cuboid
: 3.3

OUTPUT
Volume of Cuboid : 7.986

mport java.util.Scanner;
lass Asg4_4

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
//int n;
byte ch;
double s,v,r,h,l,b;
System.out.println("===================");
System.out.println("\tMAIN MENU");

Page 22 of 127
System.out.println("===================");
System.out.println("1. Volume of Cube");
System.out.println("2. Volume of Cone");
System.out.println("3. Volume of Sphere");
System.out.println("4. Volume of Cuboid");
System.out.println("5. Volume of Cylinder");
ch=sc.nextByte();

switch(ch)
{
case 1:
System.out.println("Enter sides of the cube");
s=sc.nextDouble();
v=Math.pow(s,3);
System.out.println("Volume of the cube= "+v);
break;

case 2:
System.out.println("Enter radius of the cone");
r=sc.nextDouble();
System.out.println("Enter height of the cone");
h=sc.nextDouble();
v=Math.PI*Math.pow(r,2)*h/3;
System.out.println("Volume of the cone= "+v);
break;

case 3:
System.out.println("Enter radius of the sphere");
r=sc.nextDouble();
v=(4/3)*Math.PI*Math.pow(r,3);
System.out.println("Volume of the cone= "+v);
break;

case 4:
System.out.println("Enter length of the cuboid");
l=sc.nextDouble();
System.out.println("Enter breadth of the cuboid");
b=sc.nextDouble();
System.out.println("Enter height of the cuboid");
h=sc.nextDouble();
v=l*b*h;
System.out.println("Volume of the cone= "+v);
break;

case 5:
System.out.println("Enter radius of the cylinder: ");
Page 23 of 127
r=sc.nextDouble();
System.out.println("Enter height of the cylinder: ");
h=sc.nextDouble();
v=Math.PI*Math.pow(r,2)*h;
System.out.println("Volume of the cone= "+v);
break;

default:
System.out.println("Invalid Input");
}
}
}

Page 24 of 127
VTD-

Variable name Type Purpose


ch byte To accept the choice in the
menu
s double To accept sides
v double To calculate the volume of the
shapes
r double To accept radius
h double To accept height
l double To accept length
b double To accept breadth

Page 25 of 127
OUTPUT-

Page 26 of 127
5.5 - Assignment 5:
A company announces an increment of their employees on the seniority basis (length of
service) asper the given tariff:
Length of service Increment Dearness Allowance
Up to 10 years 20% of 10% of basic
basic
Above 10 and up to 20 25% of 15% of basic
years basic
Above 20 years 30% of 20% of basic
basic

Write a program to find new basic by using the following class


specifications:Class : Increment
Data members/Instance variables:
String name : name of the employee
double basic : basic pay of the employee
int pds : length of service of the employee

Member methods :
void getdata(String n, int p, : to accept
name, length of service,basicdouble bs, double d)
and DA
void calculate( ) : to find increment and update basic salary.
: to display length of service and update basic salaryinthe format given
below:
Output:
Name Length of service Basic Salary DA
****** *********** ********* *********
****** *********** ********* *********
****** *********** ********* *********
INPUT
Name: Ashish
Kumar Shaw Enter
the basic pay:
15000.0Enter the
length of service: 12
Page 27 of 127
OUTPUT
Name Length of Service Basic Salary DA
Ashish Kumar 12 15000.0 2250.0
Shaw

package CLASS_10;

import java.util.Scanner;

class Increment {
private String name;
private double basic;
private int lengthOfService;
private double dearnessAllowance;

public void getData(String n, int p, double bs) {


name = n;
lengthOfService = p;
basic = bs;
calculate();
}

public void calculate() {


if (lengthOfService <= 10) {
dearnessAllowance = 0.2 * 0.1 * basic;
} else if (lengthOfService <= 20) {
dearnessAllowance = 0.25 * 0.15 * basic;
} else {
dearnessAllowance = 0.3 * basic;
}
}

public void display() {


System.out.println("Name: " + name);
System.out.println("Length of Service: " + lengthOfService + " years");
System.out.println("Basic Salary: " + basic);
System.out.println("Dearness Allowance: " + dearnessAllowance);
}
}

public class EmployeeIncrement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Page 28 of 127
Increment employee = new Increment();

System.out.print("Enter the employee name: ");


String name = scanner.nextLine();

System.out.print("Enter the length of service (in years): ");


int lengthOfService = scanner.nextInt();

System.out.print("Enter the basic salary: ");


double basic = scanner.nextDouble();

employee.getData(name, lengthOfService, basic);


employee.display();

scanner.close();
}
}

Page 29 of 127
VTD-

Variable name Type Purpose


name String To accept name of the employee
basic double to store basic pay of the
employee
pds int To length of service of the
employee

Page 30 of 127
OUTPUT-

Page 31 of 127
5. NUMBER BASED PROGRAMS IN JAVA

5.1 - Assignment 1:
Write a program to accept a number and check if it is a happy number or not

The happy number can be defined as a number which will yield 1 when it is replaced by the
sum of the square of its digits repeatedly. If this process results in an endless cycle of
numbers containing 4, then the number is called an unhappy number.

For example, 32 is a happy number as the process yields 1 as follows:

32 + 22 = 13
12 + 32 = 10
12 + 02 = 1

Some of the other examples of happy numbers are 7, 28, 100, 320

and so on. The unhappy number will result in a cycle of 4, 16, 37,

58, 89, 145, 42, 20, 4, ....

To find whether a given number is happy or not, calculate the square of each digit present
in number and add it to a variable sum. If resulting sum is equal to 1 then, given number is
a happy number. If the sum is equal to 4 then, the number is an unhappy number. Else,
replace the number with the sum of the square of digits.
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class happy_num
{
private int n,d=0,s=0;
void acpt()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
n = sc.nextInt();
}
void isHappy()
{
while(n!=1 && n!=4)
{
while(n!=0)
{

Page 32 of 127
d = n%10;
s = s + d*d;
n/=10;
}
n=s;
break;
}

}
void chk()
{
if(s==n)
{
System.out.println("Happy");
}
else
{
System.out.println("not Happy");
}
}
public static void main(String args[])
{
happy_num ob = new happy_num();
ob.acpt();
ob.isHappy();
ob.chk();
}
}

Page 33 of 127
VTD-

Variable name Type Purpose


n Int
to store the number of which
the user as enter
d int For digit extraction
s int To sum the number

Page 34 of 127
OUTPUT-

Page 35 of 127
5.2 - Assignment 2:
Write a program to accept a number and check if it is a Circular Prime number or not

A circular prime is a prime number with the property that the number generated at each
intermediate step when cyclically permuting its digits will be prime. For example, 1193 is a
circular prime, since 1931,9311 and 3119 all are also prime.
import java.util.Scanner;
public class cir_pri_num
{
public static void main(String args[])
{
int n,num,r,c=0;
boolean flg=true;

Scanner sc = new Scanner(System.in);


System.out.println("Enter number");
n= sc.nextInt();

num=n;
while(num>0)
{
r = num%10;
c++;
num = num/10;
}
num=n;
for(int i =1; i<=c; i++)
{
r = num%10;
num = num/10;
num = (r * (int) Math.pow(10, c-1)) + num;
if(!prime(num))
{
flg = false;
break;
}
}

if(flg)

System.out.println("Circular prime");

Page 36 of 127
else

System.out.println("not Circular prime");

}
static boolean prime(int n)
{
int i =2;
boolean flg = true;
while(n>i)
{
if(n%2==0)
{
flg = false;
break;
}
i++;
}
return flg;
}
}

Page 37 of 127
VTD-

Variable name Type Purpose


n Int
to store the number of which
the user as enter
num int To make a duplicate of variable
n
c int For counter
r int For remainder
flag Boolen For true and false

Page 38 of 127
OUTPUT-

Page 39 of 127
5.3 - Assignment 4:
Write a program to accept a number and check if it is a Evil number or not
The Evil number is another special positive whole number in Java that has an even number
of 1's in its binary equivalent. Unlike Prime and Armstrong numbers, Evil number is not so
popular and asked by the interviewers.
The numbers which are not evil are called odious numbers. Some examples of evil and
odious numbers.
1. 15 is an evil number because in its binary equivalent, i.e., 1111, it has an even number of ones.
2. 16 is an odious number because in its binary equivalent, i.e., 10000 has not even number of ones
3. 23 is also an evil number because it has an even number of ones in its binary equivalent,
i.e., 10111.
import java.util.Scanner;
public class evil_or_odi
{
private int n,m,c=0,r=0;
void acpt()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check if it is evil or odious number");
n = sc.nextInt();
}
void isEvil()
{
m=n;
while(m>0)
{
r = m%2;
if(r%2==1)
c++;
m = m/2;
}
if(c%2==0)
System.out.println("It is evil number");
else
System.out.println("It is a odious number");
}
public static void main(String args[])
{
evil_or_odi ob = new evil_or_odi();
ob.acpt();
ob.isEvil();

Page 40 of 127
}
}

VTD-
Variable name Type Purpose
n Int
to store the number of which
the user as enter
m int To make a duplicate of variable
n
c int For counter
r int For remainder

Page 41 of 127
OUTPUT-

Page 42 of 127
5.4 - Assignment 5:
Write a program to accept a number and check if it is a Automorphic number or not

A number is called an automorphic number if and only if the square of the given number
ends with thesame number itself.
For example, 25, 76 are automorphic numbers because their square is 625 and 5776,
respectively and the last two digits of the square represent the number itself. Some other
automorphic numbers are 5, 6, 36, 890, 625, etc.
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class automor_num
{
private int n,sq,flg=0;
void acpt()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check if it is Automorphic number or not");
n = sc.nextInt();
}
void isAuto()
{
sq=n*n;
while(n>0)
{
if(n%10!=sq%10)
flg=1;
n/=10;
sq/=10;
}
}
void chk()
{
if(flg==1)
{
System.out.println("Automorphic number");
}
else
{
System.out.println("not Automorphic number");
}
}

Page 43 of 127
public static void main(String args[])
{
automor_num ob = new automor_num();

ob.acpt();
ob.isAuto();
ob.chk();
}
}

Page 44 of 127
VTD-

Variable name Type Purpose


n Int
to store the number of which
the user as enter
sq int To make a square and sum
f int To check if the number is
automorphic or not

Page 45 of 127
OUTPUT-

Page 46 of 127
7. SERIES BASED PROGRAMS IN JAVA

7.1 - ASSIGNMENT 1:
Write a program to calculate the sum of the numbers in the series mentioned below:

𝟏! 𝟑! 𝟓! (𝟐𝒏 − 𝟏)!
𝑺= + + + ⋯……+
𝒙𝟏
where
x = a variable
n = no. of terms
You have to accept the value of x and n from the user and then calculate the sum of the series.

package All_School_assgigment;
import java.util.Scanner;
import java.io.*;
import java.lang.*;
class asgin
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the value of x");
double x = sc.nextDouble();
System.out.println("Enter the value of n");
int n = sc.nextInt();
double sum = 0;
for(int i = 1; i<=n; i++)
{
int f = 1;
for(int j=1;j<=2*i-1;j++)
{
f*=j;
}
sum+=(f * Math.pow(x,i))/Math.pow(x,i-1);
}
System.out.println("Sum of series "+ sum);
sc.close();
}
}

Page 47 of 127
VTD-

Variable name Type Purpose


x double To accept x value
n int To accept n value
sum double To sum the series
i int Expresions for forloop
f int To count the factorial
j int Expresions for forloop

Page 48 of 127
Page 49 of 127
OUTPUT-

Page 50 of 127
7.2 - ASSIGNMENT 2:
Write a program to calculate the sum of the numbers in the series mentioned below:

S = 1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + ............ + (1 + 2 + 3 + 4 + ......... + n)

where n = no. of terms


You have to accept the value of n from the user and then calculate the sum of the series.
import java.util.Scanner;
public class se
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Emter n");
int n = sc.nextInt();
int s =0;
for(int i=1; i<=n; i++)
{
int ts=0;
for(int j=1; j<=i; j++)
{
ts+= j;
}
s +=ts;
}
System.out.println("sum" + s);
sc.close();
}
}

Page 51 of 127
VTD-

Variable name Type Purpose


n Int For no. of terms
s Int For sum of variable ts
I Int For increment in forloop
ts int For sum
j int For increment in forloop

Page 52 of 127
OUTPUT-

Page 53 of 127
7.3 - ASSIGNMENT 3:
Write a program to calculate the sum of the numbers in the series mentioned

below:S = (3 – 1) + (7 - 5) + (11 - 9) + (15 - 13) +.............................................. + (n – (n – 2))

where n = 101
import java.util.Scanner;
public class asg_7_3
{
public static void main(String args[])
{
int n=101;
int s=0;
for(int i = 3; i<=n; i+=4)
s+=(i-(i-2));
System.out.println("Sum " + s);
}
}

Page 54 of 127
VTD-
Variable name Type Purpose
n Int For no. of terms
s Int For addition
i Int For increment in forloop

Page 55 of 127
OUTPUT-

Page 56 of 127
7.4 - ASSIGNMENT 4:
Write a program to calculate the sum of the numbers in the series mentioned below:

S = 1 + 12 + 123 + 1234 + ..............+ n

where n = no. of terms


You have to accept the value of n from the user and then calculate the sum of the series.

import java.util.Scanner;
public class asg_7_4
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter num of terms”);
int n = sc.nextInt();
sc.close();
int t=0;
int s=0;
for(int i = 1; i<=n; i++)
{
t = t * 10+i;
s+=t;
}
System.out.println("Sum " + s);
}
}

Page 57 of 127
VTD-

Variable name Type Purpose


n Int For no. of terms
s Int For sum of variable ts
I Int For increment in forloop
t int For sum

Page 58 of 127
OUTPUT-

Page 59 of 127
7.5 - ASSIGNMENT 5:
Write a program to calculate the sum of the numbers in the series mentioned below:
S = 1 + 11 + 111 + 1111 + ............. + n
where n = no. of terms
You have to accept the value of n from the user and then calculate the sum of the series.
import java.util.Scanner ;
public class se10
{
public static void main(String args[])
{
System.out.println(“Enter no.of terms”):
int n = sc.nextInt();
int i,s=0,s1=0;
for(i=1; i<=n; i++)
{
s=s*10+1;
s1 = s1 +s;
//System.out.print(s + " ");
}
System.out.print(s1);
}
}

Page 60 of 127
VTD-

Variable name Type Purpose


N Int For no. of terms
S1 Int For sum of variable s
I Int For increment in forloop
S int For sum

Page 61 of 127
OUTPUT-

Page 62 of 127
8. METHOD OVERLOADING BASED PROGRAMS IN JAVA

8.1 – ASSIGNMENT 1:
Design a class overloading a function Compute ( ) as follows:
a) void Compute(String str, int p) with one String argument and one integer argument. It
displays the word in upper case if p is 1 otherwise, displays the word in lower case.
b) void Compute(char chr, int p) with one character argument and one integer argument. It
checks and displays whether a character is in upper case or not if p is 1 otherwise,
displays thecharacter in lower case or not.
c) void Compute( String str, char chr) with one String argument and one character
argument. Itdisplays the first three characters of a String if chr is ‘f’ otherwise, displays
the last three characters of the String.

You can change the return types of the methods if required

Sample Input: SUNIL


Sample Output: If chr is ‘f’ then displays SUN otherwise, NIL

public class Compute


{

// Method to display the word in upper or lower case based on the value of 'p'
public void Compute(String str, int p) {
if (p == 1) {
System.out.println(str.toUpperCase());
} else {
System.out.println(str.toLowerCase());
}
}

// Method to check and display character case or convert it based on 'p'


public void Compute(char chr, int p) {
if (p == 1) {
if (Character.isUpperCase(chr)) {
System.out.println(chr + " is in upper case.");
} else {
System.out.println(chr + " is not in upper case.");
}
} else {
System.out.println(Character.toLowerCase(chr));
}
Page 63 of 127
}
// Method to display first three or last three characters of the String based on 'ch'
public void Compute(String str, char ch) {
if (ch == 'f') {
if (str.length() >= 3) {
System.out.println(str.substring(0, 3));
} else {
System.out.println(str);
}
} else {
if (str.length() >= 3) {
System.out.println(str.substring(str.length() - 3));
} else {
System.out.println(str);
}
}
}
public static void main(String[] args) {
Compute overloader = new Compute();

// Sample input and output


overloader.Compute("SUNIL", 'f'); // Display: "SUN"
}
}

Page 64 of 127
VTD-

Variable name Type Purpose


Str String User input In string
p Int d) It displays the word in
upper case if p is 1
otherwise, displays
the word in lower
case.
chr char to display first three or last
three characters of the
String based on 'chr'

Page 65 of 127
OUTPUT-

Page 66 of 127
8.2 - ASSIGNMENT 2:
Define a class called Employee with the following description:
Instance variables/ Data members:
int emp_ no: to accept the employee number
String name: to input the name of an
employee
int bas: to accept basic salary
Member methods:
void accept ( ) : to accept emp_no, name and basic salary
void compute ( ): to compute the gross salary and net salary of the employee accordingly:
 da = 40% of basic salary
 hra = 15% of basic salary
 pf = 12% of basic salary
 epf = 1.67% of basic salary
 gross = bas + da + hra
 net_sal = gross – (pf + epf)

void display ( ): to display the details of the employee with gross and net salary
Write a main method to create an object of the class and call the above member
methods. You canchange the return types of the methods if required

INPUT
Enter the employee number : 16
Enter the name of an employee:
Aniket SarkarEnter the basic
salary : 18000
OUTPUT
Name:Aniket Sarkar
Employee Number: 16
Gross salary: Rs. 27900.0
Net Salary: Rs. 25439.4

import java.util.Scanner;

class Employee
{
// Instance variables
private int emp_no;
private String name;
private int bas;
Page 67 of 127
// Member method to accept employee details
void accept()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the employee number: ");
emp_no = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter the name of an employee: ");
name = scanner.nextLine();
System.out.print("Enter the basic salary: ");
bas = scanner.nextInt();
}

// Member method to compute gross and net salary


void compute()
{
double da = 0.4 * bas;
double hra = 0.15 * bas;
double pf = 0.12 * bas;
double epf = 0.0167 * bas;
double gross = bas + da + hra;
double net_sal = gross - (pf + epf);

// Display the details


System.out.println("Name: " + name);
System.out.println("Employee Number: " + emp_no);

System.out.println("Gross salary: Rs. " + gross);


System.out.println("Net Salary: Rs. " + net_sal);
}

public static void main(String[] args)


{
Employee employee = new Employee();
employee.accept(); // Accept employee details
employee.compute(); // Compute and display salary details
}
}

Page 68 of 127
VTD-

Variable name Type Purpose


Emp_no Int To enter the employee no.
name string To enter the employee name
bas Int to accept basic salary
da double 40% of basic salary
hra double 15% of basic salary
pf double 12% of basic salary
epf double 1.67% of basic salary
gross double Addition of = bas + da + hra
Net_sal double Net salary = gross – (pf + epf)

Page 69 of 127
OUTPUT-

Page 70 of 127
8.3 - ASSIGNMENT 3:
Design a class to overload a function area ( ) as follows:

double area ( double a, double b, double c) – with three double arguments returns the
area of scalenetriangle using the formula:
where s= (a + b + cArea = √(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)

double area(int a, int b, int height) – with three integer arguments, returns the area of a
trapezium using the formula:

Area = (1/2) * (height * (a + b))

double area (double diagonal1, double diagonal2) – with the double arguments, returns
the area of a rhombus using the formula:

Area = ( 1 / 2 )
*(diagonal1*diagonal2)
You have to accept data as per requirement of the user
choice

INPUT
Enter the sides of a triangle:
10
12
7

OUTPUT
The area is: 499.028869
import java.util.Scanner;

public class asg_8_3


{

// Method to calculate the area of a scalene triangle


public double area(double a, double b, double c) {
double s = (a + b + c) / 2;
return Math.sqrt(s * ((s - a) * (s - b) * (s - c)));
}

// Method to calculate the area of a trapezium


public double area(int a, int b, int height) {
return 0.5 * height * (a + b);
}

Page 71 of 127
// Method to calculate the area of a rhombus
public double area(double diagonal1, double diagonal2) {
return 0.5 * diagonal1 * diagonal2;
}

public static void main(String[] args)


{
asg_8_3 ob = new asg_8_3();
Scanner sc = new Scanner(System.in);

System.out.println("Choose a shape to calculate its area:");


System.out.println("1. Scalene Triangle");
System.out.println("2. Trapezium");
System.out.println("3. Rhombus");

int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.println("Enter the sides of the triangle:");
double sideA = sc.nextDouble();
double sideB = sc.nextDouble();
double sideC = sc.nextDouble();
double triangleArea = ob.area(sideA, sideB, sideC);
System.out.println("The area is: " + triangleArea);
break;
case 2:
System.out.println("Enter the values of the trapezium:");
int baseA = sc.nextInt();
int baseB = sc.nextInt();
int heightTrapezium = sc.nextInt();
double trapeziumArea = ob.area(baseA, baseB, heightTrapezium);
System.out.println("The area is: " + trapeziumArea);
break;
case 3:
System.out.println("Enter the diagonals of the rhombus:");
double diagonal1 = sc.nextDouble();
double diagonal2 = sc.nextDouble();
double rhombusArea = ob.area(diagonal1, diagonal2);
System.out.println("The area is: " + rhombusArea);
break;
default:

Page 72 of 127
System.out.println("Invalid choice.");
break;
}

sc.close();
}
}

Page 73 of 127
VTD-

Variable name Type Purpose


a double 1st side of triangle
b double 2nd side of triangle
c double 3rd of side of triangle
diagonal1 double 1st diagonal of rhombus
diagonal2 double 2nd diagonal of rhombus
a Int 1st side of trapizium
b int 2nd side of trapizum
height int Height of trapzium

Page 74 of 127
OUTPUT-

OUTPUT-

Page 75 of 127
8.4 - ASSIGNMENT 4:
Define a Class called Library with the following description:

Instant variables/ Data members:


int acc_num : stores the accession number of the book.
String title : stores the title of the book.
String author : stores name of the author.

Member methods:
(i) void input ( ) : to input and store accession number, title and author.
(ii) void compute ( ) : to accept the number of days late, calculate the display the fine
charged the rate Rs.2 per day.
(iii) void display ( ) : to display the details in the following format:
Accession Number Title Author Fine
………………………….. ……………………………….. ………………………………. …….
………………………… ………………………………. …………………………….. …….
…………………………… ……………………………….. ………………………………. …….

INPUT
Enter the accession number: 1530
Enter the title of the book: The
Namesake Enter the name of the
author: Jhumpa LahiriEnter the
number of days late: 14

OUTPUT
Accession Number Title Author Fine
153 The Jhumpa Lahiri 28.0
0 Namesake
import java.util.Scanner;
public class Library
{
// Instance variables
private int acc_num;
private String title;
private String author;

// Member method to input and store book details


public void input()
{
Scanner sc = new Scanner(System.in);
Page 76 of 127
System.out.print("Enter the accession number: ");
acc_num = sc.nextInt();
sc.nextLine(); // Consume the newline character
System.out.print("Enter the title of the book: ");
title = sc.nextLine();

System.out.print("Enter the name of the author: ");


author = sc.nextLine();
}

// Member method to calculate and display the fine


public void compute(int daysLate)
{
double fine = daysLate * 2.0;

// Display the details in the specified format


System.out.println("Accession Number\tTitle\tAuthor\tFine");
System.out.println(acc_num + "\t" + title + "\t" + author + "\t" + fine);
}

public static void main(String[] args)


{
Library library = new Library();
Scanner sc = new Scanner(System.in);

library.input(); // Input book details

System.out.print("Enter the number of days late: ");


int daysLate = sc.nextInt();

library.compute(daysLate); // Calculate and display the fine


}
}

Page 77 of 127
VTD-

Variable name Type Purpose


acc_num int stores the accession number
of the book.
author int stores the title of the book
title int stores name of the author.
daysLate int To number of days late
fine double To calculate the number of
dayslate

Page 78 of 127
OUTPUT-

Page 79 of 127
8.5 - ASSIGNMENT 5:
Write a class program with the following specifications:
Class name: stringpro

Data members/ instance variables:


String str :to accept the string from the user Member methods:

Member Methods:
String pro (String) : Parameterized constructor to initialize str.
void count(char c) : To find and print the frequency of a character in the string.
void compare(String) : To compare the string str with the
string passed as argument and print whether the given string as
argument is larger,
smaller or equal.

INPUT
Enter the string: COMPUTER APPLICATIONS

OUTPUT
Frequency of characters:
Character Frequency
A 2
C 2
E 1
I 2
L 1
M 1
N 1
O 2
P 3
R 1
S 1
T 2
U 1

Page 80 of 127
package All_School_assgigment;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class StringPro {


private String str;

// Parameterized constructor to initialize str


public StringPro(String str) {
this.str = str;
}

// To find and print the frequency of a character in the string


public void count(char c) {
int frequency = 0;
for (char ch : str.toCharArray()) {
if (ch == c) {
frequency++;
}
}
System.out.println("Frequency of character " + c + ": " + frequency);
}

// To compare the string str with the string passed as an argument


public void compare(String otherStr) {
int result = str.compareTo(otherStr);

if (result > 0) {
System.out.println("The given string is larger.");
} else if (result < 0) {
System.out.println("The given string is smaller.");
} else {
System.out.println("The given string is equal.");
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input the string


System.out.print("Enter the string: ");

Page 81 of 127
String inputString = sc.nextLine();

// Create an instance of StringPro


StringPro stringProcessor = new StringPro(inputString);

// Display the frequency of characters


System.out.println("\nFrequency of characters:");
System.out.println("Character\tFrequency");
Map<Character, Integer> charFrequencyMap = new HashMap<>();

for (char ch : inputString.toCharArray()) {


charFrequencyMap.put(ch, charFrequencyMap.getOrDefault(ch, 0) + 1);
}

for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) {


System.out.println(entry.getKey() + "\t\t" + entry.getValue());
}

// Test the count method


System.out.print("\nEnter a character to find its frequency: ");
char charToFind = sc.next().charAt(0);
stringProcessor.count(charToFind);

// Test the compare method


sc.nextLine(); // consume the newline character
System.out.print("\nEnter another string to compare: ");
String comparisonString = sc.nextLine();
stringProcessor.compare(comparisonString);

sc.close();
}
}

Page 82 of 127
VTD-

Variable name Type Purpose


str string stores the string
c Char stores the frequency of the
string
otherStr string Stores the other

Page 83 of 127
OUTPUT-

Page 84 of 127
9. STRING BASED PROGRAMS IN JAVA

9.1 - ASSIGNMENT 1:
Write a program to input a sentence. Convert in Upper case and shift each letter of the
English alphabet two steps towards the right. Characters other than alphabets remain the
same. Print original and new string in two different lines.

Sample Input: ABACUS12@RYZ


Sample Output: CDCEWU12@TAB
import java.util.Scanner;

public class Shft_alpha


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

// Input a sentence
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();

// Convert to uppercase
String upperCaseSentence = sentence.toUpperCase();

// Initialize an empty string for the shifted sentence


StringBuilder shiftedSentence = new StringBuilder();

for (int i = 0; i < upperCaseSentence.length(); i++) {


char currentChar = upperCaseSentence.charAt(i);

if (Character.isLetter(currentChar)) {
char shiftedChar = (char) (currentChar + 2);

// Handle wrapping around from 'Z' to 'A'


if (shiftedChar > 'Z') {
shiftedChar = (char) (shiftedChar - 26);
}

shiftedSentence.append(shiftedChar);
} else {
// Non-alphabet characters remain the same
shiftedSentence.append(currentChar);
Page 85 of 127
}
}

// Print original and shifted sentences on separate lines


System.out.println("Original Sentence:");
System.out.println(sentence);

System.out.println("Shifted Sentence:");
System.out.println(shiftedSentence.toString());

sc.close();
}
}

Page 86 of 127
VTD-

Variable name Type Purpose


sentence String To accept the String
upperCaseSentence String To change into uppercase
i int Expressions for the forloop
currentChar char Single char of the input string
shiftedChar char To shift a single char of the
string

Page 87 of 127
OUTPUT-

Page 88 of 127
9.2 - ASSIGNMENT 2:
Write a program in Java to enter a String/Sentence and display the longest word and the
length of the longest word present in the String.
Sample Input: “TATA FOOTBALL ACADEMY WILL PLAY AGAINST MOHAN BAGAN”
Sample Output:

The longest
word: FOOTBALL
The length of
the word: 8
import java.util.Scanner;
import java.io.*;
import java.lang.*;

public class Lg_wd_fr


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

// Input a sentence
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();

// Split the sentence into words


String[] words = sentence.split(" ");

String longestWord = "";


int maxLength = 0;

// Find the longest word and its length


for (String word : words) {
// Remove any punctuation marks from the word
word = word.replaceAll("[^a-zA-Z]", "");

if (word.length() > maxLength) {


maxLength = word.length();
longestWord = word;
}
}

Page 89 of 127
// Print the longest word and its length
System.out.println("The longest word: " + longestWord);
System.out.println("The length of the word: " + maxLength);

sc.close();
}
}

Page 90 of 127
VTD-

Variable name Type Purpose


sentence String To input a sentence
longestWord String To the store the longest
word
maxLength int To find the maxium length of
the sentence
word String To find the longest word

Page 91 of 127
OUTPUT-

Page 92 of 127
9.3 - ASSIGNMENT 3:
Write a program in JAVA to accept a word .Convert and Display the word in Pig Latin. A Pig
Latin is an encrypted word in English, which is generated by doing following altercations:
The first vowel occurring in the input word is placed at the start of the new word along
with the remaining alphabets of it. The alphabets present before the first vowel are
shifted at the end of the new word followed by “ay” or “AY”

For example:
TROUBLE ->
OUBLETRAY
OWL->
OWLAY

package All_School_assgigment;
import java.util.Scanner;

public class strCon {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input a word
System.out.print("Enter a word: ");
String inputWord = scanner.nextLine();

// Convert the word to Pig Latin


String pigLatinWord = convertToPigLatin(inputWord);

// Display the Pig Latin word


System.out.println("Pig Latin: " + pigLatinWord);

scanner.close();
}

// Method to convert a word to Pig Latin


private static String convertToPigLatin(String word) {
word = word.toUpperCase(); // Convert the word to uppercase for consistent comparison

int firstVowelIndex = -1;

Page 93 of 127
// Find the index of the first vowel
for (int i = 0; i < word.length(); i++) {
char currentChar = word.charAt(i);
if (currentChar == 'A' || currentChar == 'E' || currentChar == 'I' || currentChar == 'O'
|| currentChar == 'U') {
firstVowelIndex = i;
break;
}
}

// If no vowel is found, the word remains unchanged


if (firstVowelIndex == -1) {
return word.toLowerCase(); // Return the original word in lowercase
}

// Create the Pig Latin word


String pigLatin = word.substring(firstVowelIndex) + word.substring(0, firstVowelIndex) +
"AY";

// Preserve the original case


if (Character.isLowerCase(word.charAt(0))) {
pigLatin = pigLatin.toLowerCase();
}

return pigLatin;
}
}

Page 94 of 127
VTD-

Variable name Type Purpose


inputWord String To input a sentence
pigLatinWord String To the store the piglatin
firstVowelIndex int To find the maxium length of
the sentence
currentChar char To find the longest word
pigLatin String To exchange it
i int Expression for forloop

Page 95 of 127
OUTPUT-

Page 96 of 127
9.4 - ASSIGNMENT 4:

Write a program to accept a sentence in mixed case. Find the frequency of vowels in each
word andprint the words along with their frequencies in separate lines.
Sample Input:
We are learning scanner class
Sample Output:
We are learning scanner class

Word
frequency of vowels
we 1
are 2
learning 3
scanner 2
class 1

package All_School_assgigment;
import java.util.Scanner;

public class Vofrecoun {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input a sentence
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();

// Process the sentence and display word frequencies


processAndDisplayWordFrequencies(sentence);

scanner.close();
}

private static void processAndDisplayWordFrequencies(String sentence) {


// Split the sentence into words
String[] words = sentence.split("\\s+");

Page 97 of 127
// Display the header
System.out.printf("%-15s%s%n", "Word", "Frequency of Vowels");

// Process each word


for (String word : words) {
int vowelFrequency = countVowels(word);

// Display word and its vowel frequency


System.out.printf("%-15s%d%n", word, vowelFrequency);
}
}

private static int countVowels(String word) {


int vowelCount = 0;
String lowerWord = word.toLowerCase(); // Convert to lowercase for case-insensitive
comparison

// Count the vowels in the word


for (int i = 0; i < lowerWord.length(); i++) {
char currentChar = lowerWord.charAt(i);
if (currentChar == 'a' || currentChar == 'e' || currentChar == 'i' || currentChar == 'o' ||
currentChar == 'u') {
vowelCount++;
}
}

return vowelCount;
}
}

Page 98 of 127
VTD-

Variable name Type Purpose


sentence String[] Stores the input sentence
entered by the user.
words String[] An array that stores
individual words obtained
by splitting
word String Represents an individual
word during the iteration
through
vowelFrequency int Stores the count of
vowels in a particular
word.
lowerWord String Represents the lowercase
version of a word, used
for
currentChar char Represents the current
character during the
iteration
i int Loop variable used for
iterating through
characters in a word

Page 99 of 127
OUTPUT-

Page 100 of 127


9.5 - ASSIGNMENT 5:
Special words are those words which start and end with the
same letter.Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right
and vice-versa.Example: MALYALAM, MADAM, LEVEL, ROTATOR, CIVIC
All palindromes are special words but all special words are not palindromes.
Write a program to accept a word. Check and display whether the word is a palindrome
or only aspecial word or none of them.

package All_School_assgigment;
import java.util.Scanner;

public class palinchk {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input a word
System.out.print("Enter a word: ");
String inputWord = scanner.nextLine();

// Check and display the result


checkAndDisplayResult(inputWord);

scanner.close();
}

private static void checkAndDisplayResult(String word) {


if (isPalindrome(word) && isSpecialWord(word)) {
System.out.println("The word is both a palindrome and a special word.");
} else if (isPalindrome(word)) {
System.out.println("The word is a palindrome.");
} else if (isSpecialWord(word)) {
System.out.println("The word is a special word.");
} else {
System.out.println("The word is neither a palindrome nor a special word.");
}
}

Page 101 of 127


private static boolean isPalindrome(String word) {
String reversed = new StringBuilder(word).reverse().toString();
return word.equalsIgnoreCase(reversed);
}

private static boolean isSpecialWord(String word) {


return word.length() > 1 && word.charAt(0) == word.charAt(word.length() - 1);
}
}

Page 102 of 127


VTD-

Variable Name Type Description


inputWord String Stores the input word entered by the user.
reversed String Stores the reversed version of the input word for palindrome check.

Page 103 of 127


OUTPUT-

Page 104 of 127


10. PROGRAMS BASED ON ARRAYS, SEARCHING AND SORTING IN AN ARRAY

10.1 - ASSIGNMENT 1:
Write a program in Java to accept the names and total marks of N number of students in two
singledimensional arrays – name [ ] and totalmarks [ ]
Calculate and print the following:
 The average of the total marks obtained by the N number of
students[Average = (sum of total marks of all the students) /
N]
 Name and deviation of each student’s total marks with
the average[Deviation = total marks of a student –
average]

Page 105 of 127


VTD-

Variable Name Type Description


N int Stores the number of students.
names String[] An array to store the names of N students.
totalMarks double[] An array to store the total marks of N students.
average double Stores the average of total marks obtained by the N students.
deviation double Stores the deviation of each student's total marks from the average.
i int Loop variable used for iterating through students.
value double Temporary variable to store the current total marks during calculations.
scanner Scanner Used for taking input from the user.

Page 106 of 127


OUTPUT-

Page 107 of 127


10.2 - ASSIGNMENT 2:
Write a program in Java to store the names of 10 important Indian cities with their
corresponding pin code in two single dimensional arrays – cityname[ ] and pincode[ ]
respectively.
Accept the name of a city as input from the user and search for it in the cityname[ ] array.
If the name of the city is found, display the message “Search Successful!” and print the
name of the city along with its corresponding pin code. If the name of the city is not
found, display the message “Search Unsuccessful! No Such City in the List!”
For example,
Cities: Kolkata, Mumbai, Chennai, Jaipur, Pune, Lucknow, Kanpur, Bhopal, Patna, Jodhpur
Pincode:
700000, 400000, 600000, 302000, 411000, 226000, 208000, 462000, 800000, 342000
Search City:
Kolkata Search
Successful!
Kolkata Pincode
= 700000Search
City: Nagpur
Search Unsuccessful! No Such City in the List!

package All_School_assgigment;
import java.util.Scanner;

public class arryCitySearch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Declare arrays to store city names and pin codes


String[] cityNames = {"Kolkata", "Mumbai", "Chennai", "Jaipur", "Pune", "Lucknow",
"Kanpur", "Bhopal", "Patna", "Jodhpur"};
int[] pinCodes = {700000, 400000, 600000, 302000, 411000, 226000, 208000, 462000,
800000, 342000};

// Accept the name of a city from the user


System.out.print("Enter the name of a city to search: ");
String searchCity = scanner.nextLine();

Page 108 of 127


// Search for the city in the array
int index = searchCityIndex(cityNames, searchCity);

// Display the result based on the search


if (index != -1) {
System.out.println("Search Successful! " + cityNames[index] + " Pincode = " +
pinCodes[index]);
} else {
System.out.println("Search Unsuccessful! No Such City in the List!");
}

scanner.close();
}

// Method to search for a city in the array and return its index
private static int searchCityIndex(String[] cities, String searchCity) {
for (int i = 0; i < cities.length; i++) {
if (cities[i].equalsIgnoreCase(searchCity)) {
return i; // Return the index of the city if found
}
}
return -1; // Return -1 if the city is not found
}
}

Page 109 of 127


VTD-

Variable Name Type Description


cityNames String[] Array to store the names of 10 Indian cities.
pinCodes int[] Array to store the corresponding pin codes.
scanner Scanner Scanner object for taking user input.
searchCity String Stores the name of the city entered by the user.
index int Stores the index of the found city in the array.

Page 110 of 127


OUTPUT-

Page 111 of 127


10.3 – ASSIGNMENT 3:
Write a program in Java to input two arrays of sizes “m” and “n” respectively. Merge the
elements of both the arrays in a third array and display the merged array. Sort the
elements of the merged array in an ascending order using the Selection Sort technique
and display the sorted merged array elements.
For example:
Enter the size of 1st array (m): 3

Enter the size of 2nd array (n): 2

Enter the elements of 1st array:


10
40
20

Enter the elements of 2nd array:


50
30

Merged array elements: 10 40 20 50 30


Sorted merged array elements in ascending order: 10 20 30 40 50

import java.util.Scanner;

public class MergeAndSortArrays {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the first array


System.out.print("Enter the size of 1st array (m): ");
int m = scanner.nextInt();

// Input the elements of the first array


int[] array1 = inputArray(m, "1st");

// Input the size of the second array


System.out.print("Enter the size of 2nd array (n): ");
int n = scanner.nextInt();

Page 112 of 127


// Input the elements of the second array
int[] array2 = inputArray(n, "2nd");

// Merge the arrays


int[] mergedArray = mergeArrays(array1, array2);

// Display the merged array elements


System.out.print("Merged array elements: ");
displayArray(mergedArray);

// Sort the merged array using Selection Sort


selectionSort(mergedArray);

// Display the sorted merged array elements


System.out.print("\nSorted merged array elements in ascending order: ");
displayArray(mergedArray);

scanner.close();
}

// Method to input elements of an array


private static int[] inputArray(int size, String ordinal) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the elements of " + ordinal + " array:");
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
return array;
}

// Method to merge two arrays


private static int[] mergeArrays(int[] array1, int[] array2) {
int[] mergedArray = new int[array1.length + array2.length];
int index = 0;

// Copy elements of the first array to mergedArray


for (int element : array1) {
mergedArray[index++] = element;
}

// Copy elements of the second array to mergedArray

Page 113 of 127


for (int element : array2) {
mergedArray[index++] = element;
}

return mergedArray;
}

// Method to display elements of an array


private static void displayArray(int[] array) {
for (int element : array) {
System.out.print(element + "\t");
}
System.out.println();
}

// Method to perform Selection Sort on an array


private static void selectionSort(int[] array) {
int n = array.length;

for (int i = 0; i < n - 1; i++) {


int minIndex = i;

for (int j = i + 1; j < n; j++) {


if (array[j] < array[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the element at index i


int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
}

Page 114 of 127


VTD-

Variable Name Type Description


scanner Scanner Scanner object for taking input from the user.
m int Size of the first array.
n int Size of the second array.
i, j int Loop counters for iterating through arrays.
arr1, arr2 int[] Arrays to store the elements of the first and second arrays.
mergedArr int[] Array to store the merged elements of arr1 and arr2.
temp int Temporary variable used in swapping elements during selection sort.

Page 115 of 127


OUTPUT-

Page 116 of 127


10.4 - ASSIGNMENT 4:
Write a program in Java to input integer numbers in a double dimensional array of size M
x M. Print the Original Array. Find and print the product of only prime numbers present in
the left diagonal and sum of all the elements except the boundary elements.
Input:
M=4
Input Matrix:
9 5 2 4
1 6 3 9
2 8 7 7
2 6 0 5

Output:
Original Matrix:
9 5 2 4
1 6 3 9
2 8 7 7
2 6 0 5
Product of only prime numbers present in the left diagonal = 35
Sum of all the elements except the boundary elements = 24

package All_School_assgigment;
import java.util.Scanner;

public class MatrixOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the matrix


System.out.print("Enter the size of the matrix (M): ");
int M = scanner.nextInt();

// Input the elements of the matrix


int[][] matrix = new int[M][M];

Page 117 of 127


System.out.println("Input Matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Print the original matrix


System.out.println("Original Matrix:");
printMatrix(matrix);

// Calculate and print the product of prime numbers in the left diagonal
int productOfPrimes = productOfPrimeNumbersLeftDiagonal(matrix);
System.out.println("Product of only prime numbers present in the left diagonal = " +
productOfPrimes);

// Calculate and print the sum of all elements except the boundary elements
int sumExceptBoundary = sumOfElementsExceptBoundary(matrix);
System.out.println("Sum of all the elements except the boundary elements = " +
sumExceptBoundary);
}

// Method to print a matrix


private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}

// Method to check if a number is prime


private static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}

Page 118 of 127


return true;
}

// Method to calculate the product of prime numbers in the left diagonal


private static int productOfPrimeNumbersLeftDiagonal(int[][] matrix) {
int product = 1;
for (int i = 0; i < matrix.length; i++) {
if (isPrime(matrix[i][i])) {
product *= matrix[i][i];
}
}
return product;
}

// Method to calculate the sum of all elements except the boundary elements
private static int sumOfElementsExceptBoundary(int[][] matrix) {
int sum = 0;
for (int i = 1; i < matrix.length - 1; i++) {
for (int j = 1; j < matrix[i].length - 1; j++) {
sum += matrix[i][j];
}
}
return sum;
}
}

Page 119 of 127


VDT-
Variable Name Type Description
scanner Scanner Scanner object for taking input from the user.
M int Size of the matrix.
matrix int[][] Double-dimensional array to store the matrix elements.
productOfPrimes int Product of prime numbers present in the left diagonal.
sumExceptBoundary int Sum of all elements except the boundary elements.
i, j int Loop counters for iterating through the matrix.

Page 120 of 127


OUTPUT-

Page 121 of 127


10.5 - ASSIGNMENT 5:
Write a program in Java to input integer numbers in a square matrix of
size M x M.Display the Original Matrix
Rotate the matrix 90O anti–clockwise.
Find the sum of the elements of the four corners of the matrix.
Input:
M=3
Input Matrix:
1 2 3
6 5 4
7 8 9

Output:
Original Matrix:
1 2 3
6 5 4
7 8 9
Matrix after 90 Degree Anti–Clockwise Rotation:
3 4 9
2 5 8
1 6 7
Sum of corner elements = 20

package All_School_assgigment;
import java.util.Scanner;

public class Matraopt {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the size of the matrix


System.out.print("Enter the size of the matrix (M): ");
int M = scanner.nextInt();

Page 122 of 127


// Input the elements of the matrix
int[][] matrix = new int[M][M];
System.out.println("Input Matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Display the original matrix


System.out.println("Original Matrix:");
displayMatrix(matrix);

// Rotate the matrix 90 degrees anti-clockwise


int[][] rotatedMatrix = rotateMatrixAntiClockwise(matrix);
System.out.println("Matrix after 90 Degree Anti–Clockwise Rotation:");
displayMatrix(rotatedMatrix);

// Find the sum of corner elements


int sumOfCorners = sumOfCornerElements(matrix);
System.out.println("Sum of corner elements = " + sumOfCorners);
}

// Method to display a matrix


private static void displayMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}

// Method to rotate a matrix 90 degrees anti-clockwise


private static int[][] rotateMatrixAntiClockwise(int[][] matrix) {
int N = matrix.length;
int[][] rotatedMatrix = new int[N][N];

for (int i = 0; i < N; i++) {


for (int j = 0; j < N; j++) {
rotatedMatrix[i][j] = matrix[j][N - i - 1];
}

Page 123 of 127


}

return rotatedMatrix;
}

// Method to find the sum of corner elements in a matrix


private static int sumOfCornerElements(int[][] matrix) {
int N = matrix.length;
return matrix[0][0] + matrix[0][N - 1] + matrix[N - 1][0] + matrix[N - 1][N - 1];
}
}

Page 124 of 127


VTD-
Variable Name Type Description
scanner Scanner Object for taking input from the user.
M int Size of the square matrix.
matrix int[][] Two-dimensional array to store the matrix elements.
rotatedMatrix int[][] Two-dimensional array to store the rotated matrix elements.
sumOfCorners int Sum of the four corner elements of the matrix.
i, j int Loop counters for iterating through the matrix.
N int Size of the matrix used for rotation calculations.

Page 125 of 127


11. CONCLUSION

while OOP has its learning curve, the benefits it brings in terms of code organization,
reusability, and scalability make it a valuable paradigm in modern software development. As
developers become more proficient in OOP, they can leverage its principles to create robust,
maintainable, and scalable software solutions.

Page 126 of 127


12. BIBLIOGRAPHY

Give the names of the books and the websites visited for researching on the above topics
andprogramming in the format given below

1. Oswal question bank – oswal


2. Self help I S C E for computer application – Arun Deep
3. www.Google.com – 7/23/23

Page 127 of 127

You might also like