0% found this document useful (0 votes)
21 views210 pages

ISC Java Project Overview 2025-2026

The document is a project report for the ISC Computer Science course at St. Joseph's Boys' High School, authored by Anvitha Rao under the guidance of Mr. Franklyn Xavier and Mrs. Jessey Tharakan. It includes a certificate of authenticity, a table of contents listing various programming topics and corresponding programs, and detailed descriptions of several Java programs demonstrating concepts such as recursion, data structures, and number classifications. The project fulfills the requirements of the Indian School Certificate Computer Science course for the academic year 2025-2026.

Uploaded by

Anvitha Rao
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views210 pages

ISC Java Project Overview 2025-2026

The document is a project report for the ISC Computer Science course at St. Joseph's Boys' High School, authored by Anvitha Rao under the guidance of Mr. Franklyn Xavier and Mrs. Jessey Tharakan. It includes a certificate of authenticity, a table of contents listing various programming topics and corresponding programs, and detailed descriptions of several Java programs demonstrating concepts such as recursion, data structures, and number classifications. The project fulfills the requirements of the Indian School Certificate Computer Science course for the academic year 2025-2026.

Uploaded by

Anvitha Rao
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

St.

Joseph’s Boys’ High School

ISC Computer Project


2025-2026

DONE UNDER THE GUIDANCE OF


MR. FRANKLYN XAVIER
MRS. JESSEY THARAKAN

By,
Anvitha Rao
Registration No: 2265628/056

Page | 1
St. Joseph’s Boys’ High School,
Museum Road, Bangalore

CERTIFICATE
This is to certify that this JAVA project is a
bone fide record of work done by

Anvitha Rao

Of St. Joseph’s Boys’ High School, Bangalore in


fulfilment of the requirement of
the Indian School Certificate Computer Science course.

Head of the department External Examiner Principal

Name: Anvitha Rao


Registration Number: 2265628/ [Your Seri

Page | 2
CONTENTS

Sl. No. Topic Number of


Programs
1. RECURSION 15

2. ARRAY [SDA & DDA] 20

3. DATA STRUCTURES 05

4. FUNCTIONS PASSING 13
OBJECTS

5. INHERITANCE 15

6. STRING MANIPULATIONS 10

7. MISCELLANEOUS 4
PROGRAMS

Page | 3
Page | 4
Index

Sl. No. Title Page


Recursion
1. Pernios Number 06
2. Sum Series 08
3. Disarium Number 10
4. Dudney Number 12
5. Perfect Number 14
6. Happy Number 16
7. Decimal to Hexa-Decimal 18
8. Mystery Number 20
9. Spy Number 22
10. ISC 2015 Binary Search Recursion 24
11. Bubble Sort Recursion 26
12. Emirp Number 29
13. Reverse String Program 31
14. Fibonacci 33
15. Case Convert 35

Page | 5
Program 01: Pernios Number
[A number is said to be pernios number if it has prime number of ones in its binary form]
Class Name: Perni
Data Members/ Instance Variables:
num: to store the Binary Number
Member Methods / Functions:
Perni (): default constructor to initialize the instance variables.
void accept (): to accept a BINARY NUMBER
int countOne (int k): counting the number of ones using recursive technique
void check (): calls the function countOne and returns whether the number is Pernios or not.

Algorithm:
Step 1: Declare and initialize the required variables as num, x, c, i, etc.
Step 2: Input a binary number and assign it to the variable num.
Step 3: Define a recursive function countOne(k) to count the number of 1’s in the binary
number: If k == 0, return 0, otherwise, return countOne(k / 10) + (k % 10).
Step 4: Call the function countOne(num) and store the result in x.
Step 5: Initialize c = 0 (to count the number of factors of x).
Step 6: Run a loop from i = 1 to x.
Step 7: Check if x % i == 0. If yes, increment c by 1.
Step 8: After the loop ends, check if c == 2.
Step 9: If c == 2, display: "Number: " + num + ", is a Pernicious Number"
Otherwise, display: "Not a Pernicious Number".
Step 10: End of the algorithm.
Code:
import [Link].*;
public class Perni
{
int num;
Perni(){
num = 0;
}
void accept(){
Scanner sc = new Scanner([Link]);
[Link]("Enter the Binary Number: ");
num = [Link]();
}

int countOne (int k) {


if(k == 0) return 0;
return(countOne(k/10) + (k % 10));
}

void check () {
int x = countOne(num), c = 0;
Page | 6
for(int i = 1; i <= x; i++)
if(x % i == 0)
c++;
[Link]((c == 2) ? ("Number: " + num + ", is Pernious Number") : "Not a
Pernious Number");
}

public static void main(){


Perni ob = new Perni();
[Link]();
[Link]();
}
}
Output:

Page | 7
Program 02: Sum Series
2 4 6
∑ ¿ 1x ! + 3x ! + 5!
x
+ …till nterms

Class Name: SeriesSum


Data Members / Instance variables:
x: to store the integer number
n: to store the number of terms
sum: double variable to store the sum of series
Member Methods:
SeriesSum(int xx, int yy) : A parameterized constructor to assign x = xx, and n = yy.
double FindFact(int m): to return the factorial of m using recursion technique.
double FindPower(int x, int y): to return x raised to the power of y using recursion;
void calculate(): To calculate the sum of series by invoking the recursive function
respectively.’
void display(): to display the series
Algorithm:
Step 1: Declare and initialize the required variables as x, n, sum, i, k, etc.
Step 2: Input the values of x and n.
Step 3: Define a recursive function FindFact(m) to calculate the factorial of a number:
If m == 0, return 1; otherwise, return FindFact(m - 1) * m.
Step 4: Define another recursive function FindPower(x, y) to calculate power:
If y == 1, return x; otherwise, return FindPower(x, y - 1) * x.
Step 5: Initialize k = 2 and sum = 0.
Step 6: Run a loop from i = 1 to n.
Step 7: In each iteration, calculate the term using the formula (FindPower(x, k) / FindFact(k -
1)) and add it to sum.
Step 8: Increment k by 2 after each iteration.
Step 9: After the loop ends, display the value of sum as "The sum of the series is: " + sum.
Step 10: End of the algorithm.
Code:
import [Link].*;
public class SeriesSum
{
int x, n;
double sum;
SeriesSum(){ x = 0; n = 0;}

SeriesSum(int xx, int yy){this(); x = xx; n = yy;}

double FindFact(int m){ if(m ==0) return 1; return FindFact(m-1)*m;}

double FindPower(int x, int y){ if(y == 1) return x; return FindPower(x, y-1) * x;}
// number of terms from 1 till n;

Page | 8
void calculate(){
int k = 2;
for(int i = 1; i <= n; i++){
sum += (double)(FindPower(x, (k)) / FindFact(k - 1));
k+=2;
}
}

void display(){ [Link]("The sum of the series is: " + sum);}

public static void main(){ Scanner sc = new Scanner([Link]);


[Link]("Enter 'x': ");
int xx = [Link]();
[Link]("Enter 'n': "); int yy = [Link]();
SeriesSum ob = new SeriesSum(xx, yy);
[Link]();
[Link]();
}
}

Output:

Page | 9
Program 03: Disarium Number
[A number is said to be Disarium number if the sum of digits to the power of their respective
position is equal to the number itself]
Class Name: Disarium
Data Members/ Instance Variables:
num: to store the number
Member Methods / Functions:
Disarium (int n): to initialize num = n, size = 0.
void countdigit (): to count the number of digits of the NUMBER
int sumofdigits (int n, int p): returns the sum of the digits of num = n, raised to the power of
their respective Position p, using recursion
void check (): calls the function sumofidigits and returns whether the number is Disarium or
not.
Algorithm:
Step 1: Declare and initialize the required variables as num, size, n, and p.
Step 2: Input a number and assign it to the variable num.
Step 3: In the constructor, initialize num = n and size = 0.
Step 4: Define a function countdigit() to count the number of digits in the number using the
formula: size = (int)(Math.log10(num)) + 1.
Step 5: Define a recursive function sumofdigits(int n, int p) to calculate the sum of digits
raised to the power of their respective positions: If n == 0, return 0.
Otherwise, return sumofdigits(n / 10, p - 1) + (int)([Link]((n % 10), p)).
Step 6: Define a function check() which calls sumofdigits(num, size) and compares the result
with num.
Step 7: If both values are equal, display "Number: " + num + ", is a Disarium",
otherwise display "Not A Disarium".
Step 8: End of the algorithm.
Code:
import [Link].*;
public class Disarium {
int num, size;
Disarium(int n) {
num = n;
size = 0;
}
// Function to count digits
void countdigit() {
size = (int) Math.log10(num) + 1;
}
// Recursive function to calculate sum of digits raised to respective powers
int sumofdigits(int n, int p) {
if (n == 0)
return 0;
return sumofdigits(n / 10, p - 1) + (int) [Link]((n % 10), p);
}
Page | 10
void check() {
[Link](
(sumofdigits(num, size) == num)
? ("Number: " + num + ", is a Disarium")
: ("Not A Disarium")
);
}
public static void main() {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number: ");
int n = [Link]();
Disarium ob = new Disarium(n);
[Link]();
[Link]();
}
}

Output:

Page | 11
Program 04: Dudney Number
[A number is said to be Dudney number if its cube of sum of its digits is equal to the number
itself.]
Class Name: NumDude
Data Members/ Instance Variables:
num: to store the number
Member Methods / Functions:
NumDude (): default constructor to initialize the instance variables.
void input (): to accept the number
int sumDigits (int x): Sum of digits using recursive technique
void isDude (): calls the function sumDigits and returns whether the number is Dudeney or
not.
Algorithm:
Step 1: Declare and initialize the required variables as num, x, and n.
Step 2: Input a positive integer and assign it to the variable num.
Step 3: Define a recursive function sumDigits(int x) to calculate the sum of digits of a
number: If x == 0, return 0.
Otherwise, return (x % 10 + sumDigits(x / 10)).
Step 4: In the function isDude(), call sumDigits(num) and store the result in variable n.
Step 5: Check if the cube of n is equal to the number itself, i.e.
if (n * n * n == num).
Step 6: If true, display: "Number: " + num + ", is a Dudeney Number".
Otherwise, display: "Number is not a Dudeney Number".
Step 7: End of the algorithm.
Code:
import [Link].*;
public class NumDude {
int num;
// Default constructor
NumDude() {
num = 0;
}
// Function to accept a number
void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter a positive Integer: ");
num = [Link]();
}
// Recursive function to find sum of digits
int sumDigits(int x) {
return (x == 0) ? 0 : (x % 10 + sumDigits(x / 10));
}
// Function to check if number is a Dudeney Number
void isDude() {
int n = sumDigits(num);
Page | 12
[Link](
(n * n * n == num)
? ("Number: " + num + ", is a Dudeney Number")
: ("Number is not a Dudeney Number")
);
}
// Main method
public static void main(String args[]) {
NumDude ob = new NumDude();
[Link]();
[Link]();
}
}
Output:

Page | 13
Program 05: Perfect Number
[A number is said to be perfect number if the sum of its factors excluding itself is equal to the
number itself.]
Class Name: Perfect
Data Members/ Instance Variables:
num: to store the number
Member Methods / Functions:
Perfect (): default constructor to initialize the instance variables.
void input (): to accept the number
int sumoffactors (int i): Sum of factors using recursive technique
void isPerfect (): calls the function sumoffactors and returns whether the number is Perfect or
not.
Algorithm:
Step 1: Declare and initialize the required variables as num, i, and n.
Step 2: Input a positive integer and assign it to the variable num.
Step 3: Define a recursive function sumoffactors(int i) to calculate the sum of all factors of
num (excluding itself):
 If i == 1, return 1.
 Otherwise, check if num % i == 0.
o If true, return i + sumoffactors(--i).
o Else, return sumoffactors(--i).
Step 4: In the function isPerfect(), call sumoffactors(num - 1) and store the result in variable n.
Step 5: Check if n == num.
Step 6: If true, display: "Number: " + num + ", is a Perfect Number". Otherwise, display:
"Number is not a Perfect Number".
Step 7: End of the algorithm.
Code:
import [Link].*;
public class Perfect {
int num;
// Default constructor
Perfect() {
num = 0;
}
// Function to accept a number
void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter a positive Integer: ");
num = [Link]();
}
// Recursive function to calculate sum of factors
int sumoffactors(int i) {
if (i == 1)
return 1;
int n = num % i;
Page | 14
if (n == 0)
return i + sumoffactors(--i);
else
return sumoffactors(--i);
}
// Function to check if number is Perfect
void isPerfect() {
int n = sumoffactors(num - 1);
[Link](
(n == num)
? ("Number: " + num + ", is a Perfect Number")
: ("Number is not a Perfect Number")
);
}
// Main method
public static void main(String args[]) {
Perfect ob = new Perfect();
[Link]();
[Link]();
}
}
Output:

Page | 15
Program 06: Happy Number
[A Happy number is a number in which the sum of the square of the digits of the number is
equal to 1]
Class Name: Happy
Data Members/ Instance Variables:
n: to store the Number
Member Methods / Functions:
Happy (): default constructor to initialize the instance variables.
void getnum (int nn): to assign a NUMBER to n
int sum_sq_digits (int x): return the sum of square of digits of number using recursive
technique
void ishappy (): calls the function sum_sq_digits and returns whether the number is happy or
not.
Algorithm:
Step 1: Declare and initialize the required variables as n, sum, and x.
Step 2:Input a positive integer and assign it to the variable n.
Step 3: In the constructor, initialize n = 0 and sum = 0.
Step 4: Define a function getnum(int nn) to assign the input value to n.
Step 5: Define a recursive function sum_sq_digits(int x) to calculate the sum of the squares of
the digits of the number:
Add (x % 10) * (x % 10) to sum.
If sum > 9, check the following:
If x == 0, assign sum to x.
If sum == x, return 1.
If sum < 10 and sum != 1, return 0.
Otherwise, call the function recursively as sum_sq_digits(x / 10).
Return sum_sq_digits(x / 10) until all digits are processed.
Step 6: Define a function ishappy() to check whether the number is a Happy Number.
If sum_sq_digits(n) == 1, display "It is a Happy Number".
Otherwise, display "It is not a Happy Number".
Step 7: End of the algorithm.
Code:
import [Link].*;
public class Happy {
int n, sum = 0;
// Default constructor
Happy() {
n = 0;
}
// Function to set the number
void getnum(int nn) {
n = nn;
}
// Recursive function to calculate sum of squares of digits
int sum_sq_digits(int x) {
Page | 16
sum += (x % 10) * (x % 10);
if (sum > 9) {
if (x == 0)
x = sum;
if (sum == x)
return 1;
if (sum < 10 && sum != 1)
return 0;
return sum_sq_digits(x / 10);
}

return sum_sq_digits(x / 10);


}
// Function to check if number is Happy
void ishappy() {
if (sum_sq_digits(n) == 1)
[Link]("It is a Happy Number");
else
[Link]("It is not a Happy Number");
}
// Main method
public static void main() {
Happy ob = new Happy();
Scanner sc = new Scanner([Link]);
[Link]("Enter n: ");
int nn = [Link]();
[Link](nn);
[Link]();
}
}
Output:

Page | 17
Program 07: DECIMAL TO HEXA-DECIMAL
e.g: i/p = 25, o/p = 19, i/p = 28, o/p = 1C
Class Name: DexiHex
Data Memebers
int num: stores the decimal num
String hexa: to store the hexa decimal equivalent
Member methods:
DeciHex() : default constructor
void getNum() : to accept the input
void convert(int n) : find the hexa decimal equivalent of the paramter n using recursion
void display() : dispays the input as well as the output by invoking the function
Algorithm:
Step 1: Declare and initialize the required variables as num, hexa, and n.
Step 2: In the constructor, initialize num = 0 and hexa = "".
Step 3: Define a function getNum() to accept a decimal number from the user and assign it to
num.
Step 4: Define a recursive function convert(int n) to convert the decimal number into
hexadecimal using conditional logic:
If n != 0, find the remainder d = n % 16.
If d <= 9, concatenate d to the left of hexa.
Else, convert d to its hexadecimal character by adding 55 (to reach ASCII value for A–F) and
append it to hexa.
Call the function recursively as convert(n / 16).
Step 5: Define another recursive function convert2(int n) using a simpler approach:
If n != 0, extract the character at position (n % 16) from "0123456789ABCDEF" and add it to
hexa.
Call the function recursively as convert2(n / 16).
Step 6:Define a function display() to show the results:
Display "The Decimal Number: " + num.
Call the function convert2(num) to perform conversion.
Display "The Hexa Decimal Equivalent: " + hexa.
Step 7: End of the algorithm.
Code:
import [Link].*;
public class DeciHex {
int num;
String hexa;
// Default constructor
DeciHex() {
num = 0;
hexa = "";
}
// Function to accept the decimal number
void getNum() {
Scanner sc = new Scanner([Link]);
Page | 18
[Link]("Please enter the decimal number: ");
num = [Link]();
}
// Method 1: Recursive conversion using ASCII logic
void convert(int n) {
if (n != 0) {
int d = n % 16;
if (d <= 9)
hexa = d + hexa;
else if (d > 9)
hexa = (char) (d + 55) + hexa;
convert(n / 16);
}
}
// Method 2: Recursive conversion using character mapping
void convert2(int n) {
if (n != 0) {
hexa = "0123456789ABCDEF".charAt(n % 16) + hexa;
convert2(n / 16);
}
}
// Function to display results
void display() {
[Link]("The Decimal Number: " + num);
convert2(num);
[Link]("The Hexa Decimal Equivalent: " + hexa);
}
// Main method
public static void main(String args[]) {
DeciHex ob = new DeciHex();
[Link]();
[Link]();
}
}
Output:

Page | 19
Program 08: Mystery Number
[Mystery Number - if the number can be expressed by the sum of two numbers. Note that these
two numbers must be reverse of each other.]
It lies from 22 to 198 => (22 <= N <= 198) It is called mystery numbers because these are the
multiples of 11, and the sum of place values of unit (1) and tens (10) place in decimal
numeration.
Example 01: INPUT: 132
working: 132/11 = 12 which is obtained by adding 9 + 3 and 93+39 = 132
OUTPUT: 132 is a mystery number
Example 02: INPUT: 154
working: 154/11 = 14 which is obtained by adding 6 + 8 and 68+86 = 154
OUTPUT: 154 is a mystery number
Algorithm:
Step 1: Declare and initialize the required variables as n, k, and h.
Step 2: In the constructor, initialize n = 0.
Step 3: Define a function revNum(int num) using recursion to reverse a number:
If num == 0, return 0; Otherwise, return (num % 10) * (int)[Link](10,
(int)Math.log10(num)) + revNum(num / 10).
Step 4: Define a recursive function checkMys(int ad1, int ad2, int limit) to find whether the
number is a Mystery Number:
Form a number num by concatenating ad1 and ad2.
Find its reverse using revNum(num).
If num + revNum(num) equals n, display "n is a Mystery Number" and stop.
Otherwise, continue checking with checkMys(ad1 + 1, ad2 - 1, limit) until all pairs are tested.
Step 5: Define a function input() to:
Accept the number n from the user. Check if (22 <= n <= 198) and (n % 11 == 0). If not,
display "INVALID INPUT". Calculate h = n / 11.
Call checkMys(1, h - 1, h) to test possible pairs.
Step 6: End of the algorithm.
Code:
import [Link].*;
public class MysNum {
int n;
// Default constructor
MysNum() {
n = 0;
}
// Recursive function to reverse a number
int revNum(int num) {
if (num == 0)
return 0;
return (num % 10) * (int) [Link](10, (int) Math.log10(num)) + revNum(num / 10);
}
// Recursive function to check if the number is Mystery
void checkMys(int ad1, int ad2, int limit) {
Page | 20
if (ad1 > limit)
return;
int num = [Link](ad1 + "" + ad2);
int renum = revNum(num);
if (num + renum == n) {
[Link](n + " is a Mystery Number.");
return;
}
checkMys(ad1 + 1, ad2 - 1, limit);
}
// Input function
void input() {
Scanner sc = new Scanner([Link]);
[Link]("Please enter a number from 22 to 198 (multiple of 11): ");
n = [Link]();
if (n < 22 || n > 198 || n % 11 != 0) {
[Link]("INVALID INPUT");
return;
}
int h = n / 11;
checkMys(1, h - 1, h);
}
// Main method
public static void main(String args[]) {
MysNum ob = new MysNum();
[Link]();
}
}
Output:

Page | 21
Program 09: Spy Number
Design a class Spy to check if the number is a spy number or not. A spy number is a number
where the sum of its digits equal the product of the digits.
Example: 1124 => 1+1+2+4 = 8 and 1*1*2*4 = 8
Class Name: Spy
Data Members: num: to store th number
Member Methods:
Spy(int nn): initialize the data memeber num = nn.
int sumOfDigits(int i) returns the sum of the digits of num using recursive technique
int prodOfDigits(int i): returns the product of num using recursion
void check() checks whether the given number is a spy number or not
Algorithm:
Step 1: Start the program and declare the class Spy with the data member num.
Step 2: Define the constructor Spy(int nn) to initialize num = nn.
Step 3: Define the recursive method int sumOfDigits(int i) to calculate the sum of digits.
If i == 0, return 0; Otherwise, return (i % 10) + sumOfDigits(i / 10).
Step 4: Define another recursive method int prodOfDigits(int i) to calculate the product of
digits. If i == 0, return 1; Otherwise, return (i % 10) * prodOfDigits(i / 10).
Step 5: Define the method void check() to compare the sum and product of digits.
If both are equal, print that the number is a Spy Number.
Otherwise, print that it is not a Spy Number.
Step 6: In the main() method, accept the number from the user, create an object of the class
Spy, and call the method check().
Step 7: End of the algorithm
Code:
import [Link].*;
public class Spy {
int num;
// Constructor to initialize number
Spy(int nn) {
num = nn;
}
// Recursive function to find sum of digits
int sumOfDigits(int i) {
if (i == 0)
return 0;
return (i % 10) + sumOfDigits(i / 10);
}
// Recursive function to find product of digits
int prodOfDigits(int i) {
if (i == 0)
return 1;
return (i % 10) * prodOfDigits(i / 10);
}
// Function to check Spy Number
Page | 22
void check() {
if (sumOfDigits(num) == prodOfDigits(num))
[Link](num + " is a Spy Number.");
else
[Link](num + " is not a Spy Number.");
}
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();

Spy ob = new Spy(n);


[Link]();
}
}
Output:

Page | 23
Program 10: Binary Search – recursion
[ISC-2015]
A class Admission contains admission numbers of 100 students that re already arranged in
ascending order.
Some of the data members and memeber functions of the class are given below:
Class Name: Admission
Data Members/Instance Variables:
Adno[] : integer array to store admission numbers.
Memeber functions/methods:
Admission(int nn): constructor to initialise the array elements.
void fillArray(): to accept te elements/admission numbers into the array in ascending order.
int binSearch(int l, int u, int v) : to search a particular admission number (v) using binar search
and recursion echnique and return if found else -1.
Algorithm:
Step 1: Start the program and declare the class Admission with the data member Adno[] (array
to store admission numbers).
Step 2: Define the constructor Admission(int nn) to initialize the array Adno of size nn.
Step 3: Define the method fillArray() to input the array elements in ascending order using a
loop.
Step 4: Define the recursive method binSearch(int l, int u, int v) to perform binary search.
If l <= u, find the middle index m = (l + u) / 2.
If Adno[m] > v, search in the left half by calling binSearch(l, m - 1, v).
If Adno[m] < v, search in the right half by calling binSearch(m + 1, u, v).
If Adno[m] == v, return 1 (found).
If not found after all checks, return -1.
Step 5: In the main() method, input the size of the array and create an object of Admission.
Step 6: Call fillArray() to accept the admission numbers.
Step 7: Input the number to be searched and call the recursive binSearch() method.
If it returns 1, display “The number was found!”,
Otherwise display “The number was not found!”.
Step 8: End of the algorithm.
Code:
import [Link].*;
public class Admission {
int Adno[];
// Constructor to initialize array
Admission(int nn) {
Adno = new int[nn];
}
// Method to input admission numbers
void fillArray() {
Scanner sc = new Scanner([Link]);
[Link]("Please enter the numbers in ascending order: ");
for (int i = 0; i < [Link]; i++)
Adno[i] = [Link]();

Page | 24
}
// Recursive Binary Search Method
int binSearch(int l, int u, int v) {
if (l <= u) {
int m = (l + u) / 2;
if (Adno[m] > v)
return binSearch(l, m - 1, v);
else if (Adno[m] < v)
return binSearch(m + 1, u, v);
else
return 1;
}
return -1;
}
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);

[Link]("Please enter size of the array: ");


int nn = [Link]();

Admission ob = new Admission(nn);


[Link]();

[Link]("Please enter the admission number to be searched in the array: ");


int v = [Link]();

if ([Link](0, nn - 1, v) == 1)
[Link]("The number was found!");
else
[Link]("The number was not found!");
}
}
Output:

Page | 25
Program 11: Bubble Sort using recursion
Question:
A recursive bubble sort is a sorting technique that works by repeatedly comparing adjacent
elements and swapping them if they are in the wrong order, until the array is completely
sorted.
Design a class BubbleSort to sort an array of integers using recursion.
class name: BubbleSort
Data members/instance variables:
arr[]: integer array to store the elements
n: integer variable to store the size of the array
Member functions:
BubbleSort(int nn):
Constructor to initialize n = nn and create an integer array of size n.
void inputArray():
To accept n integer elements into the array.
void sort(int i, int j):
A recursive function to sort the array using the bubble sort technique.
void display ():
To display the sorted array elements.
Create a main method to call the methods.
Algorithm:
Step 1: Declare class named BubbleSort
Step 2: Declare the instance variables arr [] to store int ele, n to store size.
Step 3: Define constructor BubbleSort(int nn) to initialize data members. n==nn, create arr of
size n.
Step 4: Define void inputArray () to accept ele into the array using Scanner method, display
method “Enter elements into the array”. And use for loop i=0; i<n;i++ to accept elements.
Step 5: Define a recursive method void sort (int i, int j) to perform bubble sort using recursion.
Step 6: if i==n-1 return base case
Step 7: if j==n-i-1, call sort(i+1,0) //move to next pass
Step 8: else compare adjacent elements arr[j] and arr[j+1]. Call sort(i,j+1) to continue
comparing elements.
Step 9: End recursion method
Step 10: Define void display () to print sorted array.
Step 11: Create a main method and create an object for class BubbleSort, call inputArray(),
sort(0,0), and display().
Step 12: End of the algorithm
Code:
import [Link].*;
class BubbleSort{
int arr[];

Page | 26
int n;
BubbleSort(int nn){
n=nn;
arr=new int[n];
}

void inputArray(){
Scanner sc=new Scanner([Link]);
[Link]("Enter the elements of the array");
for(int i=0;i<n;i++){
arr[i]=[Link]();
}
}

void sort(int i,int j){


if(i==n-1)return;
if(j==n-i-1){
sort(i+1,0);
return;
}
if(arr[j]>arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
sort(i,j+1);
}

void display(){
[Link]("Sorted array:");
for(int i=0;i<n;i++){
[Link](arr[i]+" ");
}
}

public static void main(String args[]){


Scanner sc=new Scanner([Link]);
[Link]("Enter the number of elements:");
int size=[Link]();
BubbleSort b=new BubbleSort(size);
[Link]();
[Link](0,0);
[Link]();
}
}

Page | 27
Output:

Page | 28
Program 12: Emirp Number
An emirp number is a number which is prime backwards and forwards. Example: 13 and 31 are both
prime numbers. Thus, 13 is an emirp number.
Design a class Emirp to check if a given number is Emirp number or not.
Class name: Emirp
Data members/instance variables:
n: stores the number
rev: stores the reverse of the number
f: stores the divisor
Member functions:
Emirp(int nn): to assign n = nn, rev = 0 and f = 2
int isprime(int x): check if the number is prime using the recursive technique and return 1 if prime
otherwise return 0
void isEmirp(): reverse the given number and check if both the original number and the reverse number
are prime, by invoking the function isprime(int) and display the result with an appropriate message
Algorithm:
Step 1: Start the program and declare a class Emirp with data members n, rev, and f.
Step 2: Define a parameterized constructor Emirp(int nn) to initialize: n = nn, rev = 0, f = 2
Step 3: Define the recursive method int isprime(int x) to check whether a number is prime or
not.
If x < 2, return 0. If x == f, return 1. If x % f == 0, return 0. Otherwise, increment f by 1 and
recursively call isprime(x).
Step 4: Define the method void isEmirp() to check if the number is Emirp. Reverse the
number by repeatedly extracting digits and forming rev. Call isprime(n) to check if the original
number is prime.
If true, reset f = 2 and call isprime(rev) to check if the reversed number is also prime.
If both are prime, display “Emirp number!”. Otherwise, display “Not an Emirp number.”
Step 5: In the main() method:
Accept a number from the user.
Create an object Emirp obj = new Emirp(num).
Call the method [Link]().
Step 6: End of the Algorithm
Code:
import [Link];
class Emirp {
int n;
int rev;
int f;
// Constructor
public Emirp(int nn) {
n = nn;
rev = 0;
f = 2;
}

Page | 29
// Recursive function to check prime
public int isprime(int x) {
if (x < 2)
return 0;
if (x == f)
return 1;
if (x % f == 0)
return 0;
f++;
return isprime(x);
}
// Method to check Emirp number
public void isEmirp() {
for (int i = n; i != 0; i /= 10)
rev = rev * 10 + i % 10;
if (isprime(n) == 1) {
f = 2;
if (isprime(rev) == 1)
[Link]("Emirp number!");
else
[Link]("Not an Emirp number.");
} else
[Link]("Not an Emirp number.");
}
// Main method
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter the number: ");
int num = [Link]([Link]());
Emirp obj = new Emirp(num);
[Link]();
}
}
Output:

Page | 30
Program 13: Palindrome String
Class Name: Revstr
Data Members/ Instance Variables:
str: to store the string
Rev: to store the reversed string
Member Methods / Functions:
Revstr (): default constructor to initialize the instance variables.
void getstr (): to accept the number
void recReverse (int l): reverses the string using recursive technique
void check (): calls the function recReverse and returns whether the number is Palindrome or not.
Algorithm:
Step 1: Start the program and declare a class Revstr with the data members str and Rev (both
of type String).
Step 2: Define the constructor Revstr() to initialize str = "" and Rev = "".
Step 3: Define the method void getstr() to accept a word from the user and store it in str.
Step 4: Define the recursive method void recReverse(int l) to reverse the string.
If l > 0, append the character at position l - 1 of str to Rev.
Call recReverse(l - 1) to continue the reversal process.
Step 5: Define the method void check() to: Display the original string. Call
recReverse([Link]()) to reverse the string. Display the reversed string. Compare str and Rev
(case-insensitive) using equalsIgnoreCase(). If both are equal, print “Palindrome String”, else
print “Not a Palindrome String”.
Step 6: In the main() method, create an object of class Revstr, call getstr() and then check().
Step 7: End of the Algorithm
Code:
import [Link].*;
public class Revstr {
String str, Rev;
// Constructor
Revstr() {
str = "";
Rev = "";
}
// Method to get input string
void getstr() {
Scanner sc = new Scanner([Link]);
[Link]("Enter the Word: ");
str = [Link]();
}
// Recursive method to reverse the string
void recReverse(int l) {
if (l > 0) {
Rev = Rev + [Link](l - 1);
recReverse(l - 1);
}

Page | 31
}
// Method to check palindrome
void check() {
[Link]("Original String: " + str);
recReverse([Link]());
[Link]("Reverse String: " + Rev);

if ([Link](str))
[Link]("Palindrome String");
else
[Link]("Not a Palindrome String");
}
// Main method
public static void main() {
Revstr ob = new Revstr();
[Link]();
[Link]();
}
}
Output:

Page | 32
Program 14: Fibonacci
Design a class Fibonacci that generates:
The Fibonacci number series using recursion, and
The Fibonacci string series defined as:
F(0) = "A"
F(1) = "B"
F(n) = F(n–1) + F(n–2) for n > 1
Display the first 10 terms of both the numeric and string series.
Algorithm:
Step 1: Start the program and declare a class Fibonacci with data members num (integer) and str
(string).
Step 2: Define the recursive method int fibo(int n) to generate the Fibonacci number.
If n <= 1, return n.
Otherwise, return fibo(n - 1) + fibo(n - 2).
Step 3: Define the recursive method String fibos(int n) to generate the Fibonacci string.
If n == 0, return "A".
If n == 1, return "B". Otherwise, return fibos(n - 1) + fibos(n - 2).
Step 4: Define the method void hex() to display both series: Use a loop from i = 0 to 9 to print the
first 10 Fibonacci numbers. Use another loop to print the first 10 Fibonacci strings.
Step 5: In the main() method: Create an object of class Fibonacci. Call the method hex() to display
both series.
Step 6: End of the Algorithm
Code:
import [Link].*;
public class Fibonacci {
int num;
String str;
// Recursive method to generate Fibonacci numbers
int fibo(int n) {
return (n <= 1) ? n : (fibo(n - 1) + fibo(n - 2));
}
// Recursive method to generate Fibonacci strings
String fibos(int n) {
if (n == 0)
return "A";
if (n == 1)
return "B";
else
return fibos(n - 1) + fibos(n - 2);
}
// Method to display both numeric and string Fibonacci series
void hex() {
[Link]("Fibonacci Number Series:");
for (int i = 0; i < 10; i++)

Page | 33
[Link](fibo(i) + " ");
[Link]("\n");
[Link]("Fibonacci String Series:");
for (int i = 0; i < 10; i++)
[Link](fibos(i) + " ");
[Link]();
}
// Main method
public static void main(String args[]) {
Fibonacci ob = new Fibonacci();
[Link]();
}
}
Output:

Page | 34
PROGRAM 15: Change (Convert case)
Design a class Change to perform the following string operation:
Class name: Change.
Data members:
Str: to store the word.
Newstr: store the changed word.
Len: stores the length of the word
Member functions:
Change(): default constructor
Void inputword(): accept the word from the user.
Char caseconvert(char ch): converts the case of the character and returns it.
Void rechange(int); extracts characters using recursive technique and changes its case using caseconvert()
and forms a new word.
Void display(): displays both the words.
Algorithm:
Step 1: Declare class Rec_change
Step 2: Declare data members, Str to store original string, newstr to store modified string and len
to store the length of the string.
Step 3: Define the method inputword() to accept the input string
Step 4: Create scanner object and take input from the user, and display message “enter the string”
and assign it to str.
Step 5: Find the length of the string using [Link]() and assign it to len.
Step 6: Define a method char caseconvert(char ch) to change the case of a single char
Step 7: Find the ASCII value of ch and store it in asc
Step 8: If asc is between 65 and 90, convert uppercase to lowercase by adding 32 to ch and return.
Step 9: Else if asc is between 96 and 122, convert lowercase to uppercase by subtracting 32 from
ch and return it. Otherwise, return ch as is (for non-alphabetic characters)
Step 10: Define a recursive method rechange(int n) to change the case of all characters in the
string. If n==len, return base case. Otherwise convert the character at position n using
caseconvert([Link](n)) and add it to newstr.
Step 11: Call rechange(n+1) to process the next character recursively.
Step 12: Define a method display() to show the original and changed strings.
Step 13: Display string and changed string.
Step 14: In the main() method create an object R of the class Rec_change and call [Link](),
[Link]() and [Link]().
Step 15: end
Code:
import [Link].*;
class Rec_change{
String str,newstr;
int len;
Rec_change(){
str="";
newstr="";
len=0;
}

Page | 35
void inputword(){
Scanner sc=new Scanner([Link]);
[Link]("enter the string");
str=[Link]();
len=[Link]();
}
char caseconvert(char ch){
int asc=(int)ch;
if(asc>=65 && asc<=90){
return(char)(ch+32); //upper to lower
}
else if(asc>=97 && asc <=122){
return (char)(ch-32); //lower to upper
}
else{
return ch;
}
}
void recchange(int n){
if(n==len){
return;
}
else{
newstr=newstr+caseconvert([Link](n));
recchange(n+1);
}
}
void display(){
[Link]("String: "+str);
[Link]("Changed String; "+newstr);
}
public static void main(String args[]){
Rec_change R=new Rec_change();
[Link]();
[Link](0);
[Link]();
}
}
Output:

Page | 36
Page | 37
Index

Sl. No. Title Page


Arrays
A. Double Dimensional Arrays
1. Sorting Row-wise and Column-wise 39
2. Sorting the entire array 42
3. Transpose 44
4. Mirror Images 46
5. Rotation [90, 180, 270] 48
6. Specimen 2025 – Sum of all prime numbers in each row 50
and column
7. Spiral Form 53
8. Symmetric Matrix 55
9. Boundary Elements 57
10. Non-Boundary Elements 59
11. Upper and lower Principal Diagonal 61
12. Cyclic Shifting 63
13. Pattern Replication 66
B. Single Dimensional Arrays
1. Insertion Sort 68
2. Selection Sort 71
3. Bubble Sort 73
4. Linear Search 75
5. Binary Search 77
6. Equilibrium Index 79
7. Zig-Zag Order – Specimen 2025 81

Page | 38
A. Double Dimensional Arrays
Program 01: Sorting Row-wise and Column-wise
Write a program to declare a matrix A[][] of order (M × N) where M is the number of rows and N is the
number of columns such that both M and N must be greater than 2 and less than 10.
Allow the user to input integers into this matrix.
Perform the following tasks on the matrix:
(a) Display the original matrix.
(b) Sort each row of the matrix in ascending order using any standard sorting technique (like Bubble Sort).
(c) Display the matrix after row-wise sorting.
(d) Sort each column of the matrix in ascending order.
(e) Display the matrix after column-wise sorting.
Display an appropriate message for invalid matrix size.
Algorithm:
Step 1: Start the program.
Step 2: Input M (rows) and N (columns).
Step 3: If M < 3 or M > 9 or N < 3 or N > 9, print "MATRIX SIZE OUT OF RANGE" and stop.
Step 4: Declare a 2D integer array A[M][N].
Step 5: Input all the elements of the matrix.
Step 6: Display the original matrix.
Step 7: For row-wise sorting, use nested loops and Bubble Sort each row.
Step 8: Display the matrix after row-wise sorting.
Step 9: For column-wise sorting, use nested loops and Bubble Sort each column.
Step 10: Display the matrix after column-wise sorting.
Step 11: Stop the program.
Code:
import [Link];
class SortMatrix {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("M = ");
int m = [Link]();
[Link]("N = ");
int n = [Link]();
// Validate matrix size
if (m < 3 || m > 9 || n < 3 || n > 9) {
[Link]("MATRIX SIZE OUT OF RANGE");
return;
}
int[][] a = new int[m][n];
// Input matrix elements
[Link]("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
Page | 39
}
// Display original matrix
[Link]("\nORIGINAL MATRIX:");
displayMatrix(a, m, n);
// Row-wise sorting (ascending order)
for (int i = 0; i < m; i++) {
for (int pass = 0; pass < n - 1; pass++) {
for (int k = 0; k < n - 1 - pass; k++) {
if (a[i][k] > a[i][k + 1]) {
int temp = a[i][k];
a[i][k] = a[i][k + 1];
a[i][k + 1] = temp;
}
}
}
}
[Link]("\nMATRIX AFTER SORTING EACH ROW (ASCENDING):");
displayMatrix(a, m, n);
// Column-wise sorting (ascending order)
for (int j = 0; j < n; j++) {
for (int pass = 0; pass < m - 1; pass++) {
for (int i = 0; i < m - 1 - pass; i++) {
if (a[i][j] > a[i + 1][j]) {
int temp = a[i][j];
a[i][j] = a[i + 1][j];
a[i + 1][j] = temp;
}
}
}
}
[Link]("\nMATRIX AFTER SORTING EACH COLUMN (ASCENDING):");
displayMatrix(a, m, n);

[Link]();
}

// Method to display a matrix


public static void displayMatrix(int[][] arr, int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link](arr[i][j] + "\t");
}
[Link]();
}
}
}

Page | 40
Output:

Page | 41
Program 02: Sorting entire array
Write a program in Java to declare a matrix A[][] of order (M × N) where both M and N are greater than 2
and less than 10.
Allow the user to input integers into this matrix.
Perform the following tasks:
Display the original matrix.
Sort the entire matrix in ascending order (without converting it into a 1D array).
Display the sorted matrix.
Algorithm:
Step 1: Start
Step 2: Input values for M (rows) and N (columns)
Step 3: If M < 3 or M > 9 or N < 3 or N > 9, print “INVALID MATRIX SIZE” and stop
Step 4: Declare a 2D array A[M][N]
Step 5: Input all elements of the matrix
Step 6: Display the original matrix
Step 7: Sort all elements in ascending order directly in the 2D array using nested loops:
Compare every element (i, j) with every other (p, q) and swap if needed
Step 8: Display the sorted matrix
Step 9: Stop
Code:
import [Link];
class DDASort {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("M = ");
int M = [Link]();
[Link]("N = ");
int N = [Link]();
if (M < 3 || M > 9 || N < 3 || N > 9) {
[Link]("INVALID MATRIX SIZE");
return;
}
int[][] A = new int[M][N];
[Link]("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A[i][j] = [Link]();
}
}
[Link]("\nORIGINAL MATRIX:");
display(A, M, N);
// Sorting directly using DDA logic (no 1D array)
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
for (int p = 0; p < M; p++) {

Page | 42
for (int q = 0; q < N; q++) {
if (A[i][j] < A[p][q]) {
int temp = A[i][j];
A[i][j] = A[p][q];
A[p][q] = temp;
}
}
}
}
}
[Link]("\nSORTED MATRIX (ASCENDING ORDER):");
display(A, M, N);
[Link]();
}
public static void display(int[][] arr, int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link](arr[i][j] + "\t");
}
[Link]();
}
}
}
Output:

Page | 43
Program 03: Transpose
Write a program to input a square matrix and display its transpose.
(Transpose of a matrix is formed by interchanging its rows and columns.)
Algorithm:
Step 1: Start the program.
Step 2: Input an integer n representing the size of the square matrix.
Step 3: Declare a 2D array a[n][n].
Step 4: Input all elements into the matrix.
Step 5: Display the original matrix.
Step 6: Traverse and print the elements as a[j][i] instead of a[i][j].
Step 7: Stop the program.
Code:
import [Link];
class TransposeMatrix {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the square matrix: ");
int n = [Link]();
int[][] a = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nOriginal Matrix:");
displayMatrix(a);
[Link]("-----------------------------");
[Link]("Transpose Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](a[j][i] + " ");
}
[Link]();
}
}
public static void displayMatrix(int[][] m) {
for (int[] row : m) {
for (int val : row)
[Link](val + " ");
[Link]();
}
}
}

Page | 44
Output:

Page | 45
Program 04: Mirror Image
Write a program to input a square matrix A[][] of order N × N, where N is entered by the user.
The program should display the mirror image of the matrix.
Mirror image means reflecting the matrix horizontally (i.e., reversing each row).
Algorithm:
Step 01: Start
Step 02: Input N (the order of the square matrix).
Step 03: Check if N > 1 (since it’s a square matrix).
Step 04: Accept all elements into a 2D array A[N][N].
Step 05: Display the original matrix.
Step 06: For each row i, print the elements from the last column to the first column.
Step 07: Stop.

Code:
import [Link];
class MirrorImage {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("IT'S A SQUARE MATRIX, SO");
[Link]("Enter the size of the matrix: ");
int n = [Link]();
if (n <= 1) {
[Link]("INVALID SIZE");
return;
}
int[][] a = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nORIGINAL MATRIX:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
[Link]("\n-----------------------------");
[Link]("MIRROR IMAGE OF THE MATRIX:");
for (int i = 0; i < n; i++) {
for (int j = n - 1; j >= 0; j--) {
[Link](a[i][j] + "\t");
}

Page | 46
[Link]();
}
[Link]();
}
}
Output:

Page | 47
Program 05: Rotation [90, 180, 270]
Write a program to input a square matrix A[][] of order N × N, where N is entered by the user.
Display the original matrix and its rotations by 90°, 180°, and 270° clockwise.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer n representing the size of the square matrix.
Step 3: Declare a 2D array a[n][n].
Step 4: Input all elements into the matrix.
Step 5: Display the original matrix.
Step 6:
(a) For 90° rotation, print elements as a[j][n-1-i].
(b) For 180° rotation, print elements as a[n-1-i][n-1-j].
(c) For 270° rotation, print elements as a[n-1-j][i].
Step 7: Stop the program.
Code:
import [Link];
class MatrixRotation {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("IT'S A SQUARE MATRIX, SO");
[Link]("Enter the size of the matrix: ");
int n = [Link]();
if (n <= 1) {
[Link]("INVALID SIZE");
return;
}
int[][] a = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nORIGINAL MATRIX:");
display(a, n);
// 90° rotation
int[][] r90 = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
r90[j][n - 1 - i] = a[i][j];
}
}
// 180° rotation
int[][] r180 = new int[n][n];
for (int i = 0; i < n; i++) {

Page | 48
for (int j = 0; j < n; j++) {
r180[n - 1 - i][n - 1 - j] = a[i][j];
}
}
// 270° rotation
int[][] r270 = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
r270[n - 1 - j][i] = a[i][j];
}
}
[Link]("\n-----------------------------");
[Link]("MATRIX AFTER 90° ROTATION:");
display(r90, n);
[Link]("\n-----------------------------");
[Link]("MATRIX AFTER 180° ROTATION:");
display(r180, n);
[Link]("\n-----------------------------");
[Link]("MATRIX AFTER 270° ROTATION:");
display(r270, n);
}
public static void display(int[][] mat, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](mat[i][j] + "\t");
}
[Link]();
}
}
}
Output:

Page | 49
Program 06: Specimen 2025 – Prime Sum
Write a program to declare a matrix A[][] of order (M × N) where M is the number of rows and N is
the number of columns, such that both M and N must be greater than 2 and less than 10.
Allow the user to input positive integers into the matrix. If any number is negative or the matrix
size is invalid, display "INVALID INPUT" and terminate the program.
Perform the following operations:
Display the original matrix.
Compute the sum of all prime elements for each row and column.
Identify the row index having the maximum prime sum and the column index having the
maximum prime sum.
Display these indices and sums.
If there are no prime numbers in all rows or all columns, display an appropriate message
Algorithm:
Step 1: Start the program.
Step 2: Input integers M and N representing the number of rows and columns.
Step 3: Check if M and N are both greater than 2 and less than 10. If not, display "INVALID
INPUT" and stop.
Step 4: Declare a 2D array A[M][N].
Step 5: Input all elements of the matrix. If any element is negative, display "INVALID INPUT" and
stop.
Step 6: Display the matrix in tabular form.
Step 7: For each row, calculate the sum of prime numbers. Store and track the maximum prime sum
and its row index.
Step 8: For each column, calculate the sum of prime numbers. Store and track the maximum prime
sum and its column index.
Step 9: Display the row index and column index having the maximum prime sum, along with their
respective sums.
Step 10: If no prime numbers are found in the entire matrix, display the message accordingly.
Step 11: End the program.
Code:
import [Link];
class PrimeSums {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("M = ");
int M = [Link]();
[Link]("N = ");
int N = [Link]();
// Validate matrix size
if (M < 3 || M > 9 || N < 3 || N > 9) {
[Link]("INVALID INPUT");
return;
}
int[][] A = new int[M][N];
[Link]("Enter the elements of the array:");

Page | 50
// Input matrix and validate positive entries
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A[i][j] = [Link]();
if (A[i][j] < 0) {
[Link]("INVALID INPUT");
return;
}
}
}
// Display original matrix
[Link]("Original array:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
[Link](A[i][j] + "\t");
}
[Link]();
}
// --- Row-wise prime sum ---
int maxRowSum = 0;
String rowIndices = "";
for (int i = 0; i < M; i++) {
int rowSum = 0;
for (int j = 0; j < N; j++) {
if (isPrime(A[i][j])) {
rowSum += A[i][j];
}
}
if (rowSum > maxRowSum) {
maxRowSum = rowSum;
rowIndices = i + "";
} else if (rowSum == maxRowSum && rowSum != 0) {
rowIndices += " " + i;
}
}
// --- Column-wise prime sum ---
int maxColSum = 0;
String colIndices = "";
for (int j = 0; j < N; j++) {
int colSum = 0;
for (int i = 0; i < M; i++) {
if (isPrime(A[i][j])) {
colSum += A[i][j];
}
}
if (colSum > maxColSum) {

Page | 51
maxColSum = colSum;
colIndices = j + "";
} else if (colSum == maxColSum && colSum != 0) {
colIndices += " " + j;
}
}
// Display results
if (maxRowSum == 0 && maxColSum == 0) {
[Link]("NO PRIME NUMBERS FOUND IN THE MATRIX");
} else {
if (maxRowSum > 0)
[Link]("Row with max prime-sum: " + rowIndices + " (sum = " +
maxRowSum + ")");
else
[Link]("NO PRIME NUMBERS FOUND IN ANY ROW");
if (maxColSum > 0)
[Link]("Column with max prime-sum: " + colIndices + " (sum = " +
maxColSum + ")");
else
[Link]("NO PRIME NUMBERS FOUND IN ANY COLUMN");
}
[Link]();
}
// Function to check if a number is prime
public static boolean isPrime(int num) {
if (num < 2)
return false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0)
return false;
}
return true;
}
}
Output:

Page | 52
Program 07: Spiral Form
Write a program to input a square matrix A[][] of order N × N, where N represents the number of rows and
columns. Display the matrix in its original form and then print the elements of the matrix in spiral order,
starting from the top-left element and moving towards the centre in a clockwise direction.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer z representing the size of the square matrix.
Step 3: Declare a 2D array a[z][z].
Step 4: Input all elements into the matrix.
Step 5: Display the original matrix.
Step 6: Initialize four variables: up = 0, down = z - 1, left = 0, right = z - 1.
These represent the current top, bottom, left, and right boundaries of the spiral traversal.
Step 7: Repeat the following steps until all elements are printed:
Traverse from left to right along the top row (up). Increment up.
Traverse from up to down along the right column (right). Decrement right.
If up <= down, traverse from right to left along the bottom row (down). Decrement down.
If left <= right, traverse from down to up along the left column (left). Increment left.
Step 8: Display all elements in spiral form.
Step 9: Stop the program.
Code:
import [Link];
class SpiralForm {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a value for the side: ");
int z = [Link]();
int[][] a = new int[z][z];
[Link]("Enter " + (z * z) + " numbers:");
for (int i = 0; i < z; i++) {
for (int k = 0; k < z; k++) {
a[i][k] = [Link]();
}
}
[Link]("-----------------------------");
[Link]("YOUR SQUARE MATRIX");
for (int i = 0; i < z; i++) {
for (int k = 0; k < z; k++) {
[Link](a[i][k] + " ");
}
[Link]();
}
[Link]("-----------------------------");
[Link]("In spiral form");
int up = 0, down = z - 1, left = 0, right = z - 1;
while (up <= down && left <= right) {

Page | 53
// Traverse from left to right
for (int i = left; i <= right; i++)
[Link](a[up][i] + " ");
up++;
// Traverse from top to bottom
for (int i = up; i <= down; i++)
[Link](a[i][right] + " ");
right--;
// Traverse from right to left
if (up <= down) {
for (int i = right; i >= left; i--)
[Link](a[down][i] + " ");
down--;
}
// Traverse from bottom to top
if (left <= right) {
for (int i = down; i >= up; i--)
[Link](a[i][left] + " ");
left++;
}
}

[Link]();
}
}
Output:

Page | 54
Program 08: Symmetric Matrix
Write a program to declare a square matrix A[][] of order M × M, where M is the number of rows and
columns, such that M must be greater than 2 and less than 10.
Accept the value of M as user input. Display an appropriate message for an invalid input.
Allow the user to input integers into this matrix.
Perform the following tasks:
1. Display the original matrix.
2. Check if the given matrix is symmetric or not.
(A matrix is symmetric if A[i][j] = A[j][i] for all i and j.)
3. Find and display the sum of the left diagonal and the sum of the right diagonal
Algorithm:
Step 1: Start the program.
Step 2: Input an integer M, the size of the square matrix.
Step 3: If M < 3 or M > 9, display “SIZE IS OUT OF RANGE” and terminate.
Step 4: Declare a 2D array A[M][M].
Step 5: Input all elements of the matrix.
Step 6: Display the original matrix.
Step 7: Initialize leftSum and rightSum to 0, and isSymmetric to true.
Step 8: Traverse the matrix:
 If A[i][j] != A[j][i], set isSymmetric to false.
 If i == j, add A[i][j] to leftSum.
 If i + j == M - 1, add A[i][j] to rightSum.
Step 9: After traversal, display whether the matrix is symmetric or not.
Step 10: Display the sum of both diagonals.
Step 11: Stop the program.
Code:
import [Link];
class Symmetric {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("M = ");
int M = [Link]();
// Check for valid range
if (M < 3 || M > 9) {
[Link]("SIZE IS OUT OF RANGE.");
return;
}
int[][] A = new int[M][M];
[Link]("Enter elements of the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
A[i][j] = [Link]();
}
}
int leftSum = 0, rightSum = 0;
boolean isSymmetric = true;
Page | 55
[Link]("ORIGINAL MATRIX");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
[Link](A[i][j] + " ");
}
[Link]();
}
// Check symmetry and compute diagonals
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
if (A[i][j] != A[j][i]) {
isSymmetric = false;
}
}
leftSum += A[i][i];
rightSum += A[i][M - i - 1];
}
if (isSymmetric)
[Link]("THE GIVEN MATRIX IS SYMMETRIC.");
else
[Link]("THE GIVEN MATRIX IS NOT SYMMETRIC.");
[Link]("THE SUM OF THE LEFT DIAGONAL = " + leftSum);
[Link]("THE SUM OF THE RIGHT DIAGONAL = " + rightSum);
}
}
Output:

Page | 56
Program 09: Boundary Elements
Write a program to input a square matrix and display only its boundary elements in their respective positions,
leaving the non-boundary elements blank.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer n representing the size of the square matrix.
Step 3: Declare a 2D array a[n][n].
Step 4: Input all elements into the matrix.
Step 5: Display the original matrix.
Step 6: Traverse the matrix:
If (i == 0 || i == n - 1 || j == 0 || j == n - 1), print the element;
otherwise, print blank spaces.
Step 7: Stop the program.
Code:
import [Link];
class BoundaryElements {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the square matrix: ");
int n = [Link]();
int[][] a = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nOriginal Matrix:");
displayMatrix(a);
[Link]("-----------------------------");
[Link]("Boundary Elements:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1)
[Link](a[i][j] + " ");
else
[Link](" ");
}
[Link]();
}
}
public static void displayMatrix(int[][] m) {
for (int[] row : m) {
for (int val : row)
[Link](val + " ");

Page | 57
[Link]();
}
}
}
Output:

Page | 58
Program 10: Non Boundary Elements
Write a program to input a square matrix and display only its non-boundary elements in their respective
positions, leaving boundary elements blank.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer n representing the size of the square matrix.
Step 3: Declare a 2D array a[n][n].
Step 4: Input all elements into the matrix.
Step 5: Display the original matrix.
Step 6: Traverse the matrix:
If (i != 0 && i != n - 1 && j != 0 && j != n - 1), print the element;
otherwise, print blank spaces.
Step 7: Stop the program.
Code:
import [Link];
class NonBoundaryElements {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the square matrix: ");
int n = [Link]();
int[][] a = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nOriginal Matrix:");
displayMatrix(a);
[Link]("-----------------------------");
[Link]("Non-Boundary Elements:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != 0 && i != n - 1 && j != 0 && j != n - 1)
[Link](a[i][j] + " ");
else
[Link](" ");
}
[Link]();
}
}
public static void displayMatrix(int[][] m) {
for (int[] row : m) {
for (int val : row)
[Link](val + " ");
Page | 59
[Link]();
}
}
}
Output:

Page | 60
Program 11: Upper and Lower Symmetry
Write a program to input a square matrix of order n × n (where n ≥ 2).
The program should:
Display the original matrix.
Display the upper principal diagonal elements (elements above the main diagonal) in their respective
positions, leaving other positions blank.
Display the lower principal diagonal elements (elements below the main diagonal) in their respective
positions, leaving other positions blank.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer n representing the size of the square matrix.
Step 3: Declare a 2D array a[n][n].
Step 4: Input all the elements into the matrix.
Step 5: Display the original matrix.
Step 6: For upper principal diagonal elements:
a) Traverse each element a[i][j].
b) If j > i, print the element; otherwise, print a blank space.
Step 7: For lower principal diagonal elements:
a) Traverse each element a[i][j].
b) If i > j, print the element; otherwise, print a blank space.
Step 8: Stop the program.
Code:
import [Link];
class MatrixDiagonalDisplay {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the square matrix: ");
int n = [Link]();
if (n < 2) {
[Link]("INVALID INPUT. Matrix size must be at least 2.");
return;
}
int[][] a = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nOriginal Matrix:");
displayMatrix(a);
[Link]("-----------------------------");
[Link]("Upper Principal Diagonal Elements:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {

Page | 61
if (j > i)
[Link](a[i][j] + " ");
else
[Link](" "); // leave space
}
[Link]();
}
[Link]("-----------------------------");
[Link]("Lower Principal Diagonal Elements:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j)
[Link](a[i][j] + " ");
else
[Link](" "); // leave space
}
[Link]();
}
[Link]("-----------------------------");
}
// Utility method to display matrix neatly
public static void displayMatrix(int[][] m) {
for (int[] row : m) {
for (int val : row) {
[Link](val + " ");
}
[Link]();
}
}
}
Output:

Page | 62
Program 12: Cyclic Shifting
Question:
Write a program to input a square matrix of order n × n (where n ≥ 2). The program should perform the
following operations:
Display the original matrix.
Perform and display cyclic rotations of rows — that is, shift each row one position down cyclically, moving
the last row to the top, and repeat for each rotation.
Perform and display cyclic rotations of columns — that is, shift each column one position right cyclically,
moving the last column to the first position, and repeat for each rotation.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer n, the size of the square matrix.
Step 3: Declare two 2D arrays a[n][n] and b[n][n].
Step 4: Input all the elements of the matrix a.
Step 5: Display the original matrix.
Step 6: For cyclic rotation of rows:
a) For each rotation, move the elements of each row down by one position, with the last row
wrapping to the top.
b) Display the matrix after every rotation.
Step 7: For cyclic rotation of columns:
a) For each rotation, move the elements of each column right by one position, with the last column
wrapping to the first position.
b) Display the matrix after every rotation.
Step 8: Stop the program.
Code:
import [Link];
class CyclicMatrixRotation {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("It's a SQUARE MATRIX.");
[Link]("Enter the size of the matrix: ");
int n = [Link]();
if (n < 2) {
[Link]("INVALID INPUT. Matrix size must be at least 2.");
return;
}
int[][] a = new int[n][n];
int[][] b = new int[n][n];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = [Link]();
}
}
[Link]("\nOriginal Matrix:");

Page | 63
displayMatrix(a);
// --- Cyclic Rotation of Rows ---
[Link]("-----------------------------");
[Link]("Cyclic Rotation of Rows:");
[Link]("-----------------------------");
for (int r = 0; r < n; r++) {
// Rotate rows cyclically
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = a[(i + 1) % n][j];
}
}
// Copy back to a
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = b[i][j];
}
}
displayMatrix(a);
[Link]("-----------------------------");
}
// --- Cyclic Rotation of Columns ---
[Link]("Cyclic Rotation of Columns:");
[Link]("-----------------------------");
for (int c = 0; c < n; c++) {
// Rotate columns cyclically
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = a[i][(j + 1) % n];
}
}
// Copy back to a
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = b[i][j];
}
}
displayMatrix(a);
[Link]("-----------------------------");
}
}
// Utility method to display a matrix
public static void displayMatrix(int[][] m) {
for (int[] row : m) {
for (int val : row) {
[Link](val + " ");

Page | 64
}
[Link]();
}
}
}
Output:

Page | 65
Program 13: Pattern Replication
Write a Java program to accept an integer r (the number of rows and columns of a square matrix) and three
characters. Using these inputs, display a square matrix of order r × r based on the following rules:
The third character should appear along both the main diagonal and the secondary diagonal.
The first character should appear at the upper and lower intersections of the diagonals.
The second character should appear at the left and right intersections of the diagonals.
Algorithm:
Step 1: Start the program.
Step 2: Accept an integer r representing the size of the square matrix.
Step 3: Declare a 2D character array a[r][r].
Step 4: Accept three characters: First character → c1; Second character → c2; Third character →
c3
Step 5: For each row i from 0 to r - 1, and for each column j from 0 to r - 1, do the following:
a. If i == j or i + j == r - 1, assign a[i][j] = c3 (for diagonals).
b. Else if (i < j && i + j < r - 1) or (i > j && i + j > r - 1), assign a[i][j] = c1 (upper/lower
intersections).
c. Otherwise, assign a[i][j] = c2 (left/right intersections).
Step 6: Print the matrix in tabular form.
Step 7: Stop the program.
Code:
import [Link].*;
public class DDAQuestion {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the length of the row: ");
int r = [Link]();
char[][] a = new char[r][r];
[Link]("Enter three characters:");
[Link]("Enter First character: ");
char c1 = [Link]().charAt(0);
[Link]("Enter Second character: ");
char c2 = [Link]().charAt(0);
[Link]("Enter Third character: ");
char c3 = [Link]().charAt(0);
// Filling matrix according to the pattern
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
if (i == j || (i + j) == r - 1) {
a[i][j] = c3; // Diagonals
} else if ((i < j && i + j < r - 1) || (i > j && i + j > r - 1)) {
a[i][j] = c1; // Upper and lower intersections
} else {
a[i][j] = c2; // Left and right intersections
}
}

Page | 66
}
// Display the matrix
[Link]("\nThe Matrix is:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
}
}
Output:

Page | 67
B. Single Dimensional Arrays
Program 01: Insertion Sort
A class InsSort contains an array of integers which sorts the elements in a particular order.
Some of the members of the class are given below:
Class name: InsSort
Data members/instance variables:
arr[]: stores the array elements
size: stores the number of elements in the array
Methods/Member functions:
InsSort(int s): constructor to initialize size = s
void getArray(): accepts the array elements
void insertionSort(): sorts the elements of the array in descending order using the Insertion Sort technique
double find(): calculates and returns the average of all the odd numbers in the array
void display(): displays the elements of the array in a sorted order along with the average of all the odd
numbers in the array by invoking the function find() with an appropriate message.
Specify the class InsSort giving details of the constructor(), void getArray(), void insertionSort(),
double find() and void display(). Define a main() function to create an object and call all the
functions accordingly to enable the task.
Algorithm:
Step 1: Start the program.
Step 2: Define the class InsSort.
Step 3: Declare the data members: arr[] → to store the array elements size → to store the number of
elements
Step 4: Define the constructor InsSort(int s): Initialize size = s; Create integer array arr = new
int[size]
Step 5: Define method void getArray(): Accept size number of elements from the user; Store them
in the array arr[]
Step 6: Define method void insertionSort(): Use the Insertion Sort technique
Arrange elements in descending order
 For each element arr[i] from index 1 to size-1
 Compare it with elements before it
 Shift smaller elements to the right
 Place the element (key) in its correct position
Step 7: Define method double find(): Initialize sum = 0, count = 0; Traverse array; If element is
odd, add to sum and increment count; Return the average of odd elements as (double) sum / count
Step 8: Define method void display(): Display the sorted array elements; Call find() and display the
average of odd numbers with a message
Step 9: In the main() method; Accept array size from the user; Create an object of InsSort; Call
methods in sequence: getArray(), insertionSort(), and display()
Step 10: End of algorithm.
Code:
import [Link];
class InsSort {
int arr[];

Page | 68
int size;
// Constructor to initialize array size
public InsSort(int s) {
size = s;
arr = new int[size];
}
// Accept array elements from user
public void getArray() {
Scanner in = new Scanner([Link]);
[Link]("Enter array elements:");
for (int i = 0; i < size; i++) {
arr[i] = [Link]([Link]());
}
}
// Insertion sort in descending order
public void insertionSort() {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] < key) { // descending order condition
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
// Find average of odd numbers
public double find() {
int sum = 0, count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] % 2 != 0) {
sum += arr[i];
count++;
}
}
if (count == 0) return 0; // avoid division by zero
return (double) sum / count;
}
// Display sorted array and average of odd numbers
public void display() {
[Link]("Sorted list (descending): ");
for (int i = 0; i < size; i++) {
[Link](arr[i] + " ");
}
[Link]();
[Link]("Average of odd numbers: " + find());

Page | 69
}
// Main function
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Array size: ");
int s = [Link]([Link]());
InsSort obj = new InsSort(s);
[Link]();
[Link]();
[Link]();
}
}
Output:

Page | 70
Program 02: Selection Sort
Program to perform Selection Sort
Algorithm:
Step 1: Start the program.
Step 2: Create a Scanner object to take user input.
Step 3: Input the size of the array n.
Step 4: Create an integer array a[] of size n.
Step 5: Input n elements into the array.
Step 6: Ask the user whether they want to sort the array in ascending or descending order.
Step 7: If ascending order is chosen:
a. For each index i from 0 to n-2:
i. Assume the smallest element is at a[i] and store its position as pos = i.
ii. For each index j from i+1 to n-1:
If a[j] < a[pos], update pos = j.
iii. Swap a[i] with a[pos].
If descending order is chosen:
a. For each index i from 0 to n-2:
i. Assume the largest element is at a[i] and store its position as pos = i.
ii. For each index j from i+1 to n-1:
If a[j] > a[pos], update pos = j.
iii. Swap a[i] with a[pos].
Step 8: Display the sorted array elements.
Step 9: Stop the program.
Code:
import [Link].*;
class SelectionSort {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Input the size of the array: ");
int n = [Link]();
int a[] = new int[n];
[Link]("Input the array elements:");
for (int i = 0; i < n; i++) {
a[i] = [Link]();
}
[Link]("Enter 1 for Ascending or 2 for Descending order: ");
int choice = [Link]();
// Selection Sort logic
for (int i = 0; i < n - 1; i++) {
int pos = i;
for (int j = i + 1; j < n; j++) {
if (choice == 1 && a[j] < a[pos]) {
pos = j; // For ascending
} else if (choice == 2 && a[j] > a[pos]) {
pos = j; // For descending

Page | 71
}
}
// Swap elements
int temp = a[i];
a[i] = a[pos];
a[pos] = temp;
}
[Link]("Arranged array:");
for (int i = 0; i < n; i++) {
[Link](a[i] + " ");
}
}
}
Output:

Page | 72
Program 03: Bubble Sort
Program to perform Bubble Sort
Algorithm:
Step 1: Start the program.
Step 2: Create a Scanner object to take input from the user.
Step 3: Input the number of elements n.
Step 4: Create an integer array a[] of size n.
Step 5: Input all array elements from the user.
Step 6: Ask the user to choose sorting order:
 Enter 1 for ascending order.
 Enter 2 for descending order.
Step 7: Repeat the following process for each pass k from 0 to n - 2:
a. For each element i from 0 to n - k - 2:
• If choice is 1 (ascending) and a[i] > a[i + 1], swap a[i] and a[i + 1].
• If choice is 2 (descending) and a[i] < a[i + 1], swap a[i] and a[i + 1].
Step 8: After all passes, print the sorted array elements.
Step 9: Stop the program.
Code:
import [Link].*;
class BubbleSort {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("How many values do you want to enter? ");
int n = [Link]();
int a[] = new int[n];
[Link]("Enter your values:");
for (int i = 0; i < n; i++) {
a[i] = [Link]();
}
[Link]("Enter 1 for Ascending or 2 for Descending order: ");
int choice = [Link]();
// Bubble Sort logic
for (int k = 0; k < n - 1; k++) {
for (int i = 0; i < n - k - 1; i++) {
if ((choice == 1 && a[i] > a[i + 1]) || (choice == 2 && a[i] < a[i + 1])) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
[Link]("\nArranged order:");
for (int i = 0; i < n; i++) {
[Link](a[i] + " ");
}

Page | 73
}
}
Output:

Page | 74
Program 04: Linear Search
Program to perform Linear Sort
Algorithm:
Step 1: Start the program.
Step 2: Input the total number of elements n.
Step 3: Declare an integer array arr[] of size n.
Step 4: Input n elements into the array.
Step 5: Input the element to be searched, se.
Step 6: Initialize a flag found = false.
Step 7: Repeat for each index i from 0 to n - 1:
a. If arr[i] == se, set found = true, store position i, and exit the loop.
Step 8: If found is true, display "Element found at position (i + 1)";
else, display "Element not found".
Step 9: Stop the program.
Code:
import [Link].*;
class LinearSearch {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]();
int arr[] = new int[n];
[Link]("Enter the array elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link]("Enter the element to search: ");
int se = [Link]();
boolean found = false;
int pos = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == se) {
found = true;
pos = i;
break;
}
}
if (found)
[Link]("Element found at position: " + (pos + 1));
else
[Link]("Element not found in the array.");
}
}
Output:

Page | 75
Page | 76
Program 05: Binary Search
Program to perform Binary Search
Algorithm:
Step 1: Start the program.
Step 2: Input the number of elements n.
Step 3: Create an integer array arr[] of size n.
Step 4: Input all the array elements in ascending or descending order.
Step 5: Input the search element se.
Step 6: Detect the order of the array: If arr[0] < arr[n - 1], it is ascending; otherwise, descending.
Step 7: Initialize low = 0, high = n - 1, and a flag found = false.
Step 8: Repeat while low <= high:
a. Compute mid = (low + high) / 2.
b. If arr[mid] == se, display "Element found" and set found = true.
c. If the array is ascending:
• If se < arr[mid], set high = mid - 1.
• Else set low = mid + 1.
d. If the array is descending:
• If se > arr[mid], set high = mid - 1.
• Else set low = mid + 1.
Step 9: If found is still false, display "Element not found".
Step 10: Stop the program.
Code:
import [Link].*;
class BinarySearch {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]();
int arr[] = new int[n];
[Link]("Enter the elements in ascending or descending order:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link]("Enter the element to search: ");
int se = [Link]();
boolean isAscending = arr[0] < arr[n - 1]; // Detect array order
int low = 0, high = n - 1;
boolean found = false;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == se) {
[Link]("Element found at position: " + (mid + 1));
found = true;
break;
}

Page | 77
if (isAscending) {
if (se < arr[mid])
high = mid - 1;
else
low = mid + 1;
} else {
if (se > arr[mid])
high = mid - 1;
else
low = mid + 1;
}
}
if (!found)
[Link]("Element not found in the array.");
}
}
Output:

Page | 78
Program 06: Equilibrium Index
Write a program to declare a single-dimensional array A[] of size L, where L is an integer greater than or
equal to 3 and less than or equal to 50. Allow the user to input integers into this array. Display an appropriate
error message for an invalid input.

Perform the following tasks on the array:


a) Display the array.
b) Find and print all equilibrium indices in increasing order. An index i (0-based) is called an equilibrium
index if the sum of elements on its left equals the sum of elements on its right.
c) If no equilibrium index exists, display an appropriate message.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer L representing the size of the array.
Step 3: If L < 3 or L > 50, display "INVALID INPUT" and terminate the program.
Step 4: Declare an integer array A[L].
Step 5: Input L integers into the array.
Step 6: Display the array elements in the format:
Array: element1, element2, ..., elementL
Step 7: Initialize a flag found = false.
Step 8: For each index i from 0 to L - 1:
a. Initialize leftSum = 0 and rightSum = 0.
b. Compute the sum of all elements to the left of index i.
c. Compute the sum of all elements to the right of index i.
d. If leftSum == rightSum, print index i and set found = true.
Step 9: If found is still false, print "NIL".
Step 10: Stop the program.
Code:
import [Link];
class Equilibrium {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("L = ");
int L = [Link]();
// Validate array size
if (L < 3 || L > 50) {
[Link]("INVALID INPUT");
return;
}
int A[] = new int[L];
[Link]("Enter array elements:");
for (int i = 0; i < L; i++) {
A[i] = [Link]();
}
// Display the array
[Link]("Array: ");

Page | 79
for (int i = 0; i < L; i++) {
[Link](A[i]);
if (i < L - 1)
[Link](", ");
}
[Link]();
// Find equilibrium indices
boolean found = false;
[Link]("Equilibrium Indices: ");
for (int i = 0; i < L; i++) {
int leftSum = 0, rightSum = 0;
for (int j = 0; j < i; j++)
leftSum += A[j];
for (int j = i + 1; j < L; j++)
rightSum += A[j];
if (leftSum == rightSum) {
if (found)
[Link](", ");
[Link](i);
found = true;
}
}
if (!found)
[Link]("NIL");

[Link]();
}
}
Output:

Page | 80
Program 07: Zig-Zag Order
Write a program to declare a single-dimensional array of size N, where N is an integer greater than 2 and less
than 10.
Allow the user to input positive integers into this array.
Display an appropriate error message for an invalid input.
Rearrange the array in zig-zag order in the form
arr[0] ≤ arr[1] ≥ arr[2] ≤ arr[3] ≥ arr[4] … using in-place swaps only.
Perform the following tasks on the array:
a) Display the original array.
b) Transform it into zig-zag order.
c) Display the transformed array.
Algorithm:
Step 1: Start the program.
Step 2: Input an integer N.
Step 3: Check if N is between 3 and 9 (both inclusive). If not, display INVALID INPUT and stop.
Step 4: Declare an array A[N].
Step 5: Input all elements. If any element is negative, display INVALID INPUT and stop.
Step 6: Display the original array.
Step 7: Rearrange the array in zig-zag order using in-place swaps:
(a) If index i is even, ensure A[i] ≤ A[i+1].
(b) If index i is odd, ensure A[i] ≥ A[i+1].
Step 8: Display the zig-zag array.
Step 9: Stop the program.
Code:
import [Link];
class ZigZag {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("N = ");
int n = [Link]();
// Check for valid size
if (n < 3 || n > 9) {
[Link]("INVALID INPUT");
return;
}
int a[] = new int[n];
[Link]("Array Elements:");
for (int i = 0; i < n; i++) {
a[i] = [Link]();
if (a[i] < 0) {
[Link]("INVALID INPUT");
return;
}
}
// Display original array

Page | 81
[Link]("Original Array: ");
for (int i = 0; i < n; i++)
[Link](a[i] + " ");
// Zig-Zag rearrangement
boolean flag = true;
for (int i = 0; i < n - 1; i++) {
if (flag) {
if (a[i] > a[i + 1])
swap(a, i, i + 1);
} else {
if (a[i] < a[i + 1])
swap(a, i, i + 1);
}
flag = !flag;
}
// Display transformed array
[Link]("\nZig-Zag Array: ");
for (int i = 0; i < n; i++)
[Link](a[i] + " ");
[Link]();
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Output:

Page | 82
Page | 83
Index

Sl. No. Title Page


Data Structures
1. Dequeue 85
2. Register [Stack] 89
3. Bookshelf [Stack] 92
4. Circular Queue 95
5. Linear Queue 98

Page | 84
Program 01: Dequeue
A double ended queue is a linear data structure which enables user to add or remove the data from rear or
front index.
Define a class: dequeue
Data members:
arr[]: array to hold upto 100 int elements.
limit: stores the limit of the dequeue
front: to point the index to the front end of the dequeue,
rear: to point the index to the rear end of the dequeue
Member functions
dequeue(int l): constructor to initialize l to limit and 0 to front and rear
void addrear(int val): to add the int val from rear if possible otherwise display "Overflow"
void addfront(int val): to add the int val from the front, if possible, otherwise display the message
"Overflow"
int popfront(): to remove and return an int from front if possible, otherwise display the message underflow
int poprear(): to remove and return an int from rare if possible otherwise display the message underflow (ifrn
-99)
void display(): print the elements of the dequeue otherwise display underflow
Algorithm:
Step 1: Declare class dequeue.
Step 2: Declare data members — front, rear, integer array arr[1000], and limit for size.
Step 3: Define constructor dequeue(int l) to initialize limit = l and set front = rear = 0.
Step 4: Define method addrear(int val) to insert an element at the rear.
If rear == limit - 1, display “Overflow”; else update rear and store val in arr[rear].
Step 5: Define method addfront(int val) to insert an element at the front.
If front == 0, display “Overflows”; else update front and store val in arr[front].
Step 6: Define method delrear() to delete an element from the rear.
If rear == 0, display “Underflows”; else return arr[rear] and adjust rear.
Step 7: Define method delfront() to delete an element from the front.
If front == 0, display “Underflows”; else return arr[front] and adjust front.
Step 8: Define method display() to print elements from front to rear.
If deque is empty, display “Dequeue is empty”.
Step 9: End of the algorithm.
Code:
import [Link].*;
class Dequeue {
int front, rear, arr[], limit;
Dequeue(int l) {
limit = l;
arr = new int[limit];
front = rear = -1;
}
void addrear(int val) {
if (rear == limit - 1)
[Link]("Overflow");
else {

Page | 85
if (front == -1)
front = 0;
rear++;
arr[rear] = val;
}
}
void addfront(int val) {
if (front == 0)
[Link]("Overflow");
else {
if (front == -1) {
front = rear = 0;
arr[front] = val;
} else {
front--;
arr[front] = val;
}
}
}
int delrear() {
if (front == -1)
[Link]("Underflow");
else {
int v = arr[rear];
if (front == rear)
front = rear = -1;
else
rear--;
return v;
}
return -999;
}
int delfront() {
if (front == -1)
[Link]("Underflow");
else {
int v = arr[front];
if (front == rear)
front = rear = -1;
else
front++;
return v;
}
return -999;
}
void display() {

Page | 86
if (front == -1)
[Link]("Dequeue is empty");
else {
[Link]("The Dequeue is:");
for (int i = front; i <= rear; i++)
[Link](arr[i] + " || ");
[Link]();
}
}
public static void main(String args[]) {
Scanner obj = new Scanner([Link]);
[Link]("Enter the size of the Dequeue:");
Dequeue ob = new Dequeue([Link]());
while (true) {
[Link]("\nChoose operation:");
[Link]("1. Add from rear");
[Link]("2. Add from front");
[Link]("3. Delete from front");
[Link]("4. Delete from rear");
[Link]("5. Display");
[Link]("6. Exit");
switch ([Link]()) {
case 1:
[Link]("Enter the number: ");
[Link]([Link]());
break;
case 2:
[Link]("Enter the number: ");
[Link]([Link]());
break;
case 3:
[Link]("Deleted: " + [Link]());
break;
case 4:
[Link]("Deleted: " + [Link]());
break;
case 5:
[Link]();
break;
case 6:
[Link]("Exiting...");
[Link](0);
default:
[Link]("Invalid choice");
}
}

Page | 87
}
}
Output:

Page | 88
Program 02: Register
Register is an entity which can hold a maximum of 100 names. The register enables the user to add and
remove names from the topmost end only.
Define a class Register with the following details:
Class name: Register
Data members/instance variables:
stud[]: array to store the names of the students
cap: stores the maximum capacity of the array
top: to point the index of the top end
Member functions:
Register(int max): constructor to initialize the data member cap = max, top = -1 and create the string array
void push(String n): to add names in the register at the top location if possible, otherwise display the message
“OVERFLOW”
String pop(): removes and returns the names from the topmost location of the register if any, else returns “$
$”
void display(): displays all the names in the register
Algorithm:
Step 1: Start the program and declare class Register.
Step 2: Declare data members: stud[] as a string array to store student names. cap for stack capacity.
top to track the topmost element.
Step 3: Define constructor Register(int max). Set cap = max. If cap > 100, set cap = 100. Create
array stud = new String[cap]. Initialize top = -1.
Step 4: Define method push(String n). If top + 1 == cap, display "OVERFLOW". Else increment
top and store name: stud[++top] = n. Display confirmation message.
Step 5: Define method pop(). If top == -1, return "$$" (underflow indicator). Else return stud[top--].
Step 6: Define method display(). If top == -1, display "STACK EMPTY". Else print all names from
index 0 to top.
Step 7: In main() method: Create Scanner object for input. Ask user for stack capacity and create
object Register obj = new Register(cap).
Step 8: Use a loop to display menu:
1. PUSH NAME
2. POP NAME
3. DISPLAY NAME
4. Exit
Step 9: Based on user choice: For 1, input name, convert to uppercase, and call push().
For 2, call pop() and display popped name or "UNDERFLOW".
For 3, call display().
For any other choice, print "Bye!" and exit.
Step 10: End the program.
Code:
import [Link];
class Register{
String stud[];
int cap;
int top;
public Register(int max){

Page | 89
cap = max;
if(cap > 100)
cap = 100;
stud = new String[cap];
top = -1;
}
public void push(String n){
if(top + 1 == cap)
[Link]("OVERFLOW");
else{
stud[++top] = n;
[Link](n + " PUSHED");
}
}
public String pop(){
if(top == -1)
return "$$";
return stud[top--];
}
public void display(){
if(top == -1)
[Link]("STACK EMPTY");
else{
for(int i = 0; i <= top; i++)
[Link](stud[i]);
}
}
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Capacity: ");
int cap = [Link]([Link]());
Register obj = new Register(cap);
while(true){
[Link]("1. PUSH NAME");
[Link]("2. POP NAME");
[Link]("3. DISPLAY NAME");
[Link]("Enter your choice: ");
int choice = [Link]([Link]());
switch(choice){
case 1:
[Link]("Name to be pushed: ");
String n = [Link]().toUpperCase();
[Link](n);
break;
case 2:
n = [Link]();

Page | 90
if([Link]("$$"))
[Link]("UNDERFLOW");
else
[Link](n + " POPPED");
break;
case 3:
[Link]();
break;
default:
[Link]("Bye!");
return;
}
}
}
}
Output:

Page | 91
Program 03: Bookshelf
A bookshelf is designed to store the books in a stack with LIFO (Last In First Out) operation. Define a
class Book with the following specifications:
Class name: Book
Data members/instance variables:
name[]: stores the names of the books
point: stores the index of the topmost book
max: stores the maximum capacity of the bookshelf
Methods/Member functions:
Book(int cap): constructor to initialize the data members max = cap and point = -1
void tell(): displays the name of the book which was last entered in the shelf. If there is no book left in the
shelf, displays the message “SHELF EMPTY”
void add(String v): adds the name of the book to the shelf if possible, otherwise displays the message
“SHELF FULL”
void display(): displays all the names of the books available in the shelf
Algorithm:
Step 1: Start the program and declare class Book.
Step 2: Declare data members: name[] as a string array to store book names. point as the index of
the top book. max for bookshelf capacity.
Step 3: Define constructor Book(int cap). Set max = cap. Initialize point = -1. Create string array
name = new String[max].
Step 4: Define method tell(). If point == -1, display "SHELF EMPTY". Else display "LAST
ENTERED: " followed by name[point].
Step 5: Define method add(String v). If point + 1 == max, display "SHELF FULL". Else increment
point and store the book: name[++point] = v.
Step 6: Define method display(). If point == -1, display "SHELF EMPTY". Else print "BOOKS
AVAILABLE:" and display all books from 0 to point.
Step 7: In main() method: Create Scanner object for input. Ask user for bookshelf capacity and
create object Book stack = new Book(cap).
Step 8: Display menu repeatedly:
1. Last entered book
2. Add book
3. Display all books
4. Exit
Step 9: Based on user choice: For 1, call tell() to show last entered book. For 2, input book name
and call add(). For 3, call display() to show all stored books. For any other input, print "Bye!" and
exit.
Step 10: End of the algorithm.
Code:
import [Link];
class Book {
String name[];
int point;
int max;
public Book(int cap) {
max = cap;

Page | 92
point = -1;
name = new String[max];
}
public void tell() {
if (point == -1)
[Link]("SHELF EMPTY");
else
[Link]("LAST ENTERED: " + name[point]);
}
public void add(String v) {
if (point + 1 == max)
[Link]("SHELF FULL");
else
name[++point] = v;
}
public void display() {
if (point == -1)
[Link]("SHELF EMPTY");
else {
[Link]("BOOKS AVAILABLE:");
for (int i = 0; i <= point; i++)
[Link](name[i]);
[Link]();
}
}
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Bookshelf capacity: ");
int cap = [Link]([Link]());
Book stack = new Book(cap);
while (true) {
[Link]("1. Last entered book");
[Link]("2. Add book");
[Link]("3. Display all books");
[Link]("Enter your choice: ");
int choice = [Link]([Link]());
switch (choice) {
case 1:
[Link]();
break;
case 2:
[Link]("Name of the book: ");
String n = [Link]();
[Link](n);
break;
case 3:

Page | 93
[Link]();
break;
default:
[Link]("Bye!");
return;
}
}
}
}
Output:

Page | 94
Program 04: Circular Queue
A circular queue is a linear data structure that allows data insertion at the rear and removed from the front,
with the rear end connected to the front end forming a circular arrangement.
The details of the members of the class are given below:
Class name: CirQueue
Data members/instance variables:
Q[]: array to hold integer values
cap: maximum capacity of the circular queue
front: to point the index of the front
rear: to point the index of the rear
Methods/Member functions:
CirQueue(int n): constructor to initialize cap = n, front = 0 and rear = 0
void push(int v): to add integers from the rear index if possible else display the message “QUEUE IS FULL”
int remove(): to remove and return the integer from front if any, else return -999
void print(): to display the elements of the circular queue in the order of front to rear
Algorithm:
Step 1: Start the program.
Step 2: Declare class CirQueue.
Step 3: Declare data members: int Q[] to store queue elements. int cap for queue capacity. int front,
rear for index management
Step 4: Define constructor CirQueue(int n) to initialize: cap = n, Q = new int[cap], front = 0, rear =
0.
Step 5: Define method push(int v):If cap > 0, insert element v at rear.
Update rear = (rear + 1) % [Link]. Decrease cap by 1. Else, display “QUEUE IS FULL”.
Step 6: Define method remove(): If cap == [Link], return -999 (queue empty). Else, remove
element from front.
Update front = (front + 1) % [Link]. Increase cap by 1. If front == rear, reset front = rear = 0 and
cap = [Link].
Step 7: Define method print(): If cap == [Link], display “QUEUE IS EMPTY”. Else, print all
elements from front to rear in circular order.
Step 8: In main() Accept size of the queue. Use a menu-driven loop for push, pop, and print
operations.
Step 9: End of the algorithm.
Code:
import [Link];
class CirQueue {
int Q[];
int cap;
int front;
int rear;
public CirQueue(int n) {
cap = n;
Q = new int[cap];
front = 0;
rear = 0;
}

Page | 95
public void push(int v) {
if (cap > 0) {
Q[rear] = v;
rear = (rear + 1) % [Link];
cap--;
} else {
[Link]("QUEUE IS FULL");
}
}
public int remove() {
if (cap == [Link])
return -999;
int temp = Q[front];
front = (front + 1) % [Link];
cap++;
if (front == rear) {
front = 0;
rear = 0;
cap = [Link];
}
return temp;
}
public void print() {
if (cap == [Link])
[Link]("QUEUE IS EMPTY");
else {
int index = front;
for (int i = 1; i <= [Link] - cap; i++) {
[Link](Q[index] + " ");
index = (index + 1) % [Link];
}
[Link]();
}
}
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("CIRCULAR QUEUE CAPACITY: ");
int size = [Link]([Link]());
CirQueue obj = new CirQueue(size);
while (true) {
[Link]("1. PUSH");
[Link]("2. POP");
[Link]("3. PRINT");
[Link]("ENTER YOUR CHOICE: ");
int choice = [Link]([Link]());
switch (choice) {

Page | 96
case 1:
[Link]("ELEMENT TO BE PUSHED: ");
int elem = [Link]([Link]());
[Link](elem);
break;
case 2:
elem = [Link]();
if (elem == -999)
[Link]("QUEUE IS EMPTY");
else
[Link](elem + " REMOVED");
break;
case 3:
[Link]();
break;
default:
[Link]("BYE");
return;
}
}
}
}
Output:

Page | 97
Program 05: Linear Queue
Queue is an entity which can hold a maximum of 100 integers. The queue enables the user to add integers
from the rear and remove integers from the front.
Define a class Queue with the following details:
Class name: Queue
Data members/instance variables:
Que[]: array to hold the integer elements
size: stores the size of the array
front: to point the index of the front
rear: to point the index of the rear
Member functions:
Queue(int mm): constructor to initialize the data size = mm, front = 0, rear = 0
void addele(int v): to add integer from the rear if possible else display the message “Overflow”
int delete(): returns elements from front if present, otherwise displays the message “Underflow” and returns -
9999
void display(): displays the array elements
Algorithm:
Step 1: Start the program.
Step 2: Declare class Queue.
Step 3: Declare data members: int que[] → array to store elements int size → maximum capacity int
front, rear → to track the front and rear positions
Step 4: Define constructor Queue(int m): Initialize size = m; Create array que = new int[size]; Set
front = 0, rear = 0
Step 5: Define method addele(int v): If rear == size, display “Overflow”, Else insert element v at
que[rear] and increment rear
Step 6: Define method delele(): If rear == 0, display “Underflow” and return -9999, Else remove
element from front, increment front; If front >= rear, reset both front and rear to 0
Step 7: Define method display(): If rear == 0, display “QUEUE EMPTY”, Else display elements
from front to rear - 1
Step 8: In main(): Accept queue size; Create an object of class Queue; Use menu-driven options to
push, pop, and display queue elements
Step 9: End of the algorithm.
Code:
import [Link];
class Queue {
int que[];
int size;
int front;
int rear;
public Queue(int m) {
size = m;
que = new int[size];
front = 0;
rear = 0;
}
public void addele(int v) {

Page | 98
if (rear == size)
[Link]("Overflow");
else {
que[rear++] = v;
[Link](v + " PUSHED");
}
}
public int delele() {
if (rear == 0) {
[Link]("Underflow");
return -9999;
}
int v = que[front++];
if (front >= rear) {
front = 0;
rear = 0;
}
return v;
}
public void display() {
if (rear == 0)
[Link]("QUEUE EMPTY");
else {
for (int i = front; i < rear; i++)
[Link](que[i] + " ");
[Link]();
}
}
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Queue size: ");
int max = [Link]([Link]());
if (max > 100)
max = 100;
Queue obj = new Queue(max);
while (true) {
[Link]("1. PUSH ELEMENT");
[Link]("2. POP ELEMENT");
[Link]("3. DISPLAY ELEMENTS");
[Link]("ENTER YOUR CHOICE: ");
int choice = [Link]([Link]());
switch (choice) {
case 1:
[Link]("Element to be pushed: ");
int v = [Link]([Link]());
[Link](v);

Page | 99
break;
case 2:
v = [Link]();
if (v != -9999)
[Link](v + " POPPED");
break;
case 3:
[Link]();
break;
default:
[Link]("Bye!");
return;
}
}
}
}
Output:

Page | 100
Page | 101
Index

Sl. No. Title Page


Function Passing Objects
1. Time Adder ISC 2017 103
2. Slope ISC 2010 105
3. Point ISC 2010 107
4. Sports 109
5. Combine Matrix 112
6. Matrix Subtraction 115
7. Matrix Addition 118
8. Matrix Multiplication 121
9. MatRev - 2019 124
10. Shift Matrix 127
11. Point Distance Calculation 130
12. Password Check 132
13. Mini Banking System 135

Page | 102
Program 01: Time Adder 2017
A class Adder has been defined to add any two accepted time.
Example:
Time A = 6 hours 35 minutes
Time B = 7 hours 45 minutes
Their sum = 14 hours 20 minutes (where 60 minutes = 1 hour)
The details of the members of the class are given below:
Class name: Adder
Data member/instance variable:
a[]: integer array to hold two elements (hours and minutes)
Member functions/methods:
Adder(): constructor to assign 0 to the array elements
void readtime(): to enter the elements of the array
void addtime(Adder X, Adder Y): adds the time of the two parameterized objects X and Y and stores the sum
in the current calling object
void disptime(): displays the array elements with an appropriate message (i.e. hours = and minutes = )
Specify the class Adder giving details of the constructor(), void readtime(), void addtime(Adder, Adder) and
void disptime(). Define the main() function to create objects and call the functions accordingly to enable the
task.
Algorithm:
Step 1 : Start of algorithm
Step 2 : Create class Adder with an integer array a[2] to store hours and minutes
Step 3 : In constructor Adder(), initialize a[0] = 0 and a[1] = 0
Step 4 : Define function readtime()
(a) Prompt user to enter hours and minutes
(b) Input values and store in a[0] and a[1]
(c) Display entered time
Step 5 : Define function addtime(Adder X, Adder Y)
(a) Add minutes from both objects → total = X.a[1] + Y.a[1]
(b) Compute resultant minutes as a[1] = total % 60
(c) Compute resultant hours as a[0] = X.a[0] + Y.a[0] + (total / 60)
Step 6 : Define function displaytime()
(a) Display total hours and minutes stored in array a[]
Step 7 : In main() method
(a) Create three objects: time1, time2, and timeres of class Adder
(b) Call [Link]() to input first time
(c) Call [Link]() to input second time
(d) Call [Link](time1, time2) to add the two times
(e) Call [Link]() to display the resultant time
Step 8 : End of algorithm
Code:
import [Link];
class Adder{
Scanner sc = new Scanner([Link]);
int a[] = new int[2];
Adder(){

Page | 103
a[0] = 0;
a[1] = 0;
}
void readtime(){
[Link]("Enter hours and minutes: ");
a[0] = [Link]();
a[1] = [Link]();
[Link](a[0]+" hours "+a[1]+" minutes");
[Link]();
}
void addtime(Adder X, Adder Y){
a[1] = (X.a[1]+Y.a[1])%60;
a[0] = X.a[0]+Y.a[0] + (X.a[1]+Y.a[1])/60;
}
void displaytime(){
[Link]("The total time is: ");
[Link](a[0]+" hours "+a[1]+" minutes");
}
public static void main(){
Adder time1 = new Adder();
Adder time2 = new Adder();
Adder timeres = new Adder();
[Link]();
[Link]();
[Link](time1, time2);
[Link]();
}
}
Output:

Page | 104
Program 02: Slope
M = (y2 - y1)/(x2 - x1)
Class: Slope
Data Memebers:
double x, y: to store the coordinates
double m: to store the slope
Mmeber Methods:
Slope() : default constructor
Accept() : to input the coordiantes
void calculate(Slope A, Slope B): to calculate slope
void display() : To display the slope
Algorithm:
Step 1 : Start of algorithm
Step 2 : Create class Slope with data members x, y, and m as double
Step 3 : In constructor Slope(), initialize x = 0.0, y = 0.0, and m = 0.0
Step 4 : Define function accept()
(a) Prompt user to enter values of x and y
(b) Input and store values in x and y
Step 5 : Define function calculate(Slope A, Slope B)
(a) Create a new object res of class Slope
(b) Compute slope using formula m = (B.y - A.y) / (B.x - A.x)
(c) Store the result in res.m
(d) Return res
Step 6 : Define function display(double v)
(a) Print the value of slope v
Step 7 : In main() method
(a) Create three objects: val1, val2, and val of class Slope
(b) Call [Link]() and [Link]() to input coordinates
(c) Call [Link](val1, val2) and store result in res
(d) Call [Link](res.m) to display the calculated slope
Step 8 : End of algorithm
Code:
import [Link];
class Slope{
Scanner sc = new Scanner([Link]);
double x, y, m;
Slope(){
x = 0.0D;
y = 0.0D;
m = 0.0D;
}
void accept(){
[Link]("Enter the values of x and y: ");
x = [Link]();
y = [Link]();
}

Page | 105
Slope calculate(Slope A, Slope B){
Slope res = new Slope();
res.m = (B.y - A.y)/(B.x - A.x);;
return res;
}
void display(double v){
[Link]("The slope is "+v);
}
public static void main(){
Slope val1 = new Slope();
Slope val2 = new Slope();
Slope val = new Slope();
[Link]();
[Link]();
Slope res = [Link](val1, val2);
[Link](res.m);
}
}
Output:

Page | 106
Program 03: Midpoint ISC 2010
[ISC 2010]
the coordinate of a point on a two dimensional plane can be represented by P(x,y);
an 'x' co-ordnate and a 'y' co-ordinate
Co-ordinates of the midpoint between the points (2,3), (4,7) can be calculated as: (2+4)/2, (3+7)/2
=(3,5)
Class Name: Point
Datamemebers: x, y: to store x, y co-oridnates
Member functions:
Point(): constructor to initialise x = 0, y = 0;
void readpoint(): to input the coodinates x and y
void displaypoint(): to print x, y using suitable headings
Point midpoint(Point A, Point B): to calculate the midpoint betwen the two given points p1 ans p2 and
returns them.
Algorithm:
Step 1: Start the program.
Step 2: Declare a class Point with data members x and y of type double.
Step 3: Define a default constructor to initialize x = 0 and y = 0.
Step 4: Define readpoint() to input the values of x and y from the user.
Step 5: Define displaypoint() to display the coordinates of the point as (x, y).
Step 6: Define midpoint(Point A, Point B) which:
(a) Creates a new object res of class Point.
(b) Calculates res.x = (A.x + B.x) / 2.
(c) Calculates res.y = (A.y + B.y) / 2.
(d) Returns the object res.
Step 7: In the main() method:
(a) Create objects A and B of class Point.
(b) Input and display the coordinates of both points.
(c) Call midpoint(A, B) to find the midpoint.
(d) Display the midpoint coordinates.
Step 8: Stop the program.
Code:
public class Point
{
double x, y;
Point(){x = y = 0;}
void readpoint(){Scanner sc = new Scanner([Link]);
[Link]("Enter the x co-ordinate:");
x = [Link]();
[Link]("Enter the y co-ordinate:");
y = [Link]();
}
void displaypoint(){
[Link]("(" + x + "," + y + ")");
}
Point midpoint(Point A, Point B){

Page | 107
Point res = new Point();
res.x = (A.x + B.x)/2;
res.y = (A.y + B.y)/2;
return res;
}
public static void main(){
Point A = new Point();
[Link]();
[Link]("Co-ordinates of point A:");
[Link]();
Point B = new Point();
[Link]();
[Link]("Co-ordinates of point B:");
[Link]();
Point ob = new Point().midpoint(A, B);
[Link]("Co-ordinates of midpoint: (" + ob.x + "," + ob.y + ")");
}
}
Output:

Page | 108
Program 04: Sports Academy
[ISC 2010]
the coordinate of a point on a two dimensional plane can be represented by P(x,y);
an 'x' co-ordnate and a 'y' co-ordinate
Co-ordinates of the midpoint between the points (2,3), (4,7) can be calculated as: (2+4)/2, (3+7)/2
=(3,5)
Class Name: Point
Datamemebers: x, y: to store x, y co-oridnates
Member functions:
Point(): constructor to initialise x = 0, y = 0;
void readpoint(): to input the coodinates x and y
void displaypoint(): to print x, y using suitable headings
Point midpoint(Point A, Point B): to calculate the midpoint betwen the two given points p1 ans p2 and
returns them.
Algorithm:
Step 1: Start the program.
Step 2: Define a class Sports with data members height[], name, and n.
Step 3: In the default constructor, initialize height with a maximum size of 15, n = 0, and name =
"".
Step 4: Define the parameterized constructor Sports(int n, String name) to assign n and name.
Step 5: Define void fillHeight() to input the heights of all players one by one using a loop.
Step 6: Define double averageHeight() to calculate the average of all the values in height[] as
average = (sum of all heights) / n.
Step 7: Define String compare(Sports s1, Sports s2) to:
(a) Compute the average height of s1 and s2.
(b) Compare both averages.
(c) Return a message stating which team has the higher average height, or if both are equal.
Step 8: Define void display(String msg) to print the message.
Step 9: In the main() method:
(a) Input the number of players.
(b) Create two objects s1 and s2 for the two teams.
(c) Input their heights using fillHeight().
(d) Use an object to call compare(s1, s2) and store the message.
(e) Display the message using display(msg).
Step 10: Stop the program.
Code:
import [Link];
public class Sports {
double height[];
String name;
int n;
Sports() {
height = new double[15];
name = "";
n = 0;
}

Page | 109
Sports(int n, String name) {
this();
this.n = n;
[Link] = name;
}
void fillHeight() {
Scanner sc = new Scanner([Link]);
[Link]("Enter the height of " + n + " players for team " + name + ":");
for (int i = 0; i < n; i++) {
[Link]("Height of player " + (i + 1) + ": ");
height[i] = [Link]();
}
}
double averageHeight() {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += height[i];
}
return sum / n;
}
String compare(Sports s1, Sports s2) {
double avg1 = [Link]();
double avg2 = [Link]();
if (avg1 == avg2)
return "Both teams have the same average height";
else if (avg1 > avg2)
return [Link] + " has a higher average height.";
else
return [Link] + " has a higher average height.";
}
void display(String msg) {
[Link](msg);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter total number of players (max 15): ");
int n = [Link]();

if (n > 15 || n <= 0) {
[Link]("INVALID INPUT");
return;
}
Sports ob = new Sports();
Sports s1 = new Sports(n, "Bharat");
Sports s2 = new Sports(n, "Kilo");
[Link]("Team 1: " + [Link]);

Page | 110
[Link]();
[Link]("Team 2: " + [Link]);
[Link]();
String result = [Link](s1, s2);
[Link](result);
}
}
Output:

Page | 111
Program 05: Combine Matrix
A class Combine contains an array of integers which combines two arrays into a single array including the
duplicate elements, if any, and sorts the combined array. Some of the members of the class are given below:
Class name: Combine
Data members/instance variables:
com[]: integer array
size: size of the array
Member functions/methods:
Combine(int num): parameterized constructor to assign size = num
void inputArray(): to accept array elements
void sort(): sorts the elements of combined array in ascending order using the selection sort technique
void mix(Combine a, Combine b): combines the parameterized object arrays and stores the result in the
current object array along with duplicate elements, if any
void display(): displays the array elements
Algorithm:
Step 1: Start the program.
Step 2: Define a class Combine with data members:
com[] – integer array to store elements.
size – to store the size of the array.
Step 3: Define the constructor Combine(int num) to assign size = num and initialize com with the
given size.
Step 4: Define the method void inputArray(). Accept elements of the array from the user and store
them in com[].
Step 5: Define the method void sort() to sort the array elements in ascending order using Selection
Sort technique: Repeat for each element of the array except the last: Assume the current element as
the smallest. Compare it with all subsequent elements. If a smaller element is found, swap the two
elements.
Step 6: Define the method void mix(Combine a, Combine b) Copy all elements of array a into the
current object’s array com[]. Then copy all elements of array b into the same array after the
elements of a. This combines both arrays (including duplicates).
Step 7: Define the method void display(). Display all elements of the current object’s array com[].
Step 8: In the main() method: Input the sizes of two arrays.
Create three objects: x for the first array, y for the second array, z for the combined array of size s1
+ s2. Input elements of both arrays using inputArray(). Call [Link](x, y) to combine both arrays.
Call [Link]() to arrange all elements in ascending order. Call [Link]() to print the combined sorted
array.
Step 9: Stop the program.
Code:
import [Link];
class Combine{
int com[];
int size;
public Combine(int num){
size = num;
com = new int[size];
}

Page | 112
public void inputArray(){
Scanner in = new Scanner([Link]);
for(int i = 0; i < size; i++)
com[i] = [Link]([Link]());
}
public void sort(){
for(int i = 0; i < size - 1; i++){
int small = com[i];
int pos = i;
for(int j = i + 1; j < size; j++){
if(small > com[j]){
small = com[j];
pos = j;
}
}
int temp = com[i];
com[i] = com[pos];
com[pos] = temp;
}
}
public void mix(Combine a, Combine b){
int index = 0;
for(int i = 0; i < [Link]; i++)
[Link][index++] = [Link][i];
for(int i = 0; i < [Link]; i++)
[Link][index++] = [Link][i];
}
public void display(){
for(int i = 0; i < size; i++)
[Link](com[i] + " ");
[Link]();
}
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Size of array 1: ");
int s1 = [Link]([Link]());
[Link]("Size of array 2: ");
int s2 = [Link]([Link]());
Combine x = new Combine(s1);
Combine y = new Combine(s2);
Combine z = new Combine(s1 + s2);
[Link]("Enter array 1 elements:");
[Link]();
[Link]("Enter array 2 elements:");
[Link]();
[Link](x, y);

Page | 113
[Link]();
[Link]("Combined and sorted list:");
[Link]();
}
}
Output:

Page | 114
Program 06: Matrix Subtraction - 2013
A class Matrix continas a 2D array of order n * n and the maximum valye of n = 5;
Class nmae: Matrix
Data memebers:
arr[][] : to store the matrix;
m : to store the numebr of rows
n : to store the number of columns
Member Function
Matrix(int mm, int nn) : paramterised constructor for m =mm; n = nn;
void fillArray() : to get the elements of the matrix
Matrix subMat(Matrix A, Matrix B) : is to subtract Matrix A from matrix B
void display() : print the resultant matrix, A and B.
Algorithm:
Step 1: Start the program.
Step 2: Input the number of rows m and columns n of the matrices.
Step 3: Create two matrices A and B of order m × n.
Step 4: Input the elements of matrix A using the fillArray() method.
Step 5: Input the elements of matrix B using the fillArray() method.
Step 6: Display both matrices A and B using the display() method.
Step 7: Call the method subMat(A, B) to perform subtraction A - B.
Step 8: Store the resultant matrix in another matrix object res.
Step 9: Display the resultant matrix using display().
Step 10: Stop the program.
Code:
import [Link].*;
public class Matrix
{
static Scanner sc = new Scanner([Link]);
int arr[][], m, n;
Matrix(int mm, int nn)
{
m = mm; n =nn;
arr = new int[m][n];
}
void fillArray()
{
[Link]("Enter the array elements one by one: ");
for(int i = 0; i < m; i++)
{
[Link]("Elements in row number: " + (i + 1));
for(int j = 0; j < n; j++)
arr[i][j] = [Link]();
}
}
Matrix subMat(Matrix A, Matrix B)
{

Page | 115
Matrix smat = new Matrix(m,n);
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
[Link][i][j] = [Link][i][j] - [Link][i][j];
return smat;// we return mat because resultant matrix must be returned
}
void display()
{
[Link]("The array elements are: ");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
[Link](arr[i][j] + "\t");
[Link]();
}
}
public static void main()
{
[Link]("Please enter the size of the array A: ");
[Link]("Please enter the row size of the array A: ");
int mm = [Link]();
[Link]("Please enter the column size of the array A: ");
int nn = [Link]();
Matrix A = new Matrix(mm, nn);
[Link]("Elements in A: ");
[Link]();
[Link]("Entered Matrix A: ");
[Link]();
Matrix B = new Matrix(mm, nn);
[Link]("Elements in B: ");
[Link]();
[Link]("Entered Matrix B: ");
[Link]();
[Link]("The resultant matrix is: ");
Matrix res = new Matrix(mm, nn).subMat(A, B);
[Link]();
}
}
Output:

Page | 116
Program 07: Matrix Addition

Page | 117
A class Matrix contains a two-dimensional integer array of order [m × n]. The maximum value possible for
both ‘m’ and ‘n’ is 25.
Design a class Matrix to find the sum of two matrices. The details of the members of the class are given
below:
Class name: Matrix
Data members/instance variables:
 arr[][]: stores the matrix elements
 m: integer to store the number of rows
 n: integer to store the number of columns
Member functions:
1. Matrix(int mm, int nn): to initialize the size of the matrix m = mm and n = nn
2. void fillArray(): to enter the elements of the matrix
3. Matrix addMat(Matrix a): to add the current object matrix to the parameterized matrix and return the
resulting object
4. void display(): to display the matrix elements
Also define the main() function to create objects and call the methods accordingly to enable the task.
Algorithm:
Step 1: Start the program.
Step 2: Input the number of rows m and columns n.
Step 3: Create two matrix objects A and B of order m × n.
Step 4: Input all elements for matrix A using fillArray().
Step 5: Input all elements for matrix B using fillArray().
Step 6: Display both matrices using display().
Step 7: Call addMat() to perform element-wise addition and store the result.
Step 8: Display the resultant matrix.
Step 9: Stop the program.
Code:
import [Link];
class MatrixAdd {
int arr[][];
int m, n;
MatrixAdd(int mm, int nn) {
if(mm > 25)
m = 25;
else
m = mm;
if(nn > 25)
n = 25;
else
n = nn;
arr = new int[m][n];
}
void fillArray() {
Scanner sc = new Scanner([Link]);
[Link]("Enter the elements of the matrix:");
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {

Page | 118
arr[i][j] = [Link]();
}
}
}
MatrixAdd addMat(MatrixAdd A) {
MatrixAdd sum = new MatrixAdd(m, n);
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
[Link][i][j] = [Link][i][j] + [Link][i][j];
}
}
return sum;
}
void display() {
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
[Link](arr[i][j] + "\t");
}
[Link]();
}
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of rows: ");
int r = [Link]();
[Link]("Enter number of columns: ");
int c = [Link]();
MatrixAdd A = new MatrixAdd(r, c);
[Link]("Enter Matrix A elements:");
[Link]();
MatrixAdd B = new MatrixAdd(r, c);
[Link]("Enter Matrix B elements:");
[Link]();
[Link]("Matrix A:");
[Link]();
[Link]("Matrix B:");
[Link]();
MatrixAdd res = [Link](B);
[Link]("Matrix A + B:");
[Link]();
}
}
Output:

Page | 119
Page | 120
Program 08: Matrix Product
A class Matrix contains a two-dimensional integer array of order [m × n]. The maximum value possible for
both ‘m’ and ‘n’ is 25.
Design a class Matrix to find the product of two matrices. The details of the members of the class are given
below:
Class name: Matrix
Data members/instance variables:
 arr[][]: stores the matrix elements
 m: integer to store the number of rows
 n: integer to store the number of columns
Member functions:
1. Matrix(int mm, int nn): to initialize the size of the matrix m = mm and n = nn
2. void fillArray(): to enter the elements of the matrix
3. Matrix product(Matrix b): to multiply the current object matrix with the parameterized matrix and
return the resulting object
4. void display(): to display the matrix elements
Also define the main() function to create objects and call the methods accordingly to enable the task.
Algorithm:
Step 1: Start the program.
Step 2: Input dimensions of matrices such that if matrix A is of order m × n, then matrix B must be
of order n × p.
Step 3: Create matrices A, B, and C where C will store the result of order m × p.
Step 4: Input all elements of matrices A and B using fillArray().
Step 5: For each element C[i][j], calculate
C[i][j] = Σ (A[i][k] * B[k][j]) for all valid k.
Step 6: Display matrices A, B, and C using display().
Step 7: Stop the program.
Code:
import [Link];
class MatrixMultiply {
int arr[][];
int m, n;
MatrixMultiply(int mm, int nn) {
if(mm > 25)
m = 25;
else
m = mm;
if(nn > 25)
n = 25;
else
n = nn;
arr = new int[m][n];
}
void fillArray() {
Scanner sc = new Scanner([Link]);
[Link]("Enter the elements of the matrix:");

Page | 121
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
arr[i][j] = [Link]();
}
}
}
MatrixMultiply product(MatrixMultiply B) {
if(this.n != B.m) {
[Link]("Matrix multiplication not possible!");
return new MatrixMultiply(0, 0);
}
MatrixMultiply prod = new MatrixMultiply(this.m, B.n);
for(int i = 0; i < this.m; i++) {
for(int j = 0; j < B.n; j++) {
[Link][i][j] = 0;
for(int k = 0; k < this.n; k++) {
[Link][i][j] += [Link][i][k] * [Link][k][j];
}
}
}
return prod;
}
void display() {
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
[Link](arr[i][j] + "\t");
}
[Link]();
}
}
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of rows for Matrix A: ");
int r1 = [Link]();
[Link]("Enter number of columns for Matrix A: ");
int c1 = [Link]();
MatrixMultiply A = new MatrixMultiply(r1, c1);
[Link]("Enter Matrix A elements:");
[Link]();
[Link]("Enter number of rows for Matrix B: ");
int r2 = [Link]();
[Link]("Enter number of columns for Matrix B: ");
int c2 = [Link]();
MatrixMultiply B = new MatrixMultiply(r2, c2);
[Link]("Enter Matrix B elements:");
[Link]();

Page | 122
if(c1 != r2) {
[Link]("Matrix multiplication not possible!");
return;
}
[Link]("Matrix A:");
[Link]();
[Link]("Matrix B:");
[Link]();
MatrixMultiply res = [Link](B);
[Link]("Matrix A × B:");
[Link]();
}
}
Output:

Page | 123
Program 09: MatRev
Class name: MatRev
Data members/instance variables:
arr[][]: to store integer elements
m: to store the number of rows
n: to store the number of columns
Member functions/methods:
MatRev(int mm, int nn): parameterized constructor to initialize the data members m = mm and n = nn
void fillarray(): to enter elements in the array
int reverse(int x): returns the reverse of the number x
void revMat(MatRev P): reverse each element of the array of the parameterized object and stores it in the
array of the current object
void show(): displays the array elements in matrix form
Algorithm:
Step 01: Start
Step 02: Input the number of rows m
Step 03: Input the number of columns n
Step 04: Create an object obj1 of class MatRev with size m × n
Step 05: Call [Link](): This reads all matrix elements from the user and stores them in
[Link]
Step 06: Create another object obj2 of class MatRev with size m × n
Step 07: Call [Link](obj1) For each element at position (i, j) in obj1
a. Call the function reverse(x)
b. Store the reversed value in [Link][i][j]
Step 08: Display the original matrix by calling [Link]()
Step 09: Display the reversed-digit matrix by calling [Link]()
Step 10: Stop
Code:
import [Link];
class MatRev{
int ar[][];
int m;
int n;
public MatRev(int mm, int nn){
m = mm;
n = nn;
ar = new int[m][n];
}
public void fillarray(){
Scanner in = new Scanner([Link]);
[Link]("Enter matrix elements: ");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
ar[i][j] = [Link]([Link]());
}
}

Page | 124
}
public int reverse(int x){
int rev = 0;
while(x != 0){
rev = rev * 10 + x % 10;
x /= 10;
}
return rev;
}
public void revMat(MatRev P){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
[Link][i][j] = reverse([Link][i][j]);
}
}
}
public void show(){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
[Link](ar[i][j] + "\t");
}
[Link]();
}
}
public static void main(String args[]){
Scanner in = new Scanner([Link]);
[Link]("Number of rows: ");
int rows = [Link]([Link]());
[Link]("Number of columns: ");
int cols = [Link]([Link]());
MatRev obj1 = new MatRev(rows, cols);
[Link]();
MatRev obj2 = new MatRev(rows, cols);
[Link](obj1);
[Link]("Original Matrix:");
[Link]();
[Link]("Matrix with reversed elements:");
[Link]();
}
}
Output:

Page | 125
Page | 126
Program 10: Shift
Class name: Shift
Data members/instance variables:
mat[][]: stores the array elements
m: integer to store the number of rows
n: integer to store the number of columns
Member functions/methods:
Shift(int mm, int nn): parameterized constructor to initialize the data members m = mm and n = nn
void input(): enters the elements of the array
void cyclic(Shift p): enables the matrix of the object (p) to shift each row upwards in a cyclic manner and
store the resultant matrix in the current object
void display(): displays the matrix elements
Algorithm:
Step 1: Start the algorithm.
Step 2: Declare the variables
m = number of rows,
n = number of columns,
and a 2-D array mat[m][n].
Step 3: Input the values of m and n.
If either value is more than 5, set it to 5.
Step 4: Create an object of the class Shift with m and n.
Step 5: Input all the matrix elements row-wise and store them in mat.
Step 6: Create another object of the class Shift with the same size.
This object will store the shifted matrix.
Step 7: To shift the matrix cyclically upward: For every row i and column j: If i == 0, move the first
row to the last row → newMat[m - 1][j] = oldMat[0][j]
Otherwise, shift the row up by one → newMat[i - 1][j] = oldMat[i][j]
Step 8: Store the shifted values in the second object's matrix.
Step 9: Display the original matrix.
Step 10: Display the new (shifted) matrix.
Step 11: End the algorithm.
Code:
import [Link];
class Shift{
int mat[][];
int m;
int n;
public Shift(int mm, int nn){
m = mm;
n = nn;
if(m > 5)
m = 5;
if(n > 5)
n = 5;
mat = new int[m][n];
}

Page | 127
public void input(){
Scanner in = new Scanner([Link]);
[Link]("Enter matrix elements:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
mat[i][j] = [Link]([Link]());
}
}
}
public void cyclic(Shift p){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0)
[Link][m - 1][j] = [Link][i][j];
else
[Link][i - 1][j] = [Link][i][j];
}
}
}
public void display(){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++)
[Link](mat[i][j] + "\t");
[Link]();
}
}
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Number of rows: ");
int rows = [Link]([Link]());
[Link]("Number of columns: ");
int cols = [Link]([Link]());
Shift x = new Shift(rows, cols);
[Link]();
[Link]("Original Matrix");
[Link]();
Shift y = new Shift(rows, cols);
[Link](x);
[Link]("New Matrix");
[Link]();
}
}
Output:

Page | 128
Page | 129
Program 11: Point Distance
Create a Java program with a class named PointDistance that stores the coordinates of a point using two
integer data members x and y.
The class should include:
1. A parameterized constructor PointDistance(int a, int b) to initialise the coordinates.
2. A method double distance(PointDistance p) that calculates and returns the distance between the
current point and another point p using the distance formula.
Accept the values of two points (x1, y1, x2, y2) from the user. Create two objects of PointDistance, compute
the distance between them, and display the result.
Algorithm:
Step 1: Start the algorithm.
Step 2: Declare two integer variables x1, y1 to store the coordinates of the first point.
Step 3: Declare two integer variables x2, y2 to store the coordinates of the second point.
Step 4: Input the values of x1 and y1 from the user.
Step 5: Create an object P1 of class PointDistance using the constructor and pass x1 and y1.
Step 6: Input the values of x2 and y2 from the user.
Step 7: Create another object P2 of class PointDistance using the constructor and pass x2 and y2.
Step 8: Call the method distance() using [Link](P2) to calculate the distance between the two
points.
Step 9: Store the returned value in a variable d.
Step 10: Display the distance d.
Step 11: End the algorithm.
Code:
import [Link];
public class PointDistance { int x; int y;
PointDistance(int a, int b)
{
x = a;
y = b;
}
double distance(PointDistance p)
{
int dx = p.x - this.x;
int dy = p.y - this.y;
return [Link](dx * dx + dy * dy);
}
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);

[Link]("Enter x1: ");


int x1 = [Link]();
[Link]("Enter y1: ");
int y1 = [Link]();
PointDistance P1 = new PointDistance(x1, y1);
[Link]("Enter x2: ");
Page | 130
int x2 = [Link]();
[Link]("Enter y2: ");
int y2 = [Link]();
PointDistance P2 = new PointDistance(x2, y2);
double d = [Link](P2);
[Link](d);
}
}
Output:

Page | 131
Program 12: Password
Define a class Password that stores a password as a string.
The class should include:
1. Parameterized Constructor
Password(String p)
Used to initialize the password.
2. Method
String checkStrength(Password obj)
This method accepts a Password object and checks the strength of the password stored inside it.
Password Strength Rules
A password is:
Strong (if ALL conditions are satisfied):
 Minimum 8 characters
 At least one uppercase letter
 At least one lowercase letter
 At least one digit
 At least one special character
Less Strong
 If three or four of the above conditions are satisfied.
Weak
 If two or fewer conditions are satisfied.
Algorithm:
Step 1: Start the algorithm.
Step 2: Display clear instructions for a Strong Password:
Minimum 8 characters, at least one uppercase letter, one lowercase letter, one digit, and one special
character.
Step 3: Set a variable again = "yes" to allow repeated attempts.
Step 4: Repeat the following steps while again is equal to "yes":
Step 4.1: Ask the user to enter a password and store it in variable p.
Step 4.2: Create an object P1 of class Password using p.
Step 4.3: Call the method checkStrength(P1) and store the result in strength.
Step 4.4: If strength is "Strong", then:
a. Display the password
b. Display “Strong Password”
c. End the program immediately
Step 4.5: Otherwise (if the password is Less Strong or Weak):
a. Display “Password Strength: ” followed by the strength category
b. Ask the user: “Do you want to try again? (yes/no)”
c. Store their response in again
Step 5: End the algorithm.
Code:
import [Link];

class Password {
String pass;

Password(String p) {
Page | 132
pass = p;
}

String checkStrength(Password obj) {


String s = [Link];
boolean upper = false;
boolean lower = false;
boolean digit = false;
boolean special = false;
boolean length = [Link]() >= 8;

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if ([Link](ch))
upper = true;
else if ([Link](ch))
lower = true;
else if ([Link](ch))
digit = true;
else
special = true;
}

int count = 0;
if (length) count++;
if (upper) count++;
if (lower) count++;
if (digit) count++;
if (special) count++;

if (count == 5)
return "Strong";
else if (count >= 3)
return "Less Strong";
else
return "Weak";
}
}

public class PasswordStrengthCheck {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
String again = "yes";

[Link]("Instructions for a Strong Password:");

Page | 133
[Link]("1. Minimum 8 characters");
[Link]("2. At least one uppercase letter");
[Link]("3. At least one lowercase letter");
[Link]("4. At least one digit");
[Link]("5. At least one special character\n");

while ([Link]("yes")) {

[Link]("Enter password: ");


String p = [Link]();

Password P1 = new Password(p);


String strength = [Link](P1);

if ([Link]("Strong")) {
[Link](p);
[Link]("Strong Password");
break;
} else {
[Link]("Password Strength: " + strength);
[Link]("Do you want to try again? (yes/no): ");
again = [Link]();
}
}
}
}
Output:

Page | 134
Program 13: Mini-Banking
Define a class Password that stores a password as a string.
The class should include:
1. Parameterized Constructor
Password(String p)
Used to initialize the password.
2. Method
String checkStrength(Password obj)
This method accepts a Password object and checks the strength of the password stored inside it.
Password Strength Rules
A password is:
Strong (if ALL conditions are satisfied):
 Minimum 8 characters
 At least one uppercase letter
 At least one lowercase letter
 At least one digit
 At least one special character
Less Strong
 If three or four of the above conditions are satisfied.
Weak
 If two or fewer conditions are satisfied.
Algorithm:
Step 1: Start the program.
Step 2: Create an ArrayList to store multiple Account objects.
Step 3: Set nextAccNo = 1 to auto-generate account numbers.
Step 4: Display a menu with 7 options inside a loop.
Create Account
Step 5: If user chooses option 1: Input name and initial balance; Create an Account object; Assign
next account number; Add it to the list; Increase nextAccNo;
Delete Account
Step 6: If option 2 is chosen: Input account number; Search the list; If found, remove the account;
`Otherwise show “Account Not Found”
Deposit Money
Step 7: If option 3 is chosen: Ask for account number and amount; Find the account using
findAccount(); Call deposit(amount)
Withdraw Money
Step 8: If option 4 is chosen: Ask account number and amount; Find the account; Call
withdraw(amount)
Transfer Money
Step 9: If option 5 is chosen: Ask for sender and receiver account numbers; Ask for amount; Find
both accounts; Call [Link](receiver, amt);
Show All Accounts
Step 10: If option 6 is chosen: Loop through the list; Call show() for each account; Exit
Step 11: If option 7 is chosen:
End the program.
Code:
import [Link];
Page | 135
class Password {
String pass;

Password(String p) {
pass = p;
}

String checkStrength(Password obj) {


String s = [Link];
boolean upper = false;
boolean lower = false;
boolean digit = false;
boolean special = false;
boolean length = [Link]() >= 8;

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if ([Link](ch))
upper = true;
else if ([Link](ch))
lower = true;
else if ([Link](ch))
digit = true;
else
special = true;
}

int count = 0;
if (length) count++;
if (upper) count++;
if (lower) count++;
if (digit) count++;
if (special) count++;

if (count == 5)
return "Strong";
else if (count >= 3)
return "Less Strong";
else
return "Weak";
}
}

public class PasswordStrengthCheck {

Page | 136
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
String again = "yes";

[Link]("Instructions for a Strong Password:");


[Link]("1. Minimum 8 characters");
[Link]("2. At least one uppercase letter");
[Link]("3. At least one lowercase letter");
[Link]("4. At least one digit");
[Link]("5. At least one special character\n");

while ([Link]("yes")) {

[Link]("Enter password: ");


String p = [Link]();

Password P1 = new Password(p);


String strength = [Link](P1);

if ([Link]("Strong")) {
[Link](p);
[Link]("Strong Password");
break;
} else {
[Link]("Password Strength: " + strength);
[Link]("Do you want to try again? (yes/no): ");
again = [Link]();
}
}
}
}
Output:

Page | 137
Page | 138
Page | 139
Index

Sl. No. Title Page


Inheritance
1. Student Record 141
2. Stock 144
3. Telephone 147
4. Perimeter 150
5. Plane 153
6. Bank 156
7. Series 160
8. Flight 163
9. Interest 165
10. Emp Sal 167
11. Library 170
12. Circle 172
13. Author 174
14. Shape 176
15. Student 178

Page | 140
Program 01: Student Record
A super class Record has been defined to store the names and ranks of 50 students.
Define a sub-class Rank to find the highest rank along with the name.
The details of both classes are given below:
Class name: Record

Data members / instance variables:


 name[] – to store the names of students
 rnk[] – to store the ranks of students
Member functions:
 Record() – constructor to initialize the data members
 void readValues() – to store the names and ranks
 void display() – to display the names and their ranks
Class name: Rank (inherits from Record)
Data members:
 index – integer to store the index of the topmost rank
Member functions:
 Rank() – constructor to invoke base class constructor and initialize index = 0
 void highest() – finds the index of the highest rank without sorting
 void display() – displays all names, ranks, and the name with the topmost rank
Using the above specifications, write the classes Record and Rank along with the main method.
Algorithm:
Step 1: Start the program.
Step 2: Define the super-class Record with the arrays name[] and rnk[].
Step 3: Inside the constructor of Record, initialize both arrays to store 50 elements.
Step 4: Define the function readValues() to input each student’s name and rank.
Step 5: Define the function display() to print all names with their ranks.
Step 6: Define the sub-class Rank extending Record.
Step 7: In the constructor of Rank, call super() and set index = 0.
Step 8: Define the function highest() to scan through the rnk[] array and find the smallest rank
value.
Step 9: Store the position of the topmost rank in the variable index.
Step 10: Override the display() method in Rank to first print the entire list and then print the student
with the highest rank.
Step 11: In main(), create an object of class Rank.
Step 12: Call readValues(), highest(), and display().
Step 13: Stop the program.
Code:
import [Link];
class Record {
protected String name[];
protected int rnk[];
public Record() {
name = new String[50];
rnk = new int[50];
}

Page | 141
public void readValues() {
Scanner in = new Scanner([Link]);
[Link]("Enter names and ranks of 50 students:");
for (int i = 0; i < 50; i++) {
[Link]("Name " + (i + 1) + ": ");
name[i] = [Link]();
[Link]("Rank: ");
rnk[i] = [Link]([Link]());
}
}
public void display() {
[Link]("\nName and Rank List:");
for (int i = 0; i < 50; i++) {
[Link](name[i] + " - " + rnk[i]);
}
}
}
class Rank extends Record {
int index;
public Rank() {
super();
index = 0;
}
public void highest() {
for (int i = 1; i < 50; i++) {
if (rnk[i] < rnk[index]) {
index = i; // smaller rank number = higher rank
}
}
}
public void display() {
[Link]();
[Link]("\nStudent with the Topmost Rank:");
[Link](name[index] + " - Rank " + rnk[index]);
}
}
public class Student {
public static void main(String[] args) {
Rank obj = new Rank();
[Link]();
[Link]();
[Link]();
}
}
Output:

Page | 142
Page | 143
Program 02: Stock
A super class Stock has been defined to store the details of the stock of a retail store.
Define a subclass Purchase to store the details of items purchased along with the new rate, and update the
existing stock.
Class: Stock
Data Members:
 item: name of the item
 qty: quantity in stock
 rate: unit price of the item
 amt: net value of the item in stock (qty * rate)
Member Functions:
 Stock(...): parameterized constructor to assign values
 void display(): displays stock details
Class: Purchase (inherits Stock)
Data Members:
 pqty: purchased quantity
 prate: unit price during purchase
Member Functions:
 Purchase(...): parameterized constructor (for both base and derived class variables)
 void update():
o Add purchased quantity to stock quantity
o Change rate if purchase rate differs
o Update net value amt = qty * rate
 void display(): display stock before and after update
Write the classes Stock and Purchase using inheritance and implement stock updation.
Algorithm:
Step 1: Start the program
Step 2: Define super-class Stock with data members item, qty, rate, and amt
Step 3: Define parameterized constructor Stock(String, int, double) to initialize item, quantity, rate
and calculate amt = qty × rate
Step 4: Define display() method in Stock to show current stock details
Step 5: Define sub-class Purchase that inherits from Stock
Step 6: Declare additional instance variables pqty (purchased quantity) and prate (purchase rate) in
Purchase
Step 7: Define parameterized constructor in Purchase to initialize all values using super()
Step 8: Define update() method to:
- Add purchased quantity to existing stock (qty += pqty)
- Update rate if new rate is different (if(prate != rate) rate = prate)
- Recalculate total stock value (amt = qty × rate)
Step 9: Override display() in Purchase to:
- Print "BEFORE UPDATION" and show current stock using [Link]()
- Call update()
- Print "AFTER UPDATION" with updated quantity, rate and amount
Step 10: Stop the program
Code:
import [Link];
class Stock {

Page | 144
protected String item;
protected int qty;
protected double rate;
protected double amt;
// Parameterized constructor
public Stock(String i, int q, double r) {
item = i;
qty = q;
rate = r;
amt = qty * rate; // Net value of stock
}
// Display stock details
public void display() {
[Link]("Item name: " + item);
[Link]("Quantity: " + qty);
[Link]("Unit price: " + rate);
[Link]("Stock value: " + amt);
[Link](); // Blank line for better readability
}
}
class Purchase extends Stock {
int pqty; // Purchased quantity
double prate; // Purchased unit price
// Parameterized constructor for Purchase class
public Purchase(String i, int q, double r, int pq, double pr) {
super(i, q, r); // Initialize Stock class members
pqty = pq;
prate = pr;
}
// Update stock with purchased items
public void update() {
qty += pqty; // Add purchased quantity
if (prate != rate) { // If new rate is different
rate = prate; // Update the rate
}
amt = qty * rate; // Recalculate total stock value
}
// Override display() to show before and after update
public void display() {
[Link]("BEFORE UPDATION:");
[Link](); // Show original stock
update(); // Perform update
[Link]("AFTER UPDATION:");
[Link]("Item name: " + item);
[Link]("Quantity: " + qty);
[Link]("Unit price: " + rate);

Page | 145
[Link]("Stock value: " + amt);
}
}
public class MyInheritance{
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Item name: ");
String i = [Link]();
[Link]("Quantity: ");
int q = [Link]([Link]());
[Link]("Rate: ");
double r = [Link]([Link]());
[Link]("New Quantity: ");
int pq = [Link]([Link]());
[Link]("New Rate: ");
double pr = [Link]([Link]());
Purchase obj = new Purchase(i, q, r, pq, pr);
[Link]();
}
}
Output:

Page | 146
Program 03: Telephone
A super class Detail has been defined to store the details of a customer. Define a sub class Bill to compute the
monthly telephone charge of the customer as per the chart given below:
NUMBER OF CALLS RATE
1 – 100 Only rental charge
101 – 200 60 paise per call + rental charge
201 – 300 80 paise per call + rental charge
Above 300 1 rupee per call + rental charge
The details of both the classes are given below:
Class name: Detail
Data members/instance variables:
name: to store the name of the customer
address: to store the address of the customer
telno: to store the phone number of the customer
rent: to store the monthly rental charge
Member functions:
Detail(…): parameterized constructor to assign values to data members
void show(): to display the details of the customer
Class name: Bill
Data members/instance variables:
n: to store the number of calls
amt: to store the amount to be paid by the customer
Member functions:
Bill(…): parameterized constructor to assign values to data members of both classes and to initialize amt = 0.0
void cal(): calculates the monthly telephone charge as per the chart given above
void show(): displays the details of the customer and amount to be paid
Specify the class Detail giving details of the constructor and void show(). Using the concept of inheritance,
specify the class Bill giving details of the constructor, void cal() and void show().
Algorithm:
Step 01: Start.
Step 02: Accept customer details from user: name, address, telephone number, and monthly rental
charge.
Step 03: Accept the number of calls made by the customer.
Step 04: Create a Bill object using the parameterized constructor, passing name, address, telephone
number, rental charge, and number of calls.
Step 05: Initialize amt = 0.0 in the Bill constructor.
For cal() method:
Step 06: Check if number of calls (n) ≤ 100.
Step 07: If yes → amt = rent (only rental charge applies, no additional call charges).
Step 08: Else check if n ≤ 200.
Step 09: If yes → amt = rent + 0.60 × (n − 100) (charge 60 paise per call only for calls beyond 100).
Step 10: Else check if n ≤ 300.
Step 11: If yes → amt = rent + (0.60 × 100) + 0.80 × (n − 200) (charge first 100 extra calls at 60
paise, next calls at 80 paise).
Step 12: Else (n > 300) → amt = rent + (0.60 × 100) + (0.80 × 100) + 1.00 × (n − 300) (charge
progressively: 60 paise for 101-200, 80 paise for 201-300, and 1 rupee for calls above 300).
For show() method:

Page | 147
Step 13: Call [Link]() to display customer name, address, telephone number, and monthly rent
from the Detail class.
Step 14: Display the number of calls made.
Step 15: Display the total amount to be paid (amt) formatted to 2 decimal places.
Step 16: End.
Code:
import [Link].*;
class Detail {
protected String name;
protected String address;
protected String telno; // keep as String to preserve leading zeros and formatting
protected double rent;
public Detail(String name, String address, String telno, double rent) {
[Link] = name;
[Link] = address;
[Link] = telno;
[Link] = rent;
}
public void show() {
[Link]("Customer name : " + name);
[Link]("Address : " + address);
[Link]("Telephone No. : " + telno);
[Link]("Monthly rent : %.2f%n", rent);
}
}

class Bill extends Detail {


protected int n; // number of calls
protected double amt; // total amount to be paid
public Bill(String name, String address, String telno, double rent, int n) {
super(name, address, telno, rent);
this.n = n;
[Link] = 0.0;
}
public void cal() {
if (n <= 100) {
amt = rent;
} else if (n <= 200) {
amt = rent + 0.60 * (n - 100);
} else if (n <= 300) {
amt = rent + (0.60 * 100) + 0.80 * (n - 200);
} else {
amt = rent + (0.60 * 100) + (0.80 * 100) + 1.00 * (n - 300);
}
}
public void show() {

Page | 148
[Link]();
[Link]("Number of calls: " + n);
[Link]("Amount to pay : %.2f%n", amt);
}
}
public class Telephone{
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Customer name: ");
String n = [Link]();
[Link]("Address: ");
String a = [Link]();
[Link]("Telephone number: ");
String t = [Link]();
[Link]("Rent: ");
double r = [Link]([Link]());
[Link]("Number of calls: ");
int num = [Link]([Link]());
Bill obj = new Bill(n, a, t, r, num);
[Link]();
[Link]();
}
}
Output:

Page | 149
Program 04: Perimeter
A super class Perimeter has been defined to calculate the perimeter of a parallelogram. Define a
subclass Area to compute the area of the parallelogram by using the required data members of the super class.
The details are given below:
Class name: Perimeter
Data members/instance variables:
a: to store the length in decimal
b: to store the breadth in decimal
Member functions:
Perimeter(…): parameterized constructor to assign values to data members
double calculate(): calculate and return the perimeter of a parallelogram as 2 × (length + breadth)
void show(): to display the data members along with the perimeter of the parallelogram
Class name: Area
Data members/instance variables:
h: to store the height in decimal
area: to store the area of the parallelogram
Member functions:
Area(…): parameterized constructor to assign values to data members of both the classes
void doArea(): compute the area as (breadth × height)
void show(): display the data members of both classes along with the area and perimeter of the parallelogram.
Specify the class Perimeter giving details of the constructor, double calculate() and void show(). Using
the concept of inheritance, specify the class Area giving details of the constructor, void doArea() and void
show().
The main() function and algorithm need not be written.
Algorithm:
Step 1: Start the program.
Step 2: Define the super-class Perimeter with protected variables a (length) and b (breadth).
Step 3: Define parameterized constructor Perimeter(double x, double y) to initialize a and b.
Step 4: Define method calculate() to return perimeter as 2 * (a + b).
Step 5: Define method show() to display length, breadth, and perimeter.
Step 6: Define the sub-class Area extending Perimeter.
Step 7: In Area, declare instance variables h (height) and area.
Step 8: Define parameterized constructor Area(double x, double y, double z) that calls super(x, y)
and initializes h.
Step 9: Define method doArea() to calculate area as breadth × height (i.e., b * h).
Step 10: Override method show() in Area to first call [Link]() (to print length, breadth,
perimeter), then print height and area.
Step 11: In main(), create a Scanner object.
Step 12: Input length, breadth, and height from the user.
Step 13: Create an object of class Area with the three values.
Step 14: Call doArea() to compute the area.
Step 15: Call show() to display all details including perimeter and area.
Step 16: Stop the program.
Code:
import [Link];
class Perimeter {
protected double a; // length

Page | 150
protected double b; // breadth
// Parameterized constructor
public Perimeter(double x, double y) {
a = x;
b = y;
}
// Calculate and return perimeter
public double calculate() {
return 2 * (a + b);
}
// Display length, breadth and perimeter
public void show() {
[Link]("Length = " + a);
[Link]("Breadth = " + b);
[Link]("Perimeter = " + calculate());
}
}

class Area extends Perimeter {


double h; // height
double area; // area of parallelogram
// Parameterized constructor for Area
public Area(double x, double y, double z) {
super(x, y); // initialize length and breadth in superclass
h = z;
area = 0.0;
}
// Compute area = breadth × height
public void doArea() {
area = b * h;
}
// Override show() to display everything including area
public void show() {
[Link](); // display length, breadth, perimeter
[Link]("Height = " + h);
[Link]("Area = " + area);
}
}
class Parallelogram {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Length: ");
double l = [Link]([Link]());
[Link]("Breadth: ");
double b = [Link]([Link]());
[Link]("Height: ");

Page | 151
double h = [Link]([Link]());
Area obj = new Area(l, b, h);
[Link]();
[Link]();
[Link]();
}
}
Output:

Page | 152
Program 05: Plane
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 super class Plane is defined to represent a line and a sub class Circle to find the length of the radius and the
area of circle by using the required data members of super class.
Some of the members of both the classes are given below:
Class name: Plane
Data members/methods:
x1: to store the x-coordinate of the first end point
y1: to store the y-coordinate of the first end point
Member functions/methods:
Plane(int nx, int ny): parameterized constructor to assign the data members x1 = nx and y1 = ny
void show(): to display the coordinates
Class name: Circle
Data members/instance variables:
x2: to store the x-coordinate of the second end point
y2: to store the y-coordinate of the second end point
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:
sqrt(x * x + y * y) / 2
assuming that x1, x2, y1, y2 are the coordinates of the two ends of the diameter of a circle
void show(): to display both the coordinates along with the length of the radius and the 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 findArea() and void show().
The main() function and algorithm need not be written.
Algorithm:
Step 1: Start the program
Step 2: Define super-class Plane with protected variables x1 and y1
Step 3: Define parameterized constructor Plane(int nx, int ny) to initialize x1 and y1
Step 4: Define show() method in Plane to display coordinates of point p1
Step 5: Define sub-class Circle that extends Plane
Step 6: Declare instance variables x2, y2, radius, and area in Circle
Step 7: Define parameterized constructor Circle(int, int, int, int) using super() to initialize p1 and
assign p2
Step 8: Define findRadius() to calculate distance between (x1,y1) and (x2,y2), then divide by 2 (since
it's diameter)
Step 9: Inside findRadius(), also calculate area = π × radius²
Step 10: Override show() in Circle to display both points, radius, and area
Step 11: Stop the program
Code:
import [Link];
class Plane {
protected int x1;
protected int y1;

Page | 153
// Parameterized constructor for point p1
public Plane(int nx, int ny) {
x1 = nx;
y1 = ny;
}
// Display coordinates of first point
public void show() {
[Link]("p1(" + x1 + ", " + y1 + ")");
}
}
class Circle extends Plane {
int x2;
int y2;
double radius;
double area;
// Parameterized constructor to initialize both points
public Circle(int a1, int b1, int a2, int b2) {
super(a1, b1); // Initialize p1 using super constructor
x2 = a2;
y2 = b2;
radius = 0.0;
area = 0.0;
}
// Calculate radius (half the diameter) and area
public void findRadius() {
// Distance formula: sqrt( (x2-x1)^2 + (y2-y1)^2 )
double distance = [Link]([Link](x2 - x1, 2) + [Link](y2 - y1, 2));
radius = distance / 2.0; // Radius = diameter / 2
area = [Link] * radius * radius; // Area = πr²
}
// Override show() to display complete circle details
public void show() {
[Link](); // Show p1
[Link]("p2(" + x2 + ", " + y2 + ")");
[Link]("Radius: %.2f\n", radius);
[Link]("Area: %.2f\n", area);
}
}
// Driver class as requested
public class CircleDemo {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);

[Link]("Enter x1 of point p1: ");


int x1 = [Link]([Link]());
[Link]("Enter y1 of point p1: ");

Page | 154
int y1 = [Link]([Link]());
[Link]("Enter x2 of point p2: ");
int x2 = [Link]([Link]());
[Link]("Enter y2 of point p2: ");
int y2 = [Link]([Link]());

Circle obj = new Circle(x1, y1, x2, y2);


[Link]();
[Link]();
[Link]();
}
}
Output:

Page | 155
Program 06: Bank
A super class Bank has been defined to store the details of a customer. Define a sub-class Account that enables
transactions for the customer with the bank. The details of both the classes are given below:
Class name: Bank
Data members/instance variables:
name: stores the name of the customer
accno: stores the account number
p: stores the principal amount in decimals
Member functions/methods:
Bank(…): parameterized constructor to assign values to the instance variables
void display(): displays the details of the customer
Class name: Account
Data member/instance variable:
amt: stores the transaction amount in decimals
Member functions/methods:
Account(…): parameterized constructor to assign values to the instance variables of both the classes
void deposit(): accepts the amount and updates the principal as p = p + amt
void withdraw(): accepts the amount and updates the principal as p = p – amt. If the withdrawal amount is
more than the principal amount, then display the message “INSUFFICIENT BALANCE”. If the principal
amount after withdrawal is less than 500, then a penalty is imposed by using the formula p = p – (500 – p) / 10
void display(): displays the details of the customer
Assume that the super class Bank has been defined. Using the concept of inheritance, specify the class
Account giving details of the constructor, void deposit(), void withdraw() and void display().
The super class and the main function need not be written.
Algorithm:
Step 1: Start the program
Step 2: Create an object of class Account by passing customer name, account number, and initial
principal amount
Step 3: Display the menu with options: Deposit, Withdraw, Display Details, Exit
Step 4: Input user’s choice
Step 5: If choice is 1, call deposit() method
→ Input the amount to deposit
→ Add the amount to principal (p = p + amt)
Step 6: If choice is 2, call withdraw() method
→ Input the amount to withdraw
→ Check if withdrawal amount > principal
→ If yes, display “INSUFFICIENT BALANCE”
→ Else, subtract amount from principal (p = p – amt)
→ Check if new principal < 500
→ If yes, calculate penalty = (500 – p) / 10
→ Deduct penalty from principal (p = p – penalty)
Step 7: If choice is 3, call display() method to show customer name, account number, current
principal, and last transaction amount
Step 8: If choice is 4, terminate the program
Step 9: Repeat from Step 3 until the user chooses to exit
Step 10: Stop the program
Code:

Page | 156
import [Link];
// Super class Bank (already defined as per question)
class Bank {
protected String name;
protected int accno;
protected double p; // principal amount
public Bank(String n, int a, double pr) {
name = n;
accno = a;
p = pr;
}
public void display() {
[Link]("Customer Name : " + name);
[Link]("Account Number : " + accno);
[Link]("Principal Amount : " + [Link]("%.2f", p));
}
}
// Sub-class Account using inheritance
class Account extends Bank {
double amt; // transaction amount
// Parameterized constructor
public Account(String n, int a, double pr) {
super(n, a, pr);
amt = 0.0;
}
// Deposit money
public void deposit() {
Scanner in = new Scanner([Link]);
[Link]("Enter amount to deposit: ");
amt = [Link]([Link]());
if (amt > 0) {
p += amt;
[Link]("Amount " + amt + " deposited successfully.");
} else {
[Link]("Invalid deposit amount!");
}
}
// Withdraw money with conditions
public void withdraw() {
Scanner in = new Scanner([Link]);
[Link]("Enter amount to withdraw: ");
amt = [Link]([Link]());
if (amt > p) {
[Link]("INSUFFICIENT BALANCE");
} else {
p -= amt;

Page | 157
[Link]("Amount " + amt + " withdrawn successfully.");
if (p < 500) {
double penalty = (500 - p) / 10.0;
p -= penalty;
[Link]("Balance below 500! Penalty imposed: " + [Link]("%.2f",
penalty));
[Link]("New balance after penalty: " + [Link]("%.2f", p));
}
}
}
// Display all customer and current account details
public void display() {
[Link]();
[Link]("Last Transaction Amount : " + [Link]("%.2f", amt));
[Link]("Current Balance : " + [Link]("%.2f", p));
[Link]("----------------------------------------");
}
}
// Driver class with menu
public class BankTransaction {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter Customer Name : ");
String name = [Link]();
[Link]("Enter Account Number : ");
int accno = [Link]([Link]());
[Link]("Enter Initial Principal : ");
double principal = [Link]([Link]());
Account customer = new Account(name, accno, principal);
while (true) {
[Link]("\n=== BANK TRANSACTION MENU ===");
[Link]("1. Deposit Money");
[Link]("2. Withdraw Money");
[Link]("3. Display Account Details");
[Link]("4. Exit");
[Link]("Enter your choice (1-4): ");
int choice = [Link]([Link]());
switch (choice) {
case 1:
[Link]();
break;
case 2:
[Link]();
break;
case 3:
[Link]();

Page | 158
break;
case 4:
[Link]("Thank you for banking with us. Goodbye!");
[Link]();
return;
default:
[Link]("Invalid choice! Please try again.");
}
}
}
}
Output:

Page | 159
Program 07: Series
A super class Number is defined to calculate the factorial of a number. Define a subclass Series to find the sum
of the series S = 1! + 2! + 3! + 4! + … + n!
The details of the members of both the classes are given below:
Class name: Number
Data member/instance variable:
n: to store an integer number
Member functions/methods:
Number(int nn): parameterized constructor to initialize the data member n = nn
int factorial(int a): returns the factorial of a number (factorial of n = 1 × 2 × 3 × … × n)
void display(): displays the data members
Class name: Series
Data member/instance variable:
sum: to store the sum of the series
Member functions/methods:
Series(…): parameterized constructor to initialize the data members of both the classes
void calsum(): calculates the sum of the given series
void display(): displays the data members of both the classes
Assume that the super class Number has been defined. Using the concept of inheritance, specify the class
Series giving the details of the constructor(…), void calsum() and void display().
The super class, main() function and algorithm need not be written.
Algorithm:
Step 1: Start the program
Step 2: Input a positive integer value for n
Step 3: Create an object of class Series by passing n
Step 4: Call the method calSum() to compute the sum of the series
→ Initialize sum = 0
→ Use a loop from i = 1 to i <= n
→ For each i, calculate factorial(i) using the inherited method
→ Add the result to sum
Step 5: Call the display() method
→ First display the value of n (using super-class display logic)
→ Then display the calculated sum of the series
Step 6: Stop the program
Code:
import [Link];
// Super class Number (as given)
class Number {
protected int n;
public Number(int nn) {
n = nn;
}
// Recursive factorial method
public int factorial(int a) {
if (a == 0 || a == 1)
return 1;
return a * factorial(a - 1);
Page | 160
}
public void display() {
[Link]("Value of n = " + n);
}
}
// Subclass Series using inheritance
class Series extends Number {
int sum; // To store sum of factorial series
// Parameterized constructor
public Series(int nn) {
super(nn); // Initialize n in super class
sum = 0;
}
// Method to calculate sum of series: 1! + 2! + ... + n!
public void calSum() {
sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i); // Reuse inherited factorial() method
}
}
// Override display to show n and the sum
public void display() {
[Link](); // Display n from super class
[Link]("Sum of series (1! + 2! + ... + " + n + "!) = " + sum);
}
}
// Driver class
public class FactorialSeriesDemo {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]([Link]());

if (n < 0) {
[Link]("Please enter a non-negative integer.");
} else {
Series obj = new Series(n);
[Link]();
[Link]();
}
[Link]();
}
}

Page | 161
Output:

Page | 162
Program 08: Flight
A superclass Flight has been defined to store the details of a flight. Define a subclass Passenger to calculate the
fare for a passenger.
Class name: Flight
Data members/instance variables:
flightno: to store the flight number in string
dep_time: to store the departure time in string
arr_time: to store the arrival time in string
basefare: to store the base fare in decimal
Methods/Member functions:
Flight(…): parameterized constructor to assign values to the data members
void show(): to display the flight details
Class name: Passenger
Data members/instance variables:
id: to store the ID of the passenger
name: to store the name of the passenger
tax: to store the tax to be paid in decimal
tot: to store the total amount to be paid in decimal
Methods/Member functions:
Passenger(…): parameterized constructor to assign values to the data members of both the classes
void cal(): to calculate the tax as 5% of base fare and total amount (base fare + tax)
void show(): to display the flight details along with the passenger details and total amount to be paid.
Algorithm:
Step 01: Start the program.
Step 02: Define class Flight.
Step 03: Create a constructor to initialize flight data.
Step 04: Create show() method to display flight details.
Step 05: Define subclass Passenger extending Flight.
Step 06: Create a constructor in Passenger to initialize passenger data and call super().
Step 07: Define cal() method to compute tax and total fare.
Step 08: Override show() in Passenger to display passenger info, call [Link](), and cal().
Step 09: Stop.
Code:
class Flight{
String flightno,dep_time,arr_time;
double basefare;
Flight(String f,String d, String a,double b){
flightno=f;
dep_time=d;
arr_time=a;
basefare=b;}
void show(){
[Link]("Flight Number: "+flightno);
[Link]("Departure Timings: "+dep_time);
[Link]("Arrival Timings: "+arr_time);
[Link]("Base Fare price: "+basefare);}}
class Passenger extends Flight{
String id,name;
double tax,tot;

Page | 163
Passenger(String f,String d, String a,double b,String i,String n){
super(f,d,a,b);
id=i;
name=n;}
void cal(){
tax=(5.0/100.0)*basefare;
tot=basefare+tax;
[Link]("Tax:"+tax);
[Link]("Total Amount to be paid:"+tot);}
void show(){
[Link]("Name of the passenger:"+name);
[Link]("ID of the Passenger:"+id);
[Link]();
cal();}
public static void main(String args[]){
Scanner obj=new Scanner([Link]);
[Link]("Enter the name of the passenger:");
String n=[Link]();
[Link]("Enter the flight number:");
String f=[Link]();
[Link]("Enter the ID of the passenger:");
String i=[Link]();
[Link]("Enter the basefare:");
double b=[Link]();
[Link]("Enter the arrival timings of the passenger:");
String a=[Link]();
[Link]("Enter the departure timings of the passenger:");
String d=[Link]();
Passenger ob=new Passenger(f,d,a,b,i,n);
[Link]();}}

Output:

Page | 164
Program 09: Interest
A super class Bank has been defined to store the details of the customer in a bank. Define a subclass Interest to
calculate the compound interest.
Class name : Bank
Data members/instance variables:
name : to store the name of the customer
acc_no : integer to store the account number
principal : to store the principal amount in decimals
Methods / Member functions:
Bank( ... ) : parameterized constructor to assign values to the data members void display( ) : to display the
customer details
Class name Interest
Data members/instance variables:
rate : to store the interest rate in decimals
time : to store the time period in decimals
Methods / Member functions:
Interest( ... ) : parameterized constructor to assign values to the data members of both the classes
double calculate( ) : to calculate and return the compound interest using the formula
[ CI = P ( 1 + R/100 )N − P] where, P is the principal, R is the rate and N is the time
void display( ) : to display the customer details along with the compound interest.
Algorithm:
Step 01: Start the program.
Step 02: Define class Bank.
Step 03: Create a constructor to initialize name, account number, and principal.
Step 04: Create display() method to show bank details.
Step 05: Define subclass Interest extending Bank.
Step 06: Create a constructor in Interest to initialize rate and time, and call super().
Step 07: Create calculate() method to compute compound interest.
Step 08: Override display() to show bank details and computed interest.
Step 09: Stop.
Code:
class Bank{
String name;
int ac_no;
double principal;
Bank(String n,int a,double p){
name=n;
ac_no=a;
principal=p;}
void display(){
[Link]("Name of the customer: "+name);
[Link]("Account number of the customer: "+ac_no);
[Link]("Principal amount of the customer: "+principal);}}
class Interest extends Bank{
double rate,time;
Interest(String n,int a,double p,double r,double t){
super(n,a,p);
rate=r;
time=t;}

Page | 165
double calculate(){
return (principal * [Link](( 1 + (rate/100)),time)) - principal;}
void display(){
[Link]();
[Link]("The Compound Interest: "+calculate());}
public static void main(String args[]){
Scanner obj=new Scanner([Link]);
[Link]("");
[Link]("Enter Name of the customer");
String n=[Link]();
[Link]("Enter Account number of the customer");
int a=[Link]();
[Link]("Enter Principal amount of the customer");
double p=[Link]();
[Link]("Enter Rate of Interest the customer");
double r=[Link]();
[Link]("Enter deposit time of the customer");
double t=[Link]();
Interest ob=new Interest(n,a,p,r,t);
[Link]();}}

Output:

Page | 166
Program 10: Emp Sal
A super class EmpSal has been defined to store the details of an employee. Define a
subclass Overtime to compute the total salary of the employee, after adding the overtime amount
based on the following criteria.
 If hours are more than 40, then ₹ 5000 are added to salary as an overtime amount

 If hours are between 30 and 40 (both inclusive), then ₹ 3000 are added to salary as an
overtime amount

 If hours are less than 30, then the salary remains unchanged

The details of the members of both the classes are given below.
Class name: EmpSal
Data members/instance variables:
empnum: to store the name of the employee
empcode: integer to store the employee code
salary: to store the salary of the employee in decimal
Methods/Member functions:
EmpSal(…): parameterized constructor to assign values to data members
void show(): to display the details of the employee
Class name: Overtime
Data members/instance variables:
hours: integer to store overtime in hours
totsal: to store the total salary in decimal
Methods/Member functions:
Overtime(…): parameterized constructor to assign values to data members of both the classes
void calSal(): calculates the total salary by adding the overtime amount to salary as per the criteria
given above
void show(): to display the employee details along with the total salary (salary + overtime amount)
Algorithm:
Step 01: Start the program.
Step 02: Define class EmpSal.
Step 03: Create a constructor to initialize employee name, code, and salary.
Step 04: Create show() method to display employee details.
Step 05: Define subclass Overtime extending EmpSal.
Step 06: Create a constructor in Overtime to initialize overtime hours and call super().
Step 07: Create calSal() method to compute total salary based on overtime hours:
 If hours > 40 → add 5000
 If 30 ≤ hours ≤ 40 → add 3000
 If hours < 30 → no extra
Step 08: Override show() to display employee details, overtime hours, and total salary.
Step 09: Stop.
Code:
class EmpSal{
String empname;

Page | 167
int empcode;
double salary;
EmpSal(String name, int code, double sal){
empname=name;
empcode=code;
salary=sal;}
void show(){
[Link]("Name of the Employee:"+empname);
[Link]("Code of the Employee:"+empcode);
[Link]("Salary of the Employee:"+salary);}}
class Overtime extends EmpSal{
int hours;
double total;
Overtime(String name,int code,double sal,int h){
super(name,code,sal);
hours=h;}
void calSal(){
if(hours>40)
total=salary+5000;
if(hours>=30 && hours<=40)
total=salary+3000;
if(hours<30)
total=salary;}
void show(){
[Link]();
[Link]("Overtime hours of the Employee:"+hours);
[Link]("Total salary of the Employee:"+total);}
public static void main(String args[]){
Scanner obj=new Scanner([Link]);
[Link]("Enter the name of the employee:");
String name=[Link]();
[Link]("Enter the code of the employee:");
int code=[Link]();
[Link]("Enter the salary of the employee:");
double sal=[Link]();
[Link]("Enter the overtime hours of the employee:");
int h=[Link]();
Overtime ob=new Overtime(name,code,sal,h);
[Link]();
[Link]();}}

Page | 168
Output:

Page | 169
Program 11: Library

Algorithm:
Step 01: Start the program.
Step 02: Define class Library.
Step 03: Create a constructor to initialize book name, author, and price.
Step 04: Create show() method to display book details.
Step 05: Define subclass Compute extending Library.
Step 06: Create a constructor in Compute to initialize number of days and call super().
Step 07: Create fine() method to compute the fine based on days used:
 If days > 7 → calculate extra days and fine:
o ≤ 5 days → 2 per day
o 6–10 days → 3 per day
o 10 days → 5 per day
 If days ≤ 7 → fine = 0
 Add 2% of extra days to fine and compute total amount.
Step 08: Override show() to display book details, number of days, and call fine().
Step 09: Stop.
Code:
class Library{
String name,author;
double p;
Library(String n,String a,double pa){
name=n;
author=a;
p=pa;}
void show(){
[Link]("Name of the book: "+name);
[Link]("Name of the author: "+author);
[Link]("Price of the book: "+p);}}
import [Link].*;
class Compute extends Library{
int d;
double f;
Compute(String n,String a,double pa,int dd){
super(n,a,pa);
d=dd;}
void fine(){
if(d>7){
d=d-7;
if(d<=5 && d!=0)
f=2.0*d;
else if(d>=6 && d<=10)
f=3.0*d;

Page | 170
else
f=5.0*d;}
else
f=0;
[Link]("Fine: "+f);
double a=((2.0/100.0)*d)+f;
[Link]("Total amount to be paid : "+a);}
void show(){
[Link]();
[Link]("Number of days books used: "+d);
fine();}
public static void main(String args[]){
Scanner obj=new Scanner([Link]);
[Link]("Enter Name of the book: ");
String n=[Link]();
[Link]("Enter Name of the author: ");
String a=[Link]();
[Link]("Enter Price of the book: ");
int pa=[Link]();
[Link]("Enter number of the days: ");
int dd=[Link]();
Compute ob=new Compute(n,a,pa,dd);
[Link]();}}

Output:

Page | 171
Program 12: Circle
A super class Circle has been defined to calculate the area of a circle. Define a subclass Volume to
calculate the volume of a cylinder.
Class name : Circle
Data members/instance variables:
radius : to store the radius in decimals
area : to store the area of a circle
Methods / Member functions:
Circle( ... ) : parameterized constructor to assign values to the data members void cal_area() :
calculates the area of a circle (πr2 )
void display( ) : to display the area of the circle
Class name Volume
Data members/instance variables:
height : to store the height of the cylinder in decimals
volume : to store the volume of the cylinder in decimals
Methods / Member functions:
Volume( ... ) : parameterized constructor to assign values to the data members of both the classes
double calculate( ) : to calculate and return the volume of the cylinder using the formula (πr2 h)
where, r is the radius and h is the height
void display( ) : to display the area of a circle and volume of a cylinder
Algorithm:
Step 01: Start the program.
Step 02: Define class Circle.
Step 03: Create a constructor to initialize radius.
Step 04: Create method cal_area() to calculate the area of the circle: area==3.14×radius2
Step 05: Create method display() to print the area of the circle.
Step 06: Define subclass Volume extending Circle.
Step 07: Create a constructor in Volume to initialize height and call super(radius).
Step 08: Create method calculate() to compute the volume of the cylinder:
volume=3.14×radius2×height
Step 09: Override display() to:
Call [Link]() to show circle area
Print the cylinder volume using calculate()
Step 10: Stop.
Code:
class Circle{
double radius, area;
Circle(double r){
radius=r;}
void cal_area(){
area= 3.14 * radius * radius;}
void display(){
[Link]("The area of the circle is:"+area);}}
class Volume extends Circle{
double height, volume;
Page | 172
Volume(double h,double r){
super(r);
height=h;}
double calculate(){
volume=(3.14 * radius * radius * height);
return volume;}
void display(){
[Link]();
[Link]("The area of the Cylinder is:"+calculate());}
public static void main(String args[]){
Scanner obj=new Scanner([Link]);
[Link]("Enter the radius of the circle");
double r=[Link]();
[Link]("Enter the height of the cylinder");
double h=[Link]();
Volume ob=new Volume(h,r);
ob.cal_area();
[Link]();}}

Output:

Page | 173
Program 13: Author
Write a Java program to demonstrate the concept of inheritance. Create a base class named Author
with the following members:
o Data members:int authorno (Author number); String name (Author name)
 Constructors:A default constructor initializing data members to default values
o A parameterized constructor to initialize the data members
 A method void show() to display the author's details

Create a derived class named Booklist that extends the Author class, with the following additional
members:
 Data members:
o long bookno (Book number)
o int edition (Edition number)
o String bookname (Name of the book)
o float price (Price of the book)
 A parameterized constructor to initialize all data members (including the inherited ones using
super()). An overridden method void show() to display both author and book details
Algorithm:
Step 01: Start the program.
Step 02: Define class Author.
• Two constructors: default (0, "") and parameterized (author number and name).
• Method show() prints author number and name.
Step 03: Define class Booklist extending Author.
• Constructor initializes: bookno (book number); edition’;bookname’; price; Calls super(a,n) to
set author info.
• Method show() overrides parent show() and prints book details in addition to author info.
Step 04: Stop.
Code:
import [Link].*;
class Author{
int authorno;
String name;
Author(){
authorno=0;
name="";}
Author(int a,String n){
authorno=a;
name=n;}
void show(){
[Link]("Name of the author:"+name);
[Link]("Number of the author:"+authorno); }}
class Booklist extends Author{
long bookno;

Page | 174
int edition;
String bookname;
float price;
Booklist(int a,String n,long b,int e,String bn,float p){
super(a,n);
bookno=b;
edition=e;
bookname=bn;
price=p;}
void show(){
[Link]();
[Link]("Name of the book:"+bookname);
[Link]("Number of the book:"+bookno);
[Link]("Price of the book:"+price);
[Link]("Edition of the book:"+edition);}
public static void name(String args[]){
Scanner obj=new Scanner([Link]);
[Link]("Enter number of the author:");
int a=[Link]();
[Link]("Enter name of the author:");
String n=[Link]();
[Link]("Enter number of the book:");
long b=[Link]();
[Link]("Enter edition of the book:");
int e=[Link]();
[Link]("Enter name of the book:");
String bn=[Link]();
[Link]("Enter price of the book:");
float p=[Link]();
Booklist ob=new Booklist(a,n,b,e,bn,p);}}

Output:

Page | 175
Program 14: Shape
Write a Java program to demonstrate the use of interfaces.
1. Define an interface Shape with the following: An abstract method double area() to compute the area of
a shape.
2. Implement the Shape interface in two classes:
Class rect to represent a rectangle with:
Data members: double length and double breadth
A constructor to initialize length and breadth
An implementation of the area() method that returns the area of the rectangle
Class circ to represent a circle with:
Data member: double radius
A constructor to initialize the radius
An implementation of the area() method that returns the area of the circle
Algorithm:
Step 01: Start the program.
Step 02: Define interface Shape.
• Declares an abstract method area() that returns a double.
Step 03: Define class rect implementing Shape.
• Fields: length, breadth.
• Constructor initializes length and breadth.
• Implements area() method as length * breadth.
Step 04: Define class circ implementing Shape.
• Field: radius.
• Constructor initializes radius.
• Implements area() method as 3.14 * radius * radius.
Step 05: Stop.
Code:
class rect implements Shape{
double length,breadth;
rect(int l, int b){
length=l;
breadth=b;}
public double area(){
return length*breadth;}}
class circ implements Shape {
double radius;
circ(int r){
radius=r;}
public double area(){
return 3.14*radius*radius;}}
interface Shape{
abstract double area();}

Page | 176
Output:

Page | 177
Program 15: Student
Write a Java program to demonstrate the concepts of multilevel inheritance and interface implementation.
Your program should include the following components:
1. A base class Student with:
A data member: int indexno
A method void getIndexNumber(int rn) to assign the index number
A method void Show() to display the index number
2. A derived class TestMarks that extends Student, with:
Data members: double sub1 and double sub2 to store marks of two subjects
A method void readMarks(double s1, double s2) to assign subject marks
A method void showMarks() to display both subject marks
3. An interface SchoolRecord with:
A static final data member dob (Date of Birth)
An abstract method void printDOB() to display the date of birth
4. A class result that:
Extends TestMarks
Implements SchoolRecord
Contains a method void display()
Algorithm:
Step 1: Start.
Step 2: Input student index number.
Step 3: Input marks of two subjects.
Step 4: Store the index number in the student record.
Step 5: Store the marks in the test marks record.
Step 6: Compute total marks as the sum of the two subject marks.
Step 7: Display the index number.
Step 8: Display marks of both subjects.
Step 9: Display total marks.
Step 10: Display date of birth from the school record.
Step 11: End.
Code:
class result extends TestMarks implements SchoolRecord{
double total;
public void printDOB(){
[Link]("Date of Birth:"+dob);}
void display(){
[Link]();
[Link]();
total=sub1+sub2;
[Link]("Total marks: "+total);
printDOB();}
public static void main(String args[]){
Scanner obj=new Scanner ([Link]);
result ob=new result();
[Link]("Enter the index number");
[Link]([Link]());

Page | 178
[Link]("Enter the marks of 2 subjects:");
[Link]([Link](),[Link]());
[Link]();}}
class TestMarks extends Student{
double sub1,sub2;
void readMarks(double s1,double s2){
sub1=s1;
sub2=s2;}
void showMarks(){
[Link]("Marks in 1st Subject: "+sub1);
[Link]("Marks in 2nd Subject: "+sub2);}}
class Student{
int indexno;
void getIndexNumber(int rn){
indexno=rn;}
void Show(){
[Link]("Index Number: "+indexno);}}
interface SchoolRecord{
static String dob="09 09 99";
abstract void printDOB();}

Output:

Page | 179
Page | 180
Index

Sl. No. Title Page


String Manipulation
1. Ceaser Cipher 182
2. Pangrammatic Lipogram 184
3. Palindrome Sentence 186
4. Balanced Brackets 189
5. Flipgram 192
6. Pangram 194
7. Keypad 197
8. Anagram 199
9. Mask String 201
10. Snowball String 203

Page | 181
Program 01: Ceaser Cipher
Question:
Write a program to input a plaintext string of length greater than 3 and less than 100.
If the length is invalid, display "INVALID LENGTH".
Otherwise, encrypt the text using Caesar Cipher (ROT13), where each alphabetic character is
replaced by the character 13 positions ahead, keeping case unchanged and leaving all non-
alphabetic characters as they are.
Display the resulting cipher text.
Example 1
Input: Hello! How are you?
Output: Uryyb! Ubj ner lbh?
Example 2
Input: You
Output: INVALID LENGTH
Algorithm:
Step 01: Start the program.
Step 02: Define the class Cipher.
Step 03: Declare the variables: text, cipher.
Step 04: In the constructor, input the text.
Step 05: Check if the length of text is within the valid range ( >3 and <100 ).
Step 06: If invalid, display "INVALID LENGTH" and stop.
Step 07: Otherwise, call the encrypt() method.
Step 08: In the encrypt() method:

 Traverse each character of the text.


 If the character is a letter:
• Rotate it by 13 positions (A ↔ N, a ↔ n).
 Otherwise, keep the character unchanged.
 Append each converted character to cipher.
Step 09: Create a display() method to show the encrypted text.
Step 10: In the main class, create an object of Cipher.
Step 11: Call the display function.
Step 12: Stop.
Code:
import [Link];
public class Rot13Cipher {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input
[Link]("Enter a sentence (terminating with ?/.)");
String text = [Link]();
int L = [Link]();
// Length check
if (L <= 3 || L >= 100) {
[Link]("INVALID LENGTH");

Page | 182
return;
}
// Convert string to char array
char[] arr = [Link]();
char[] cipher = new char[L];
// Process each character
for (int i = 0; i < L; i++) {
char ch = arr[i];
// Uppercase letters
if (ch >= 'A' && ch <= 'Z') {
cipher[i] = (char) ((ch - 'A' + 13) % 26 + 'A');
}
// Lowercase letters
else if (ch >= 'a' && ch <= 'z') {
cipher[i] = (char) ((ch - 'a' + 13) % 26 + 'a');
}
// Special characters stay same
else {
cipher[i] = ch;
}
}
// Output
[Link]("The cipher text is:\n");
[Link](new String(cipher));
}
}

Output:

Page | 183
Program 02: Pangrammatic Lipogram
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only.
The words may be separated by a single blank space and should be case-insensitive.
Perform the following tasks:
a) If the sentence is a pangram (a sentence or a phrase that uses every letter of the alphabet at
least once), then print PANGRAM.
b) If it misses exactly one letter of the alphabet, print PANGRAMMATIC LIPOGRAM and
the missing letter.
c) Else print NEITHER and list all the missing letters in alphabetical order.
Algorithm:
Step 01: Start.
Step 02: Accept the input sentence as a string.
Step 03: Check the last character of the sentence.
• If it is not . or ? or !, print INVALID INPUT and stop.
Step 04: Remove the ending punctuation.
Step 05: Convert the sentence to lowercase.
Step 06: Create a boolean array of size 26 to track letters a to z.
Step 07: Traverse each character in the sentence.
• If character is between a and z, mark its position as true in the array.
Step 08: Count how many letters are missing.
Step 09:
• If 0 letters are missing → print IT IS A PANGRAM
• If 1 letter is missing → print
PANGRAMMATIC LIPOGRAM
Missing: <letter>
• Else → print
NEITHER
<all missing letters in alphabetical order>
Step 10: End.
Code:
import [Link];
public class PangramCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a sentence:");
String sentence = [Link]().trim();
// Check valid ending punctuation
char last = [Link]([Link]() - 1);
if (last != '.' && last != '?' && last != '!') {
[Link]("INVALID INPUT");
return;
}
// Remove ending punctuation
sentence = [Link](0, [Link]() - 1).toLowerCase();
boolean[] present = new boolean[26];
Page | 184
// Mark letters present
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (ch >= 'a' && ch <= 'z') {
present[ch - 'a'] = true;
}
}
// Find missing letters
StringBuilder missing = new StringBuilder();
int countMissing = 0;
for (int i = 0; i < 26; i++) {
if (!present[i]) {
[Link]((char)('a' + i)).append(" ");
countMissing++;
}
}
// Output based on number of missing letters
if (countMissing == 0) {
[Link]("IT IS A PANGRAM");
} else if (countMissing == 1) {
[Link]("PANGRAMMATIC LIPOGRAM");
[Link]("Missing: " + [Link]().trim());
} else {
[Link]("NEITHER");
[Link]([Link]().trim());
}
}
}
Output:

Page | 185
Program 03: Palindrome Sentence
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only.
The words may be separated by a single blank space and should be case-insensitive.

Perform the following tasks:


(a) Check if the sentence is a Palindrome Sentence. A sentence is a Palindrome Sentence if,
after removing the spaces and punctuation, the letters read the same forward and backward.
Example: “Never odd or even.”
(b) Display the first-occurring most frequent word in the sentence (in lowercase). If there is a
tie, choose the word that appears first in the sentence and if no words are repeated then print
NONE.
Algorithm:
Step 01: Start.
Step 02: Accept the input sentence as a string.
Step 03: Check the last character.
• If it is not ., ?, or !, print INVALID INPUT and stop.
Step 04: Remove the ending punctuation.
Step 05: Convert the sentence to lowercase.
PALINDROME CHECK
Step 06: Create an empty string clean.
Step 07: Traverse each character of the sentence.
• If it is a letter a to z, add it to clean.
Step 08: Check palindrome:
• Compare characters clean[i] with clean[len - 1 - i] using a loop.
• If mismatch found → not palindrome.
• Else → palindrome.
MOST FREQUENT WORD
Step 09: Split the lowered sentence by spaces into words.
Step 10: For each word, remove any non-letter characters.
Step 11: Store words in an array.
Step 12: Use nested loops to count the frequency of each word.
Step 13: Track:
• Maximum frequency
• First occurring word with that frequency
Step 14: If maximum frequency is 1 → print NONE
Else → print the word.
Step 15: End.
Code:
import [Link];
class Palindrome{
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Sentence: ");
String s = [Link]();
char last = [Link]([Link]() - 1);

Page | 186
if(".?!".indexOf(last) == -1){
[Link]("INVALID INPUT");
return;
}
String str = "";
int count = 0;
if([Link]() > 0)
count = 1;
for(int i = 0; i < [Link](); i++){
char ch = [Link](i);
if(ch == ' ')
count++;
}
String a[] = new String[count];
int f[] = new int[count];
String word = "";
int index = 0;
for(int i = 0; i < [Link](); i++){
char ch = [Link](i);
if([Link](ch)){
str += ch;
word += ch;
}
else{
a[index++] = word;
word = "";
}
}
boolean isPalindrome = true;
for(int i = 0, j = [Link]() - 1; i <= j; i++, j--){
char ch1 = [Link]([Link](i));
char ch2 = [Link]([Link](j));
if(ch1 != ch2){
isPalindrome = false;
break;
}
}
if(isPalindrome)
[Link]("IT IS A PALINDROME SENTENCE");
else
[Link]("IT IS NOT A PALINDROME SENTENCE");
int highest = 0;
for(int i = 0; i < [Link]; i++){
for(int j = 0; j < [Link]; j++){
if(a[i].equalsIgnoreCase(a[j]))
f[i]++;

Page | 187
}
if(f[i] > highest)
highest = f[i];
}
String most = "";
for(int i = 0; i < [Link]; i++){
if(f[i] == highest && f[i] > 1){
most = a[i];
break;
}
}
if([Link]() > 0)
[Link]("MOST FREQUENT WORD: " + [Link]());
else
[Link]("MOST FREQUENT WORD: NONE");
}
}
Output:

Page | 188
Program 04: Balanced Brackets
Accept a sentence terminated by ‘.’, ‘?’ or ‘!’ only. Sentence may contain any of () [] {} plus
letters/spaces. It must contain no digits and no other symbols besides the final terminator. For
any violation, display INVALID INPUT.
Perform the following tasks:
(a) Check if the brackets are balanced and properly nested.
(b) Print the maximum nesting depth of brackets.
(c) If unbalanced, print the index (one-based indexing) of the first error.
 A mismatched/extra closing bracket is an error at that bracket’s index.
 If brackets are incomplete at the terminator, the first error is the index of the first
bracket that cannot be matched (typically where the mismatch first occurs).
Algorithm:
Step 01: Start.
Step 02: Read the input sentence.
Step 03: If the sentence is empty → print INVALID INPUT, stop.
Step 04: Check the last character:
• Must be one of ., ?, !
• If not → print INVALID INPUT
Step 05: Remove the sentence terminator.
Step 06: Validate each character:
• Allowed: letters, spaces, ()[]{}
• If any digit or illegal character appears → print INVALID INPUT
Step 07: Create a stack (char array) and top = -1.
Step 08: Traverse characters one by one:
• If ( or [ or {, push to stack and update maxDepth
• If ) or ] or }, check stack:
— If empty → first error at this index
— Else pop and check matching pair
— If mismatch → first error at this index
Step 09: After traversal, if stack not empty:
• Unmatched opening bracket exists
• Error index = index of the first unmatched bracket (the earliest one)
Step 10:
• If no error → print BALANCED: YES and maxDepth
• Else → print BALANCED: NO and error index
Step 11: End.
Code:
import [Link];
class Brackets {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Sentence: ");
String s = [Link]().trim();
// Empty input check
if ([Link]() == 0) {

Page | 189
[Link]("INVALID INPUT");
return;
}
// Check last character
char last = [Link]([Link]() - 1);
if (last != '.' && last != '?' && last != '!') {
[Link]("INVALID INPUT");
return;
}
// Remove terminator
s = [Link](0, [Link]() - 1);
// Validate characters
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (![Link](ch) &&
ch != ' ' &&
"()[]{}".indexOf(ch) == -1) {
[Link]("INVALID INPUT");
return;
}
}
// Stack for brackets
char stack[] = new char[[Link]()];
int indexStack[] = new int[[Link]()];
int top = -1;
int maxDepth = 0;
int errorIndex = -1;
boolean errorFound = false;
// Process characters
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
// Opening brackets
if ("([{".indexOf(ch) >= 0) {
stack[++top] = ch;
indexStack[top] = i + 1; // store index (1-based)
if (top + 1 > maxDepth)
maxDepth = top + 1;
}
// Closing brackets
else if (")]}".indexOf(ch) >= 0) {
if (top == -1) {
errorFound = true;
errorIndex = i + 1;
break;
}
char open = stack[top];

Page | 190
boolean match =
(open == '(' && ch == ')') ||
(open == '[' && ch == ']') ||
(open == '{' && ch == '}');
if (match) {
top--;
} else {
errorFound = true;
errorIndex = i + 1;
break;
}
}
}
// Unmatched opening brackets
if (!errorFound && top != -1) {
errorFound = true;
errorIndex = indexStack[0]; // first unmatched opening bracket
}
// Output results
if (errorFound) {
[Link]("BALANCED: NO");
[Link]("ERROR AT INDEX: " + errorIndex);
} else {
[Link]("BALANCED: YES");
[Link]("MAX DEPTH: " + maxDepth);
}
}
}
Output:

Page | 191
Program 05: Flipgram
A class Flipgram has been defined to flip the letters of the left and right halves of a non-
heterogram word. If the word has odd number of characters, then the middle letter remains at
its own position.
A heterogram is a word where no letter appears more than once.
Algorithm:
Step 01: Start.
Step 02: Accept a word from the user.
Step 03: Create a Flipgram object using the word.
For ishetero():
Step 04: Loop through each character of the word. For each character, check if it appears
again later in the word. If any repeat is found → return false (not heterogram).
Step 05: If loop completes → return true (heterogram).
For flip():
Step 06: Find the length of the word.
Step 07: If length is even: Split the word into left half and right half. Return right + left
Step 08:If length is odd: Middle character stays in place. Return right + middle + left
For display():
Step 09: Call ishetero(). If true → print HETEROGRAM Else → call flip() and print the
flipped result in uppercase
Step 10: End.
Code:
import [Link];
class Flipgram {
String word;
// Parameterized constructor
public Flipgram(String s) {
word = s;
}
// Check if the word is a heterogram
public boolean ishetero() {
for (int i = 0; i < [Link]() - 1; i++) {
char ch = [Link](i);
String rest = [Link](i + 1);
if ([Link](ch) >= 0)
return false; // repeated letter found
}
return true; // no repetition → heterogram
}
// Flip left and right halves of a non-heterogram word
public String flip() {
int len = [Link]();
if (len % 2 == 0) {
// even length
String left = [Link](0, len / 2);

Page | 192
String right = [Link](len / 2);
return right + left;
} else {
// odd length
String left = [Link](0, len / 2);
String right = [Link](len / 2 + 1);
char mid = [Link](len / 2);
return right + mid + left;
}
}
// Display output
public void display() {
if (ishetero())
[Link]("HETEROGRAM");
else
[Link](flip().toUpperCase());
}
// Main function
public static void main(String[] args) {
Scanner in = new Scanner([Link]);

[Link]("Enter the word: ");


String w = [Link]();

Flipgram obj = new Flipgram(w);


[Link]();
}
}
Output:

Page | 193
Program 06: Pangram
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only.
The words may be separated by a single blank space and should be case-sensitive.
Perform the following tasks:
(a) Determine if the accepted sentence is a Pangram or not. A Pangram is a sentence that
contains every letter of the alphabet at least once. Example: “The quick brown fox jumps over
the lazy dog.”
(b) Display the first occurring longest and shortest word in the accepted sentence.
Algorithm:
Step 01: Start.
Step 02: Accept a sentence from the user.
Step 03: Check if input length is zero → print INVALID INPUT → stop.
Step 04: Check last character of sentence.
If it is NOT ., ?, ! → print INVALID INPUT → stop.
Step 05: Scan entire sentence (excluding last character).
If any character is not: A letter, A space,
→ print INVALID INPUT → stop.
Step 06: PANGRAM CHECK
For each letter ‘a’ to ‘z’: Scan the sentence (case-insensitive). If any letter missing → sentence
is NOT pangram.
Else → pangram.
Step 07: WORD EXTRACTION
Traverse the sentence (excluding last character): Build each word letter-by-letter. When a non-
letter appears: compare with current longest and shortest; reset word
Step 08: Print pangram/non-pangram. Print first occurring longest word. Print first occurring
shortest word.
Step 09: End.
Code:
import [Link];
class Pangram {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter the sentence: ");
String s = [Link]();
// Empty input check
if ([Link]() == 0) {
[Link]("INVALID INPUT");
return;
}
// Check ending punctuation
char last = [Link]([Link]() - 1);
if (".?!".indexOf(last) == -1) {
[Link]("INVALID INPUT");
return;
}

Page | 194
// Validate characters (only letters and spaces allowed)
for (int i = 0; i < [Link]() - 1; i++) {
char ch = [Link](i);
if (![Link](ch) && ch != ' ') {
[Link]("INVALID INPUT");
return;
}
}
// ------------ PANGRAM CHECK ------------
boolean isPangram = true;
for (char ch = 'a'; ch <= 'z'; ch++) {
boolean found = false;
for (int i = 0; i < [Link](); i++) {
if ([Link]([Link](i)) == ch) {
found = true;
break;
}
}
if (!found) {
isPangram = false;
break;
}
}
if (isPangram)
[Link]("IT IS A PANGRAM");
else
[Link]("IT IS NOT A PANGRAM");
// ------------ LONGEST & SHORTEST WORDS ------------
String longest = "";
String shortest = "";
String word = "";
for (int i = 0; i < [Link]() - 1; i++) {
char ch = [Link](i);
if ([Link](ch)) {
word += ch;
} else { // space encountered
if ([Link]() > 0) {
if ([Link]() == 0 || [Link]() > [Link]())
longest = new String(word);
if ([Link]() == 0 || [Link]() < [Link]())
shortest = new String(word);
}
word = "";
}
}
// Last word before punctuation

Page | 195
if ([Link]() > 0) {
if ([Link]() == 0 || [Link]() > [Link]())
longest = new String(word);
if ([Link]() == 0 || [Link]() < [Link]())
shortest = new String(word);
}
[Link]("LONGEST WORD: " + longest);
[Link]("SHORTEST WORD: " + shortest);
}
}
Output:

Page | 196
Program 07: Key pad
Most (not all) cell phone keypads look like the following arrangement (the letters are above
the respective number):
Most (not all) cell phone keypads look like the following arrangement (the letters are above the
respective number):
For sending text/SMS, the common problem is the number of keystrokes to type a particular text.
For example, in the word “STOP”, there are a total of 9 keystrokes needed to type the word. You
need to press the key 7 four times, the key 8 once, the key 6 three times and the key 7 once to get
it.
Develop a program code to find the number of keystrokes needed to type the text.
For this problem, accept just one word without any punctuation marks, numbers or whitespaces
and the text message would consist of just 1 word.
For sending text/SMS, the common problem is the number of keystrokes to type a particular
text.
For example, in the word “STOP”, there are a total of 9 keystrokes needed to type the word.
You need to press the key 7 four times, the key 8 once, the key 6 three times and the key 7
once to get it.
Develop a program code to find the number of keystrokes needed to type the text.
For this problem, accept just one word without any punctuation marks, numbers or
whitespaces and the text message would consist of just 1 word.
Algorithm:
Step 01: Start
Step 02: Input the word
Step 03: Convert the word to uppercase
Step 04: Set count = 0
Step 05: Repeat for every character in the word
Step 06: If the character is not a letter, print INVALID ENTRY and stop
Step 07: If the character is in "ADGJMPTW", add 1 to count
Step 08: Else if it is in "BEHKNQUX", add 2 to count
Step 09: Else if it is in "CFILORVY", add 3 to count
Step 10: Else add 4 to count
Step 11: After the loop ends, print Number of keystrokes = count
Step 12: Stop
Code:
import [Link];
class Keypad {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter the word: ");
String word = [Link]().toUpperCase();
int count = 0;
// Validate: Only letters allowed
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (![Link](ch)) {
[Link]("INVALID ENTRY");
Page | 197
return;
}
// Classic mobile keypad groupings
if ("ABC".indexOf(ch) >= 0)
count += (ch - 'A') + 1; // A=1, B=2, C=3
else if ("DEF".indexOf(ch) >= 0)
count += (ch - 'D') + 1; // D=1, E=2, F=3
else if ("GHI".indexOf(ch) >= 0)
count += (ch - 'G') + 1;
else if ("JKL".indexOf(ch) >= 0)
count += (ch - 'J') + 1;
else if ("MNO".indexOf(ch) >= 0)
count += (ch - 'M') + 1;
else if ("PQRS".indexOf(ch) >= 0)
count += (ch - 'P') + 1; // P=1, Q=2, R=3, S=4
else if ("TUV".indexOf(ch) >= 0)
count += (ch - 'T') + 1;
else if ("WXYZ".indexOf(ch) >= 0)
count += (ch - 'W') + 1;
}
[Link]("Number of keystrokes = " + count);
}
}
Output:

Page | 198
Program 08: Anagram String
Write a program to check if a given string is an Anagram of another string. Two strings are
anagrams if they can be rearranged to form the same thing. For example, “listen” and “silent”
are anagrams.
Accept two strings from the user and check if they are anagrams of each other. Ensure that the
comparison is case-sensitive and ignores spaces. Display an appropriate message based on
whether they are anagrams or not. If any of the strings contain invalid characters (e.g.,
numbers or special characters), generate an error message.
Algorithm:
Step 01: Start
Step 02: Input the first string
Step 03: Input the second string
Step 04: Convert both strings to uppercase
Step 05: Check each string for validity
Step 06: If any character is not a letter or space, display
"INVALID CHARACTERS IN STRING. INVALID INPUT" and stop
Step 07: Remove all spaces from both strings
Step 08: Repeat until the first string becomes empty
Step 09: Take the first character of string A
Step 10: Remove all occurrences of that character from A
Step 11: Remove all occurrences of that character from B
Step 12: If the lengths of A and B become unequal, they are not anagrams
Step 13: After loop ends, if lengths stayed equal, strings are anagrams
Step 14: Display appropriate message
Step 15: Stop
Code:
import [Link];
class Anagrams{
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Enter first string: ");
String a = [Link]().toUpperCase();
[Link]("Enter second string: ");
String b = [Link]().toUpperCase();
if(!valid(a) || !valid(b)){
[Link]("INVALID CHARACTERS IN STRING. INVALID INPUT");
return;
}
a = removeSpaces(a);
b = removeSpaces(b);
boolean status = true;
while([Link]() > 0){
String x = "" + [Link](0);
a = [Link](x, "");
b = [Link](x, "");

Page | 199
if([Link]() != [Link]()){
status = false;
break;
}
}
if(status)
[Link]("STRINGS ARE ANAGRAMS");
else
[Link]("STRINGS ARE NOT ANAGRAMS");
}
public static boolean valid(String s){
for(int i = 0; i < [Link](); i++){
char ch = [Link](i);

if(![Link](ch) && ![Link](ch))


return false;
}
return true;
}
public static String removeSpaces(String s){
String str = "";
for(int i = 0; i < [Link](); i++){
if(![Link]([Link](i)))
str += [Link](i);
}
return str;
}
}
Output:

Page | 200
Program 09: Mask String
Given are two strings, input string and a mask string that remove all the characters of the mask
string from the original string.
Example:
INPUT:
ORIGINAL STRING: communication
MASK STRING: mont
OUTPUT: cuicai
A class StringOp is defined as follows to perform above operation.
Some of the members of the class are given below:
Class name: StringOp
Data members/instance variables:
str: to store the original string
msk: to store the mask string
nstr: to store the resultant string
Methods/Member functions:
StringOp(): default constructor to initialize the data members with legal initial values
void accept(): to accept the original string str and the mask string msk in lowercase
void form(): to form the new string nstr after removal of characters present in mask string from
the original string.
void display(): to display the original string nstr and the newly formed string nstr
Specify the class StringOp giving details of the constructor, void accept(), void form() and
void display(). Define a main() function to create an object and call all the functions
accordingly to enable the task.
Algorithm:
Step 01: Start
Step 02: Create an object of class StringOp
Step 03: In accept(), input the original string in lowercase
Step 04: Input the mask string in lowercase
Step 05: In form(), start with an empty resultant string nstr
Step 06: For every character in the original string
Step 07: Check if the character exists in the mask string
Step 08: If it does NOT exist, append it to nstr
Step 09: After scanning full string, nstr is formed
Step 10: In display(), print the original string and the new string
Step 11: Stop
Code:
import [Link];
class StringOp{
String str;
String msk;
String nstr;
public StringOp(){
str = new String();
msk = new String();

Page | 201
nstr = new String();
}
public void accept(){
Scanner in = new Scanner([Link]);
[Link]("ORIGINAL STRING: ");
str = [Link]().toLowerCase();
[Link]("MASK STRING: ");
msk = [Link]().toLowerCase();
}
public void form(){
for(int i = 0; i < [Link](); i++){
char ch = [Link](i);
if([Link](ch) == -1)
nstr += ch;
}
}
public void display(){
[Link]("ORIGINAL STRING: " + str);
[Link]("NEWLY FORMED STRING: " + nstr);
}
public static void main(String[] args){
StringOp obj = new StringOp();
[Link]();
[Link]();
[Link]();
}
}
Output:

Page | 202
Program 10: Snowball String
A snowball string is a sentence where each word is arranged in ascending order of their length
and is also consecutive.
For example “I am the Lord” is a snowball string as
Length of word ‘I’ is 1
Length of word ‘am’ is 2
Length of word ‘the’ is 3
Length of word ‘Lord’ is 4
The length of each word is one more than the previous word. Hence they are consecutive and
in ascending order.
Write a program to enter any sentence and check if it is a snowball string or not. The words in
the sentence may be separated by one or more spaces and terminated by ‘.’ or ‘?’ only. The
program will generate appropriate error message for any other terminating character.
Algorithm:
Step 01: Start
Step 02: Input the sentence
Step 03: Extract the last character of the sentence
Step 04: If the last character is not . or ?, print
“INCORRECT TERMINATING CHARACTER. INVALID INPUT” and stop
Step 05: Initialise len = 0 and an empty string word
Step 06: For each character in the sentence
Step 07: If the character is a letter or digit, add it to word
Step 08: Else (space or punctuation):
Step 09: If word is not empty
Step 10: If len == 0, set len = [Link]()
Step 11: Else if [Link]() != len + 1, set status = false
Step 12: Else update len = [Link]()
Step 13: Set word = ""
Step 14: After loop ends, evaluate status
Step 15: If status = true, print “IT IS A SNOWBALL STRING”
Step 16: Else print “IT IS NOT A SNOWBALL STRING”
Step 17: Stop
Code:
import [Link];
class Snowball{
public static void main(String[] args){
Scanner in = new Scanner([Link]);
[Link]("Enter a sentence: ");
String s = [Link]();
char last = [Link]([Link]() - 1);
if(last != '.' && last != '?'){
[Link]("INCORRECT TERMINATING CHARACTER. INVALID
INPUT");
return;
}

Page | 203
int len = 0;
String word = "";
boolean status = true;
for(int i = 0; i < [Link](); i++){
char ch = [Link](i);
if([Link](ch)){
word += ch;
}
else{
if([Link]() > 0){
if(len == 0)
len = [Link]();
else if([Link]() != len + 1){
status = false;
break;
}
else
len = [Link]();
}
word = "";
}
}
if(status)
[Link]("IT IS A SNOWBALL STRING");
else
[Link]("IT IS NOT A SNOWBALL STRING");
}
}
Output:

Page | 204
Page | 205
import [Link].*;
class rotate_word
{
String st;
int n;
static Scanner obj=new Scanner([Link]);
rotate_word()
{
st="";n=0;
}
void accept()
{
[Link]("Enter a string");
st=[Link]();
[Link]("Enter the number of rotations to be made:");
n=[Link]();
}
void ro()
{
String st1=[Link](n);
String st2=[Link](0,n);
[Link]("New string is: "+st1+st2);
}
void or()
{
String s="";
for(int i=0;i<[Link]();i++)
{
s=[Link](i)+s;
}
String st1=[Link]([Link]()-n);
String st2=[Link](0,[Link]()-n);
[Link]("New string is: "+st1+st2);
}
public static void main(String args[])
{
rotate_word ob=new rotate_word();
[Link]();
[Link]("MENU DRIVEN:");
[Link]("[Link] clockwise");
[Link]("[Link] anti-clockwise");
[Link]("Enter your choice");
int n=[Link]();
switch(n)
{

Page | 206
case 1:
[Link]();
break;
case 2:
[Link]();
break;
default:
[Link]("Invalid Input:");
}
}
}
import [Link].*;
class saddle
{
static saddle ob=new saddle();
int a[][]=new int[100][100],n,i,j;
int max[]=new int[100];
int min[]=new int[100];
void input()
{
Scanner obj=new Scanner([Link]);
[Link]("Enter the size of square array:");
n=[Link]();
[Link]("Enter the array elements:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=[Link]();
[Link]("The original array:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
[Link](a[i][j]+" ");
[Link]();
}
}
void maxrow()
{
int k=0,p=1000000;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
if(p > a[i][j])
p=a[i][j];
max[k]=p;
k++;
p=1000000;

Page | 207
}
}
void minrow()
{
int k=0,p=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
if(p < a[j][i])
p=a[j][i];
min[k]=p;
k++;
p=0;
}
}
void check()
{
[Link]("Maximums"+"\t"+"Minimums");
for(i=0;i<n;i++)
[Link](max[i]+"\t\t"+min[i]);
[Link]("Saddle points are:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(max[i] == min[j])
[Link](max[i]);
}
public static void main(String args[])
{
[Link]();
[Link]();
[Link]();
[Link]();
}
}
import [Link].*;
class prime_factors_of_a_number
{
public static void main(String args[])
{
Scanner obj=new Scanner([Link]);
[Link]("Enter a number");
int n=[Link]();
int i,c=0,k=0,a=0;
for(i=1;i<=n;i++)
{
if(n%i==0)

Page | 208
c++;
}
if(c==2)
[Link]("Entered number itself is Prime number");
else
{
[Link]("Prime factors of the number are:");
for(i=1;i<=n;i++)
{
if(n%i==0)
{
a=i;
for(int j=1;j<=a;j++)
{
if(a%j==0)
k++;
}
if(k==2)
[Link](a);
k=0;
}
}
}
}
}
quiz checker for mcq
import [Link].*;
class q2_2016
{
public static void main(String args[])
{
Scanner obj=new Scanner([Link]);
[Link]("Enter 'N' number of participants:");
int n=[Link]();
char a[][]=new char[n][5];
char b[]=new char[5];
int i,j,k=0,z=0,m=0;
for(i=0;i<n;i++)
{
[Link]("Enter all answers of participant "+(i+1)+" ");
for(j=0;j<5;j++)
a[i][j]=[Link]([Link]().charAt(0));
}
[Link]("Enter the key:");
for(i=0;i<5;i++)
b[i]=[Link]([Link]().charAt(0));

Page | 209
int c[]=new int[n];
for(i=0;i<n;i++)
for(j=0;j<5;j++)
if(a[i][j]==b[j])
c[i]++;
for(i=0;i<n;i++)
{
[Link]("Score of Participant "+(i+1)+" is:"+c[i]);
m=c[0];
if(m<c[i])
{
m=c[i];
z=i;
}
}
[Link]("Highest score is of participant:"+(z+1));
}
}

Page | 210

Common questions

Powered by AI

The algorithm verifies a Dudeney number by calculating the sum of its digits (using a recursive function sumDigits). It then checks if the cube of this sum equals the number itself. If they match, the number is a Dudeney number .

Cyclic shifting of rows is performed by moving each row one position down and moving the last row to the top cyclically. For columns, each column is shifted one position to the right, with the last column moving to the first position, repeating the process for each shift .

The program transposes a matrix by interchanging its rows and columns, essentially printing elements at a[j][i] instead of a[i][j] for each element in the matrix .

The program checks if the sentence's terminating character is either '.' or '?'. If it is not, the input is considered invalid for snowball string determination .

The recursive strategy calculates the sum of the squares of the digits by iteratively adding (x%10)*(x%10) to the sum for each digit, checking if the resulting sum eventually equals 1, which would make the number a Happy number .

The program determines if a sentence is a palindrome by cleaning the input to remove non-alphabetic characters and spaces, then it compares characters one-by-one from start and end towards the center. If all corresponding characters match, it is a palindrome .

The matrix is rotated by copying original elements to new positions based on calculated indices: a 90° rotation uses index mapping a[j][n-1-i], 180° uses a[n-1-i][n-1-j], and 270° uses a[n-1-j][i], effectively rotating the matrix as desired .

The method checks for a pangram by verifying the presence of each letter from 'a' to 'z' within the sentence, ignoring case. If every letter is found at least once, the sentence is a pangram .

To determine if a number is Perfect, the algorithm uses a recursive function sumoffactors that calculates the sum of all factors of the number (excluding the number itself). If the sum equals the original number, it is a Perfect number .

A Disarium number is determined by summing the digits of the number raised to the power of their respective positions (using a recursive function sumofdigits), then comparing the result with the original number. If they are equal, the number is a Disarium number .

You might also like