0% found this document useful (0 votes)
77 views82 pages

Computer 2024-2025

Uploaded by

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

Computer 2024-2025

Uploaded by

prashantnagarf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Acknowledgment

I would like to express my sincere gratitude to all those who have contributed to
the successful completion of this computer project.

Firstly, I am deeply thankful to Megha ma'am, my project supervisor, for their


invaluable guidance, continuous support, and encouragement throughout the
duration of this project. Their expertise and constructive feedback have been
instrumental in shaping this work.

My heartfelt thanks go to my family and friends for their unwavering support and
understanding during this period. Their motivation and patience have been a
source of strength for me.

Lastly, I am grateful to all the authors and researchers whose works I have
referred to and learned from. Their contributions have significantly enriched my
knowledge and understanding.

Thank you all for your support and encouragement.

1
INDEX

Sr. Title Page


no. no.
Acknowledgment 1
Index 2
Introduction 3
1 Fill Square Matrix in Circular Fashion 4- 7
2 Fill 2D Array with First 'm×n' Prime Numbers 7-10
3 Sum of Rows and Columns in 2D Array 10-14
4 Check Wondrous Square and Find Primes 14-22
5 Sort Words in Sentence Alphabetically 22-25
6 Fill 2D Array with First (m×n) Composite Numbers 25-29
7 Check for Magic String 29-31
8 Sort Array with Odd Numbers Followed by Even Numbers 31-34
9 Rearrange Uppercase Letters Before Lowercase Letters 34-37
10 Check for Sphenic Number 37-41
11 Sum of Boundary Elements in 2D Array 41-45
12 Remove Duplicates in Sorted Array 45-48
13 Modify String with Second Next ASCII Letters 48-51
14 Mirror Image of Matrix 51-55
15 Move Uppercase Letters to Right Side in Array 55-59
16 Decode String with Circular Code 59-63
17 Find Consecutive Natural Number Combinations 63-66
18 Generate Lucky Numbers Less Than Given Number 66-69
19 Find Day of Week for Given Date 69-74
20 Find Saddle Point and Sort Principal Diagonal in Matrix 74-80
Conclusion 81
Bibliography 82

2
INTRODUCTION

This project showcases a diverse collection of Java programs designed to address


various aspects of array and matrix manipulation, string processing, and number
theory. The programs involve creating and filling matrices with specific patterns
and numbers, such as circular arrangements, prime and composite numbers, and
summing rows and columns in matrices. Additionally, the project includes
identifying special matrix properties like wondrous squares and saddle points, as
well as sorting words alphabetically and rearranging characters within strings.
Each program is carefully crafted to demonstrate different techniques and
methods, allowing for a deeper understanding of how Java can be used to solve
complex problems.

Further, the project features programs that check for consecutive letters in strings,
sort numbers by parity, identify Sphenic numbers, and calculate the sum of
boundary elements in matrices. Other programs focus on removing duplicates
from arrays, modifying strings based on ASCII values, and generating mirror
images of matrices. By exploring these various tasks, the project emphasizes the
importance of understanding and applying key concepts in Java programming,
such as nested loops, condition checking, array manipulation, and algorithm
implementation. This comprehensive approach not only enhances computational
problem-solving skills but also prepares one for tackling a wide range of
programming challenges. Through this project, the versatility and power of Java
are highlighted, demonstrating its capability to handle different types of data and
operations efficiently.

3
COMPUTER PROJECT
1.A square matrix is matrix in which the number of rows equals the
number of columns. Thus, a matrix of order n*n is called a square
matrix. Write a program in Java to create a double dimensional array of
size n×n matrix form and fill the cells of the matrix in a circular fashion
(clockwise) with natural numbers from 1to n2, taking n as an input.
Input n should be an odd natural number and filling of the elements
should start from the central cell.

For example,
if n=5, then n2=25, then the array is filled as:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13

Ans) import java.util.Scanner;

public class CircularMatrix {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd natural number n: ");
int n = sc.nextInt();

if (n % 2 == 0 || n <= 0) {
System.out.println("Please enter a valid odd natural number.");
return;
}

int[][] matrix = new int[n][n];


fillCircularMatrix(matrix, n);
printMatrix(matrix, n);
}

public static void fillCircularMatrix(int[][] matrix, int n) {


4
int value = 1;
int x = n / 2, y = n / 2;
int length = 1;

matrix[x][y] = value++;

while (length < n) {


// Move right
for (int i = 0; i < length; i++) {
y++;
matrix[x][y] = value++;
}
// Move down
for (int i = 0; i < length; i++) {
x++;
matrix[x][y] = value++;
}
length++;
// Move left
for (int i = 0; i < length; i++) {
y--;
matrix[x][y] = value++;
}
// Move up
for (int i = 0; i < length; i++) {
x--;
matrix[x][y] = value++;
}
length++;
}

// Final right move to fill the last row


for (int i = 0; i < length - 1; i++) {
y++;
matrix[x][y] = value++;
5
}
}

public static void printMatrix(int[][] matrix, int n) {


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

Output:

Variable description:
Variable data type description
sc Scanner Used to read input from
the console
n int Represents the odd
natural number entered
by the user
matrix int[][] 2D array used to store
6
the circular matrix
value int Counter used to fill the
matrix with increasing
integers
x int Current row position in
the matrix
y int Current column position
in the matrix
length int Length of the current
spiral arm being filled in
the matrix

Algorithm:
1. Initialize a `Scanner` object to read user input.
2. Prompt the user to enter an odd natural number `n`.
3. Read the integer `n` from the user.
4. Check if `n` is an odd natural number (i.e., `n > 0` and `n` is not divisible
by 2). If not, print an error message and terminate the program.
5. Initialize a 2D array `matrix` of size `n x n`.
6. Call the `fillCircularMatrix` method to fill the matrix in a circular pattern:
- Initialize variables: `value` to 1, `x` and `y` to `n / 2` (the center of the
matrix), and `length` to 1.
- Set `matrix[x][y]` to `value` and increment `value`.
- While `length` is less than `n`:
- Move right by `length` steps, filling in the matrix.
- Move down by `length` steps, filling in the matrix.
- Increment `length`.
- Move left by `length` steps, filling in the matrix.
- Move up by `length` steps, filling in the matrix.
- Increment `length`.
- Perform a final move right by `length - 1` steps to fill the last row.
7. Call the `printMatrix` method to print the matrix:
- Loop through each element in the matrix and print it with tab
separation for better readability.

2.Write a program in Java to fill a 2D array with first ‘m×n’ prime numbers,
where ‘m’ is the number of rows and ‘n’ is the number of columns.

7
For example,
If rows=4 and columns=5 them the result should be:

2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71

Ans) import java.util.Scanner;

public class PrimeMatrix {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows (m): ");
int m = sc.nextInt();
System.out.print("Enter the number of columns (n): ");
int n = sc.nextInt();

int[][] matrix = new int[m][n];


fillPrimeMatrix(matrix, m, n);
printMatrix(matrix, m, n);
}

public static void fillPrimeMatrix(int[][] matrix, int m, int n) {


int count = 0;
int num = 2; // First prime number

while (count < m * n) {


if (isPrime(num)) {
matrix[count / n][count % n] = num;
count++;
}
num++;
}
}

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

public static void printMatrix(int[][] matrix, int m, int n) {


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
}

Output:

Variable data type description:


9
variable data type description
sc Scanner Used to read input from
the console
m int Represents the number
of rows in the matrix
n int Represents the number
of columns in the matrix
matrix int[][] 2D array used to
store the prime numbers
in a matrix format
count int Counter used to keep
track of the number of
prime numbers placed in
the matrix
num int Curent number being
check for primality

Algorithm:
1. Initialize a `Scanner` object to read user input.
2. Prompt the user to enter the number of rows (`m`) and columns (`n`).
3. Read the integers `m` and `n` from the user.
4. Initialize a 2D array `matrix` of size `m x n`.
5. Call the `fillPrimeMatrix` method to fill the matrix with prime numbers:
- Initialize variables: `count` to 0 and `num` to 2 (the first prime number).
- While `count` is less than `m * n`:
- Check if `num` is prime using the `isPrime` method.
- If `num` is prime, place it in the matrix at position `[count / n][count % n]` and
increment `count`.
- Increment `num` to check the next number.
6. The `isPrime` method checks if a number is prime:
- If the number is less than 2, return `false`.
- Loop from 2 to the square root of the number and check if it is divisible by any
number in this range.
- If it is divisible, return `false`; otherwise, return `true`.
7. Call the `printMatrix` method to print the matrix:
- Loop through each element in the matrix and print it with tab separation for
better readability.

3. Write a program in Java to create a double dimensional array of size n×m.


10
Input the numbers in first (n-1)×(m-1) cells. Find and place the sum of
each row and column in corresponding cells of last column and last row
respectively. Finally, display the array elements along the sum of rows
and columns.
Sample Input
10 15 16 18
15 14 12 11
11 12 16 17
12 10 14 16

Sample Output
10 15 16 18 59
15 14 12 11 52
11 12 16 17 56
12 10 14 16 52
48 51 58 62

Ans) import java.util.Scanner;

public class SumMatrix {


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

System.out.print("Enter the number of rows (n): ");


int n = sc.nextInt();
System.out.print("Enter the number of columns (m): ");
int m = sc.nextInt();

int[][] matrix = new int[n][m];

System.out.println("Enter the elements for the matrix:");


for (int i = 0; i < n - 1; i++) {
11
for (int j = 0; j < m - 1; j++) {
matrix[i][j] = sc.nextInt();
}
}

// Calculate row sums and column sums


for (int i = 0; i < n - 1; i++) {
int rowSum = 0;
for (int j = 0; j < m - 1; j++) {
rowSum += matrix[i][j];
}
matrix[i][m - 1] = rowSum;
}

for (int j = 0; j < m - 1; j++) {


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

// Calculate the total sum for the last cell


int totalSum = 0;
for (int i = 0; i < n - 1; i++) {
totalSum += matrix[i][m - 1];
}
matrix[n - 1][m - 1] = totalSum;

// Print the matrix


System.out.println("The matrix with row and column sums is:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(matrix[i][j] + "\t");
}
12
System.out.println();
}
}
}

Output:

Variable data type description:


variable data type description
sc Scanner Used to read input from
the console
n int Represents the number
of rows in the matrix
m int Represents the number
of columns in the matrix
matrix int[][] 2D array used to store
the elements and sums in
the matrix
rowSum int Stores the sum of
elements in the current
row
colSum int Stores the sum of
elements in the current
13
column
totalSum int Stores the total sum of
all row sums

Algorithm:
1. Initialize a `Scanner` object to read user input.
2. Prompt the user to enter the number of rows (`n`) and columns (`m`).
3. Read the integers `n` and `m` from the user.
4. Initialize a 2D array `matrix` of size `n x m`.
5. Prompt the user to enter the elements for the matrix:
- Use nested loops to read the matrix elements from the user, filling `matrix[i][j]`.
6. Calculate row sums:
- Loop through each row `i`.
- Initialize `rowSum` to 0.
- For each row, loop through columns `j` and add the elements to `rowSum.
- Store `rowSum` in `matrix[i][m - 1]` (last column of the current row).
7. Calculate column sums:
- Loop through each column `j`.
- Initialize `colSum` to 0.
- For each column, loop through rows `i` and add the elements to `colSum.
- Store `colSum` in `matrix[n - 1][j]` (last row of the current column).
8. Calculate the total sum for the last cell:
- Initialize `totalSum` to 0.
- Loop through each row and add the row sums to `totalSum.
- Store `totalSum` in `matrix[n - 1][m - 1]` (last cell).
9. Print the matrix:
- Use nested loops to print each element in the matrix with tab separation for
better readability.

4.A wondrous square is an n by n grid which fulfill the following


conditions:
(i) It contains integers from 1 to n2, where each integer appears only
once.
(ii) The sum of integers in any row or column must add up to
0.5×n×(n2+1).

14
For example,
The following grid is a wondrous square where the sum of each row or
column is 65 when n=5.

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Write a program in Java to read n (2<=n<=10) and the values stored in


these n by n cells and output if the grid represents a wondrous square.
Also output all the prime numbers in the grid along with their row index and
column index as shown n the output. A natural number is said to be prime if
it has exactly two divisors. For example, 2,3,5,7,11… . The first element of
the given grid i.e. 17 is stored at row index 0 and column index 0 and the
next element in the row i.e. 24 is stored at row index 0 and column index 1.

Test your program for the following data and some random data:
Input:
n=4

16 15 1 2
6 4 10 14
9 8 12 5
3 7 11 1
Output:
Yes, it represents a wondrous square.
Prime Row Index Column Index
2 0 3

15
3 3 0
5 2 3
7 3 1
11 3 2
13 3 3

Input:
n=3
1 2 4
3 7 5
8 9 6

Output:
Not a wondrous square
Prime Row Index Column Index
2 0 1
3 1 0
5 1 2
7 1 1
Output:
Not a wondrous square

Input:
n=2

2 3
3 2
Output:
Not a wondrous square

Prime Row Index Column Index


2 0 0
2 1 1

16
3 0 1
3 1 0

Ans) import java.util.Scanner;

public class WondrousSquare


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();

if (n < 2 || n > 10) {


System.out.println("Invalid value of n!");
return;
}

int a[][] = new int[n][n];

System.out.println("Enter elements of the matrix: ");


for (int i = 0; i < n; i++) {
System.out.println("Enter Row "+ (i+1) + " :");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}

System.out.println("The Matrix is:");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}

//Check Wondrous
17
int nSq = n * n;
double validSum = 0.5 * n * (nSq + 1);
boolean wondrous = isWondrous(a);

if (wondrous) {
System.out.println("Yes, it represents a wondrous square");
}
else {
System.out.println("Not a wondrous square");
}

//Print Prime Numbers


printPrime(a);
}

public static boolean isWondrous(int arr[][]) {


int n = arr.length;
int nSq = n * n;
double validSum = 0.5 * n * (nSq + 1);

/*
* seenArr is used to check that
* numbers are not repeated
*/
boolean seenArr[] = new boolean[nSq];

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

int rSum = 0, cSum = 0;

for (int j = 0; j < n; j++) {


if (arr[i][j] < 1 || arr[i][j] > nSq) {
return false;
}

//Number is not distinct

18
if (seenArr[arr[i][j] - 1]) {
return false;
}

seenArr[arr[i][j] - 1] = true;

rSum += arr[i][j];
cSum += arr[j][i];
}

if (rSum != validSum || cSum != validSum) {


return false;
}
}

return true;
}

public static void printPrime(int arr[][]) {

int n = arr.length;

System.out.println("Prime\tRow Index\tColumn Index");

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


for (int j = 0; j < n; j++) {
if (isPrime(arr[i][j])) {
System.out.println(arr[i][j] + "\t" + i + "\t\t" + j);
}
}
}
}

public static boolean isPrime(int num) {


int c = 0;

19
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}

return c == 2;
}
}

Output:

20
Variable data type description:
variable data type description
sc Scanner Used to read input from
the console
n int Represents the size of
the matrix (n x n)
a int[][] 2D array used to store
the elements of the
matrix
nSq int Represents the square of
`n` (n * n)
validSum double Represents the expected
sum for each row,
column, and diagonal in a
wondrous square
wondrous boolean Indicates whether the
matrix is a wondrous
square or not

Algorithm:
1. Initialize a `Scanner` object to read user input.
2. Prompt the user to enter the size of the matrix (`n`).
3. Check if `n` is less than 2 or greater than 10; if so, print an error message and
return.
4. Initialize a 2D array `a` of size `n x n`.
5. Prompt the user to enter the elements of the matrix:
- Use nested loops to read the matrix elements from the user, filling `a[i][j]`.
6. Print the matrix:
- Use nested loops to print each element in the matrix with tab separation.
7. Calculate the expected sum (`validSum`) for a wondrous square.
8. Call the `isWondrous` method to check if the matrix is a wondrous square:
- Initialize a boolean array `seenArr` to track distinct numbers.
- Loop through each row and column to calculate sums and check for validity.
- Return `false` if any conditions for a wondrous square are not met; otherwise,
return `true`.
9. Based on the result of `isWondrous`, print whether the matrix represents a
wondrous square or not.
10. Call the `printPrime` method to print prime numbers from the matrix:
21
- Use nested loops to check each element for primality and print it along with
its row and column indices.
11. Define the `isPrime` method to check if a number is prime:
- Count the number of divisors of the number; return `true` if there are exactly
two divisors (1 and the number itself).

5.A class SortALpha has been defined to sort the words in the sentence in
alphabetical order.

Input:
THE SKY IS BLUE
Output:
BLUE IS THE SKY

Class name: SortAlpha

Data Members/Instance Variables sent - to store a


sentence
m - integer to store the number of words in
sentence

Methods/Member Functions
SortAlpha() - default constructor to initialize
data members with legal initial values
void acceptsent() - to accept a sentence in
Uppercase void sort(SortAlpha P)-
sorts the words of the sentence of
object P in alphabetical order and
stores the sorted sentence in the
current object
void display() - display the original sentence along with
the sorted sentence by invoking the
method sort()

Specify the class SortAlpha giving details of the constructor(), void


acceptsent(), void sort(SortAlpha) and void display(). Define a main()
method to create an object and call the functions accordingly to enable
22
the task.
Ans) import java.util.Arrays;
import java.util.Scanner;

class SortAlpha {
// Data members/instance variables
private String sent;
private int m;

// Default constructor to initialize data members with legal initial values


public SortAlpha() {
this.sent = "";
this.m = 0;
}

// Method to accept a sentence in uppercase


public void acceptsent() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence in uppercase: ");
this.sent = sc.nextLine();
this.m = this.sent.split(" ").length;
}

// Method to sort the words of the sentence of object P in alphabetical order


// and store the sorted sentence in the current object
public void sort(SortAlpha P) {
String[] words = P.sent.split(" ");
Arrays.sort(words);
this.sent = String.join(" ", words);
this.m = words.length;
}

// Method to display the original sentence along with the sorted sentence
public void display(SortAlpha P) {
System.out.println("Original Sentence: " + P.sent);
System.out.println("Sorted Sentence: " + this.sent);
}

23
// Main method to create an object and call the functions accordingly to enable
the task
public static void main(String[] args) {
SortAlpha original = new SortAlpha();
original.acceptsent();

SortAlpha sorted = new SortAlpha();


sorted.sort(original);

sorted.display(original);
}
}

Output:

Variable data type decsription:


variable data type description
sent String Holds the input sentence
in uppercase
m int Represents the number
of words in the sentence

Algorithm:
1. Define the `SortAlpha` class with instance variables `sent` and `m`.
2. Implement a default constructor to initialize `sent` to an empty string and `m`
to 0.
3. Create the `acceptsent` method:
- Initialize a `Scanner` object to read input.
- Prompt the user to enter a sentence in uppercase and store it in `sent`.
24
- Update `m` with the number of words in `sent` by splitting it based on spaces.
4. Create the `sort` method:
- Accept a `SortAlpha` object `P` as a parameter.
- Split the sentence of object `P` into words and store them in an array.
- Sort the array of words alphabetically using `Arrays.sort()`.
- Join the sorted words back into a single string and assign it to `sent` of the
current object.
- Update `m` with the length of the sorted words array.
5. Create the `display` method:
- Accept a `SortAlpha` object `P` as a parameter.
- Print the original sentence from `P` and the sorted sentence from the current
object.
6. Implement the `main` method:
- Create an instance of `SortAlpha` named `original`.
- Call `acceptsent()` on `original` to get user input.
- Create another instance of `SortAlpha` named `sorted`.
- Call `sort()` on `sorted`, passing `original` as an argument.
- Call `display()` on `sorted`, passing `original` as an argument to show the
results.

6.A class Composite contains a two dimensional array of order [m×n]. the
maximum value possible for both ‘m’ and ‘n’ is 20. Design a class
Composite to fill the array with the first (m×n) composite numbers in
column wise.
[composite numbers are those which have more than two factors]
The details of the members of the class are given below:

Class name: Composite

Data Members/Instance Variables


arr[][]- integer array to store the composite numbers column
wise
m - integer to store the number of rows
n - integer to store the number of columns

Member Functions/Methods
Composite(int mm,int nn)- to initialize array to store the
composite numbers column wise
25
int isComposite(int p) - to return 1, if the number is
composite otherwise returns 0
void fill() - to fill the elements of the array with first (m×n)
composite numbers in column wise
void display() - to display the array in matrix form

Specify the class Composite, giving details of the constructor(int, int), int
is Composite(int), void fill(), vid display(). Define a main() function to
create an object of the class and call all the functions accordingly to
enable the task.

Ans) public class Composite {


private int[][] arr;
private int m, n;

// Constructor to initialize the array


public Composite(int mm, int nn) {
m = mm;
n = nn;
arr = new int[m][n];
}

// Method to check if a number is composite


public int isComposite(int p) {
if (p <= 3) return 0; // 0, 1, 2, and 3 are not composite numbers
for (int i = 2; i <= Math.sqrt(p); i++) {
if (p % i == 0) return 1;
}
return 0;
}

// Method to fill the array with composite numbers column-wise


public void fill() {
int count = 0;
int num = 4; // Starting from the first composite number
while (count < m * n) {
if (isComposite(num) == 1) {
int row = count % m;
26
int col = count / m;
arr[row][col] = num;
count++;
}
num++;
}
}

// Method to display the array in matrix form


public void display() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}

// Main method to demonstrate the class functionality


public static void main(String[] args) {
int m = 4; // Number of rows
int n = 5; // Number of columns

Composite composite = new Composite(m, n);


composite.fill();
System.out.println("The matrix filled with composite numbers:");
composite.display();
}
}

Output:

27
Variable data type description:
variable data type description
arr int[][] 2D array used
to store
composite
numbers
m int Represents the
number of rows
in the array
n int Represents the
number of
columns in the
array

Algorithm:
1. Define the `Composite` class with instance variables `arr`, `m`, and `n`.
2. Implement a constructor to initialize `m` and `n` and create a 2D array
`arr` of size `m x n`.
3. Create the `isComposite` method:
- Accept an integer `p` as a parameter.
- Return 0 if `p` is less than or equal to 3, as these numbers are not
composite.
- Loop from 2 to the square root of `p`:
- If `p` is divisible by `i`, return 1 (indicating `p` is composite).
- Return 0 if no divisors are found, indicating `p` is not composite.
4. Create the `fill` method:
- Initialize `count` to 0 and `num` to 4 (the first composite number).
- Use a while loop to continue until `count` reaches `m * n`:
- If `num` is composite (using `isComposite`), calculate the row and
column indices for the `arr` using `count`.
- Assign `num` to `arr[row][col]` and increment `count`.
- Increment `num` to check the next number.
5. Create the `display` method:
- Use nested loops to print each element of `arr` in matrix form with
tab separation.
6. Implement the `main` method:
- Define `m` and `n` for the number of rows and columns, respectively.
28
- Create an instance of `Composite`.
- Call the `fill` method to populate the array with composite numbers.
- Call the `display` method to print the matrix of composite numbers.

7.Write a program in Java to accept a word. Pass the word to a method


Magic(String word). It should check the presence of the consecutive
letters within the word. If two letters are consecutive at any position,
then it displays “It is a magic string” otherwise, “It is not a magic string”.

Input:
ABDOMEN
Output:
It is a magic string
Input:
COMPUTER
Output:
It is not a magic string
Ans) import java.util.Scanner;

public class MagicStringChecker


{
public void magic(String str) {

boolean isMagicStr = false;


String t = str.toUpperCase();
int len = t.length();

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


if (t.charAt(i) + 1 == t.charAt(i + 1)) {
isMagicStr = true;
break;
}
}

if (isMagicStr)
System.out.println("It is a magic string");
else
System.out.println("It is not a magic string");
29
}

public static void main(String args[]) {

Scanner in = new Scanner(System.in);


System.out.print("Enter word: ");
String word = in.nextLine();

MagicStringChecker obj = new MagicStringChecker();


obj.magic(word);
}
}

Output:

Variable data type description:


variable data type description
str String Input string to be
checked for being
a magic string
isMagicStr boolean Indicates whether
the string is
identified as a
magic string

30
t String Uppercase
version of the
input string for
comparison
len int Length of the
uppercase string
`t`

Algorithm:
1. Define the `MagicStringChecker` class.
2. Create the `magic` method:
- Accept a `String` parameter `str`.
- Initialize a boolean variable `isMagicStr` to `false`.
- Convert `str` to uppercase and store it in `t`.
- Get the length of `t` and store it in `len`.
3. Use a for loop to iterate through the characters of `t` from index 0 to `len
- 2`:
- Check if the ASCII value of the current character plus 1 equals the ASCII
value of the next character.
- If the condition is true, set `isMagicStr` to `true` and break the loop.
4. After the loop, check the value of `isMagicStr`:
- Print "It is a magic string" if `isMagicStr` is `true`.
- Print "It is not a magic string" if `isMagicStr` is `false`.
5. Implement the `main` method:
- Initialize a `Scanner` object to read user input.
- Prompt the user to enter a word and store it in `word`.
- Create an instance of `MagicStringChecker`.
- Call the `magic` method with `word` as an argument to check if it is a
magic string.

8.Write a program in Java to accept 10 numbers in a single dimensional


array. Pass the array to a method Arrange(int m[]) that sorts the
number (such that odd numbers are followed by even numbers) in an
ascending order.

Input:
14 24 54 34 33 65 78 59 22 12
Output:

31
33 65 59 14 24 54 34 78 22 12
Ans) import java.util.Arrays;
import java.util.Scanner;

public class ArrangeArray {


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

// Accept 10 numbers from the user


System.out.println("Enter 10 numbers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = sc.nextInt();
}

// Sort the array with the specified condition


Arrange(numbers);

// Display the sorted array


System.out.println("Sorted array (odd numbers followed by even numbers):");
for (int num : numbers) {
System.out.print(num + " ");
}
}

// Method to sort the array such that odd numbers are followed by even
numbers in ascending order
public static void Arrange(int m[]) {
// Separate odd and even numbers
int[] oddNumbers = Arrays.stream(m).filter(num -> num % 2 != 0).toArray();
int[] evenNumbers = Arrays.stream(m).filter(num -> num % 2 == 0).toArray();

// Sort odd and even numbers individually


Arrays.sort(oddNumbers);
Arrays.sort(evenNumbers);

32
// Combine sorted odd and even numbers back into the original array
int index = 0;
for (int num : oddNumbers) {
m[index++] = num;
}
for (int num : evenNumbers) {
m[index++] = num;
}
}
}

Output:

Variable data type description:


variable data type description
numbers int[] Array to store 10 integers
entered by the user
sc Scanner Scanner object used for
reading user input
oddNumbers int[] Array to hold the odd
numbers filtered from the
original array
evenNumbers int[] Array to hold the even
numbers filtered from the
original array
index int Index variable used to
track the position when
33
combining sorted arrays

Algorithm:
1. Define the `ArrangeArray` class.
2. Implement the `main` method:
- Create a `Scanner` object to read input.
- Initialize an integer array `numbers` of size 10.
- Prompt the user to enter 10 numbers and store them in the `numbers` array
using a loop.
3. Call the `Arrange` method, passing the `numbers` array as an argument to sort
it.
4. Print the sorted array with odd numbers followed by even numbers.
5. Define the `Arrange` method:
- Use the `Arrays.stream` method to filter and create an array `oddNumbers`
containing only the odd integers from the input array `m`.
- Similarly, create an array `evenNumbers` containing only the even integers.
- Sort both `oddNumbers` and `evenNumbers` using `Arrays.sort`.
- Initialize an `index` variable to 0 to keep track of where to place elements in
the original array `m`.
- Use a loop to copy sorted odd numbers back into `m`, updating `index`
accordingly.
- Use another loop to copy sorted even numbers back into `m`, continuing to
update `index`.

9.Write a program to input a string. Pass the string to a method that will
return a string having all the uppercase letters prior to the lowercase
letters of the original string. You must take acre that the order of the
letters should not change.

Input:
ComPanY
Output:
CPYoman

Ans) import java.util.Scanner;

public class RearrangeString {


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

// Accept a string from the user


System.out.print("Enter a string: ");
String input = sc.nextLine();

// Call the method to rearrange the string


String result = rearrange(input);

// Display the rearranged string


System.out.println("Rearranged string: " + result);
}

// Method to rearrange the string with uppercase letters before lowercase


letters
public static String rearrange(String str) {
StringBuilder upper = new StringBuilder();
StringBuilder lower = new StringBuilder();

// Iterate through the string and separate uppercase and lowercase letters
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
upper.append(c);
} else if (Character.isLowerCase(c)) {
lower.append(c);
}
}

// Combine the uppercase and lowercase letters


return upper.toString() + lower.toString();
}
}

35
Output:

Variable data type description:


variable data type description
sc Scanner Scanner object used for
reading user input
input String String entered by the
user to be rearranged
result String The rearranged string
with uppercase letters
before lowercase letters
upper StringBuilder StringBuilder to store
uppercase letters from
the input string
lower StringBuilder StringBuilder to store
lowercase letters from
the input string

Algorithm:
1. Define the `RearrangeString` class.
2. Implement the `main` method:
- Create a `Scanner` object to read input.
36
- Prompt the user to enter a string and store it in the `input` variable.
- Call the `rearrange` method, passing `input` as an argument, and store the
result in the `result` variable.
- Print the rearranged string.
3. Define the `rearrange` method:
- Accept a `String` parameter `str`.
- Initialize two `StringBuilder` objects: `upper` for uppercase letters and `lower`
for lowercase letters.
- Convert `str` to a character array and iterate through each character:
- If the character is uppercase, append it to `upper`.
- If the character is lowercase, append it to `lower`.
- Concatenate the contents of `upper` and `lower` and return the combined
string.

10.A Sphenic number is a positive integer which has exactly three prime
factors. The first few sphenic numbers are:
30, 42, 66. 70, 78, 102, 105, 110, 114 and so on.

Design a class Sphenic to check if a given number is a Sphenic number or


not. Specify the method Check(int n) that accepts a number from the
main() method. It displays all the prime factors. If it contains only three
prime factors then display ‘Sphenic Number’, otherwise, ‘Not a Sphenic
Number’.
Define the main() method to create an object and call the method
Check(int n) accordingly to enable the task.

Input:
30
Output:
Sphenic Number
Hint: 30 = 2×3×5
It is the product of three prime numbers
Input:
60
Not a Sphenic Number
Hint: 60 = 2×2×3×5
It doesn’t have exactly three prime factors
37
Ans) import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Sphenic {

// Method to check if a number is a Sphenic number


public void Check(int n) {
List<Integer> primeFactors = new ArrayList<>();
int originalNumber = n;

// Find prime factors


for (int i = 2; i <= Math.sqrt(n); i++) {
while (n % i == 0) {
// Add the prime factor only once
if (!primeFactors.contains(i)) {
primeFactors.add(i);
}
n /= i;
}
}
// If n is still greater than 1, then it is a prime factor
if (n > 1) {
primeFactors.add(n);
}

// Display prime factors


System.out.print("Prime factors: ");
for (int prime : primeFactors) {
System.out.print(prime + " ");
}
System.out.println();

// Check if it is a Sphenic number


38
if (primeFactors.size() == 3) {
System.out.println(originalNumber + " is a Sphenic Number.");
System.out.println("Hint: " + originalNumber + " = " +
primeFactorsToString(primeFactors));
System.out.println("It is the product of three prime numbers.");
} else {
System.out.println(originalNumber + " is Not a Sphenic Number.");
System.out.println("Hint: " + originalNumber + " has " + primeFactors.size()
+ " distinct prime factors.");
System.out.println("It doesn't have exactly three distinct prime factors.");
}
}

// Helper method to format the prime factors into a string


private String primeFactorsToString(List<Integer> primeFactors) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (int prime : primeFactors) {
if (count > 0) {
sb.append(" × ");
}
sb.append(prime);
count++;
}
return sb.toString();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Accepting input number


System.out.print("Enter a number: ");
int n = scanner.nextInt();

// Create an object of Sphenic and call Check method

39
Sphenic sphenic = new Sphenic();
sphenic.Check(n);
}
}

Output:

Variable data type description:


variable data type description
n int Number input by the
user to check if it is a
Sphenic number
originalNumber int The original value of `n`
for reference in output
messages
primeFactors List<Integer> List to store distinct
prime factors of the
number
scanner Scanner Scanner object used for
reading user input
prime int A variable used to iterate
through the list of prime
factors
sb StringBuilder StringBuilder used to
40
format the prime factors
into a string

Algorithm:
1. Define the `Sphenic` class.
2. Implement the `Check` method:
- Accept an integer parameter `n`.
- Initialize an `ArrayList` called `primeFactors` to store distinct prime factors.
- Store the original value of `n` in `originalNumber`.
- Use a loop to find prime factors:
- For each integer `i` from 2 to the square root of `n`, check if `n` is divisible by
`i`.
- If it is, add `i` to `primeFactors` if it’s not already present and divide `n` by `i`.
- If `n` is greater than 1 after the loop, add it to `primeFactors` as a prime factor.
- Print the distinct prime factors.
- Check if the size of `primeFactors` is exactly 3:
- If true, print that `originalNumber` is a Sphenic number along with a hint
showing its prime factorization.
- If false, print that it is not a Sphenic number and how many distinct prime
factors it has.
3. Implement the `primeFactorsToString` helper method:
- Accept a list of integers `primeFactors`.
- Use a `StringBuilder` to format the list into a multiplication string.
- Return the formatted string.
4. In the `main` method:
- Create a `Scanner` object to read input.
- Prompt the user to enter a number and read the input into `n`.
- Create an instance of `Sphenic` and call the `Check` method with `n`.

11.Write a program to create a double dimensional array of order [m]×[m]


to store integer numbers. Now, pass the array to a method Boundary() to
calculate and display the sum of boundary elements of the array.

Input:
Number of rows and columns = 4
Original matrix

41
11 14 15 9
12 20 10 8
6 18 16 4
5 22 20 3
Output:
Sum of boundary elements = 129

Ans) import java.util.Scanner;

public class BoundarySum {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input the order of the matrix
System.out.print("Enter the order of the matrix (m): ");
int m = sc.nextInt();

// Create a double dimensional array of order [m][m]


int[][] matrix = new int[m][m];

// Input the elements of the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}

// Display the original matrix


System.out.println("Original matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Calculate and display the sum of boundary elements


int sum = Boundary(matrix);
42
System.out.println("Sum of boundary elements = " + sum);
}

// Method to calculate the sum of boundary elements of the array


public static int Boundary(int[][] matrix) {
int m = matrix.length;
int sum = 0;

// Top boundary
for (int j = 0; j < m; j++) {
sum += matrix[0][j];
}

// Bottom boundary
for (int j = 0; j < m; j++) {
sum += matrix[m - 1][j];
}

// Left boundary (excluding corners)


for (int i = 1; i < m - 1; i++) {
sum += matrix[i][0];
}

// Right boundary (excluding corners)


for (int i = 1; i < m - 1; i++) {
sum += matrix[i][m - 1];
}

return sum;
}
}

Output:

43
Variable data type description:
variable data type description
m int The order of the
square matrix
matrix int[][] A two-
dimensional array
representing the
matrix
sc Scanner Scanner object
used for reading
user input
sum int Variable to hold
the sum of the
boundary
elements

Algorithm:
1. Define the `BoundarySum` class.
2. In the `main` method:
- Create a `Scanner` object to read input.
- Prompt the user to enter the order of the matrix (`m`).
- Initialize a two-dimensional array `matrix` of size `[m][m]`.
- Use nested loops to input the elements of the matrix from the user.
- Display the original matrix.
44
- Call the `Boundary` method to calculate the sum of boundary elements
and store the result in `sum`.
- Print the sum of boundary elements.
3. Implement the `Boundary` method:
- Accept a two-dimensional integer array `matrix`.
- Initialize `sum` to 0.
- Calculate the sum of the top boundary by iterating over the first row of the
matrix.
- Calculate the sum of the bottom boundary by iterating over the last row of
the matrix.
- Calculate the sum of the left boundary by iterating from the second row to
the second last row of the first column.
- Calculate the sum of the right boundary by iterating from the second row
to the second last row of the last column.
- Return the total sum.

12.Define a class Duplicate to pack the array containing 10 integers


(Packing means removing all duplicate elements from the sorted array).

For example,
If the given array has the following elements
1 2 3 3 4 4 4 5 6 6
The resultant array should contain each element only once. The output
should be
1 2 3 4 5 6

Now, pass the array to a method PackList() to remove the duplicates and
then display the resultant array.

Ans) import java.util.Arrays;


import java.util.Scanner;

public class Duplicate {


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

// Create an array to hold 10 integers


45
int[] array = new int[10];

// Input 10 integers into the array


System.out.println("Enter 10 sorted integers:");
for (int i = 0; i < 10; i++) {
array[i] = sc.nextInt();
}

// Call the method to remove duplicates


int[] packedArray = PackList(array);

// Display the resultant array


System.out.print("Resultant array without duplicates: ");
for (int num : packedArray) {
System.out.print(num + " ");
}
}

// Method to remove duplicates from the array


public static int[] PackList(int[] arr) {
int[] temp = new int[arr.length];
int j = 0;

// Traverse through the array and pack unique elements


for (int i = 0; i < arr.length; i++) {
// If current element is not equal to the previous one, store it
if (i == 0 || arr[i] != arr[i - 1]) {
temp[j++] = arr[i];
}
}

// Create a new array of the correct size to return


return Arrays.copyOf(temp, j);
}
}

Output:

46
variable data type description
array int[] An array to hold
10 sorted integers
sc Scanner Scanner object
used for reading
user input
packedArray int[] Array to hold the
resultant integers
without
duplicates
temp int[] Temporary array
to store unique
elements during
duplicate removal
j int Counter to keep
track of the
number of unique
elements

Algorithm:
1. Define the `Duplicate` class.
2. In the `main` method:

47
- Create a `Scanner` object to read input.
- Initialize an array `array` to hold 10 integers.
- Prompt the user to enter 10 sorted integers and fill the `array` using a
loop.
- Call the `PackList` method, passing the `array`, and store the result in
`packedArray`.
- Display the contents of `packedArray` without duplicates.
3. Implement the `PackList` method:
- Accept an integer array `arr`.
- Create a temporary array `temp` of the same length as `arr` to hold
unique elements.
- Initialize a counter `j` to zero.
- Traverse through `arr`, checking if the current element is different from
the previous one:
- If true, store the current element in `temp` and increment `j`.
- Return a new array that is a copy of `temp` with size `j`, representing
the unique elements.

13.Write a program to input a string str in mixed case. Pass the string to a
method Modify(String wrd) that replaces each letter of the original string
with the second next letter in the ASCII table. The replacement follows
the robin system (i.e. letter ‘b’ follows letter ‘z’)

For example, Input:


AbcD Output: CdeF Input: Xyz Output: Zab

Create an object in main() method and call the method Modify(String


wrd) accordingly to enable the task.

Ans) import java.util.Scanner;

public class StringModifier {


// Method to replace each letter with the second next letter in ASCII
public String Modify(String wrd) {
StringBuilder modifiedString = new StringBuilder();

for (char c : wrd.toCharArray()) {


48
// Check if the character is a letter
if (Character.isLetter(c)) {
// Determine the new character with wrapping
char newChar = (char) (c + 2);

// Wrap around if it exceeds 'z' or 'Z'


if (Character.isLowerCase(c) && newChar > 'z') {
newChar = (char) (newChar - 26);
} else if (Character.isUpperCase(c) && newChar > 'Z') {
newChar = (char) (newChar - 26);
}

modifiedString.append(newChar);
} else {
// If it's not a letter, append it as it is
modifiedString.append(c);
}
}

return modifiedString.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Create an object of StringModifier


StringModifier modifier = new StringModifier();

// Input the string from the user


System.out.print("Enter a string in mixed case: ");
String input = sc.nextLine();

// Call the Modify method to transform the string


String result = modifier.Modify(input);

// Display the modified string


System.out.println("Output: " + result);
}
49
}

Output:

Variable data type description:


Variable data type description
wrd String Input string to be
modified
modifiedString StringBuilder Stores the modified
string
c char Current character being
processed
newChar char Character after
modification
sc Scanner Scanner object for user
input
input String User input string
result String Final modified string
output

Algorithm:
1. Create a `StringBuilder` to hold the modified string.
2. Iterate over each character in the input string:
1. If the character is a letter, calculate the new character by adding 2 to its ASCII
value.
50
2. If the new character exceeds 'z' or 'Z', wrap around to the beginning of the
alphabet.
3. Append the new character to the `StringBuilder`.
4. If it's not a letter, append the original character.
3. Return the modified string from the `StringBuilder`.
4. In the `main` method, accept user input and display the modified string.

14.A class matrix_image is created with the following


details: Class name: matrix_image

Data Members/Instance variables


arr1[][], arr2[][]- double dimensional arrays of maximum size
15×15
m,n - integers to store number of rows and columns

Member Functions/Methods
matrix_image() - constructor to assign 0 to each
location of arrays arr1[][],
arr2[][] and also 0 to m and n
matrix_image(int mm, int nn)- constructor to assign mm to m
and nn to n as actual number of
rows and columns
void getmat() - to input the matrix arr1[][] of size
m×n
void mirror_image() - to create another matrix arr2[][]
of same size m,n such that
arr2[][] is the mirror image of
matrix arr1[][]
void show() - to display matrices arr1[][] and
arr2[][]

Input Matrix (arr1)


8 4 3
2 6 4
3 4 7

Output Matrix (arr2)


51
3 4 8
4 6 2
7 4 3

Specify the class matrix_image by giving details of constructors and all


functions.

Ans) import java.util.Scanner;

public class matrix_image {


// Data members
private double[][] arr1; // Original matrix
private double[][] arr2; // Mirror image matrix
private int m; // Number of rows
private int n; // Number of columns

// Default constructor
public matrix_image() {
arr1 = new double[15][15];
arr2 = new double[15][15];
m = 0;
n = 0;
}

// Constructor to initialize with actual dimensions


public matrix_image(int mm, int nn) {
m = mm;
n = nn;
arr1 = new double[m][n];
arr2 = new double[m][n];
}

// Method to input the matrix arr1


public void getmat() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter elements of the matrix of size " + m + "x" + n + ":");
52
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr1[i][j] = sc.nextDouble();
}
}
}

// Method to create the mirror image in arr2


public void mirror_image() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr2[i][j] = arr1[i][n - 1 - j]; // Mirror image logic
}
}
}

// Method to display both matrices


public void show() {
System.out.println("Input Matrix (arr1):");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}

System.out.println("Output Matrix (arr2):");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr2[i][j] + " ");
}
System.out.println();
}
}

// Main method to demonstrate functionality


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

// Input dimensions
System.out.print("Enter the number of rows (m): ");
int m = sc.nextInt();
System.out.print("Enter the number of columns (n): ");
int n = sc.nextInt();

// Create an instance of matrix_image


matrix_image matrix = new matrix_image(m, n);

// Get input for the matrix


matrix.getmat();

// Create the mirror image


matrix.mirror_image();

// Display both matrices


matrix.show();
}
}

Output:

54
Variable data type description:
Variable data type description
arr1 double[][] Original matrix
arr2 double[][] Mirror image matrix
m int Number of rows in the
matrix
n int Number of columns in
the matrix
sc Scanner Scanner object for user
input
mm int Parameter for the
number of rows in the
constructor
nn int Parameter for the
number of columns in the
constructor
i int Loop variable for rows
j int Loop variable for
columns

Algorithm:
1. Create two matrices: `arr1` for the original matrix and `arr2` for the mirror
image.
2. Initialize the matrix dimensions using the constructor.
3. Input elements into the original matrix `arr1` from user input.
4. Create the mirror image of `arr1` by reversing the columns into `arr2`.
5. Display both the original and the mirrored matrices to the user.
6. In the `main` method, prompt for the matrix dimensions, create an instance of
`matrix_image`, input the matrix, generate the mirror image, and display the
results.

15.Class chaarray contains an array of n characters (n<=100). You may


assume that the array contains only the letters of English alphabets.
Some of the members functions/methods of chaarray are given below:

Class name: chaarray

Data Members/Instance Variables


55
ch[] - array of characters
size - the size of the array of characters

Member Fucntions/Methods
chaarray() - constructor to assign instance variables to 0
or null
chaarray(char c[]) - constructor to assign character array c to
the instance variable
void displayarray() – to display the list of characters
void move() - to move all the uppercase letters to the
right side of the array without using any s
standard sorting technique

Input:
t D f s X v d
Output:
t d f s v X D

Specify the class chaarray giving the details of two constructors and the
functions void displayarray() and void move(). Create an object to call the
functions accordingly.

Ans) import java.util.Scanner;

public class chaarray {


// Data members
private char[] ch;
private int size;

// Default constructor
public chaarray() {
this.ch = new char[100]; // Initialize array with a max size of 100
this.size = 0;
}

// Constructor to assign character array c to the instance variable


public chaarray(char c[]) {
this.ch = new char[c.length];
56
this.size = c.length;
System.arraycopy(c, 0, this.ch, 0, c.length);
}

// Method to display the list of characters


public void displayarray() {
for (int i = 0; i < size; i++) {
System.out.print(ch[i] + " ");
}
System.out.println();
}
// Method to move all uppercase letters to the right side of the array
public void move() {
int j = size - 1; // Pointer for the end of the array
for (int i = size - 1; i >= 0; i--) {
if (Character.isLowerCase(ch[i])) {
// Move lowercase letters to the left
ch[j--] = ch[i];
}
}
// Fill remaining positions with uppercase letters
while (j >= 0) {
ch[j--] = ' '; // You can use any character or leave it as is
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Accepting input characters


System.out.println("Enter characters separated by space (type 'end' to
stop):");
String input = scanner.nextLine();
String[] inputChars = input.split(" ");

// Creating an object of chaarray with the input characters


chaarray arr = new chaarray(new char[inputChars.length]);
for (int i = 0; i < inputChars.length; i++) {
57
arr.ch[i] = inputChars[i].charAt(0); // Convert string to char
}
arr.size = inputChars.length;

// Display original array


System.out.println("Original array:");
arr.displayarray();

// Move uppercase letters to the right side


arr.move();

// Display modified array


System.out.println("Modified array after moving uppercase letters:");
arr.displayarray();

scanner.close();
}
}

Output:

Variable data type description:


Variable Data Type Description
ch char[] Array to hold characters
58
size int Current number of
characters in the array
scanner Scanner Scanner object for user
input
input String Input string from the
user
inputChars String[] Array of characters from
the input string
arr chaarray Instance of chaarray to
hold the characters

Algorithm:
1. Initialization: Create a character array `ch` and initialize it with a maximum size
of 100.
2. Input: Accept characters from the user, allowing multiple characters separated
by spaces.
3. Storage: Store the input characters into the array `ch` and update the `size`.
4. Display Original Array: Print the original array of characters.
5. Move Functionality:
- Start from the end of the array and move lowercase characters to the left side.
- Fill the remaining right side of the array with spaces.
6. Display Modified Arra: Print the modified array with lowercase letters on the
left and spaces filling the right side.
7. Termination: Close the scanner.

16.A class Stringop is designed to handle string related operations. Some of


the members of the class are given below:

Class name: Stringop

Data Members
txt - string variable to store the given string

Member Fucntions/Methods
stringop() - constructor
void readstring() - to accept the string
char caseconvert(int i) - to convert the letter present at ith index
59
into its opposite case and return
void circularcode() - to decode the string by replacing each
letter by converting it to opposite case
and then by the next character in a
circular way. Hence, “AbZ” will be
decoded as “bCa”

Specify the class giving the details of the char caseconvert(int i) and void
circularcode() only.

Ans) public class Stringop {


// Data Members
private String txt;

// Constructor
public Stringop() {
txt = "";
}

// Member Functions/Methods

// Method to accept the string


public void readstring(String input) {
txt = input;
}

// Method to convert the letter present at ith index into its opposite case and
return
public char caseconvert(int i) {
if (i < 0 || i >= txt.length()) {
throw new IndexOutOfBoundsException("Index out of range");
}
char ch = txt.charAt(i);
if (Character.isUpperCase(ch)) {
return Character.toLowerCase(ch);
} else if (Character.isLowerCase(ch)) {
return Character.toUpperCase(ch);
} else {
60
return ch; // Return the character as is if it's not a letter
}
}

// Method to decode the string by replacing each letter by converting it to


opposite case and then by the next character in a circular way
public void circularcode() {
StringBuilder decodedString = new StringBuilder();
for (int i = 0; i < txt.length(); i++) {
char ch = caseconvert(i);
if (Character.isLetter(ch)) {
if (ch == 'z') {
ch = 'A';
} else if (ch == 'Z') {
ch = 'a';
} else {
ch++;
}
}
decodedString.append(ch);
}
txt = decodedString.toString();
}

// Method to get the current value of txt (for testing purposes)


public String getTxt() {
return txt;
}

public static void main(String[] args) {


// Testing the Stringop class
Stringop obj = new Stringop();
obj.readstring("AbZ");
System.out.println("Original String: " + obj.getTxt());
obj.circularcode();
System.out.println("Decoded String: " + obj.getTxt());
}
}
61
Output:

Variable Data Type Description :


Variable Data Type Description
`txt String Holds the string value to
be processed`
`input String The input string provided
by the user`
`i int Index of the character
being processed`
`ch char Character at the current
index in the string`
`decodedString StringBuilder Holds the transformed
version of the original
string`

Algorithm:
1. Initialization: Create a `Stringop` class with a private string member `txt`.
2.Input Method: Implement `readstring(String input)` to set the value of `txt`.
3.Case Conversion Method:
- Implement `caseconvert(int i)` to convert the character at index `i` to its
opposite case.
- Handle invalid indices by throwing an `IndexOutOfBoundsException`.
4.Circular Encoding Method:
62
- Implement `circularcode()` to process each character:
- Convert to the opposite case using `caseconvert`.
- For letters:
- If it's 'z', change it to 'A'.
- If it's 'Z', change it to 'a'.
- For others, increment the character.
- Append the processed character to `decodedString`.
- Update `txt` with the result from `decodedString`.
5. Output Method: Implement `getTxt()` to return the current value of `txt`.
6. Testing: In `main`, create an instance of `Stringop`, read an input string, and
demonstrate the encoding functionality by printing the original and decoded
strings.

17. A positive natural number (eg 27) can be represented as


follows: 2+3+4+5+6+7
8+9+10
13+14
Where every row represents a combination of consecutive natural
numbers, which adds up to 27.
Write a program, which inputs a positive natural number n and prints the
possible consecutive natural number combinations which when added
give n.

Test your program for the following data and some random data.

Input:
n=9
Output:
45
234
Input:
n=15
Output:
78
12345
456
Input:
n=21
63
Output:
10 11
123456
678

Ans) import java.util.ArrayList;


import java.util.List;
import java.util.Scanner;

public class ConsecutiveSums {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive natural number n: ");
int n = sc.nextInt();

// Find and print all combinations


findConsecutiveSums(n);
}

// Method to find and print consecutive sums


public static void findConsecutiveSums(int n) {
List<List<Integer>> combinations = new ArrayList<>();

// Loop to find the starting point of the consecutive numbers


for (int start = 1; start < n; start++) {
int sum = 0;
List<Integer> currentCombination = new ArrayList<>();

// Create a combination starting from 'start'


for (int i = start; sum < n; i++) {
sum += i;
currentCombination.add(i);

// If the sum equals n, add the combination to the list

64
if (sum == n) {
combinations.add(new ArrayList<>(currentCombination));
}
}
}

// Print the results


for (List<Integer> combination : combinations) {
System.out.println(combination);
}
}
}

Output:

Variable Data Type Description:


Variable Data Type Description
sc Scanner Scanner object for
reading user input
n int The positive natural
number input by the user
combinations List<List<Integer>> Stores all valid
combinations of
65
consecutive sums
start int The starting point for
generating consecutive
numbers
sum int The cumulative sum of
the current combination
currentCombination List<Integer> Stores the current
combination of
consecutive numbers

Algorithm:
1. Input Handling:
- Initialize a `Scanner` object to read user input.
- Prompt the user to enter a positive natural number \( n \).

2. Finding Combinations:
- Initialize an empty list `combinations` to store valid combinations.
- Use a loop with `start` ranging from 1 to \( n-1 \) to denote the starting point
of consecutive numbers.
- For each starting point:
- Initialize `sum` to 0 and create an empty list `currentCombination`.
- Use another loop to add consecutive numbers starting from `start` until the
`sum` is greater than or equal to \( n \).
- For each consecutive number:
- Add it to `sum` and `currentCombination`.
- If `sum` equals \( n \), add a copy of `currentCombination` to `combinations`.

3. Output:
- After finding all combinations, print each combination in `combinations`.

18. Consider the sequence of natural numbers


1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26…
Removing every second number produces the sequence
1,3,5,7,9,11,13,15,17,19,21,23,25…
Removing every third number from the above sequence produces
1,3,7,9,13,15,19,21,25,…

66
This process continues indefinitely by removing the forth, fifth… and so
on till after a fixed number of steps, certain natural numbers remain
indefinitely. These are known as Lucky Numbers. Write a program to
generate and print Lucky Number less than a given natural number n
where n<=50.

Input:
n=10
Output:
The lucky numbers less than 10 are:
137
Input:
n=25
Output:
The lucky numbers less than 25 are:
1 3 7 13 19

Ans) import java.io.*;


class luckyNumber
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Number of Elements : ");
int n=Integer.parseInt(br.readLine());

int a[]=new int[n];


int c=n;

for(int i=0;i<n;i++)
{
a[i]=i+1;
}

int del=1;
System.out.println("\nLucky Number Operation :\n");

while(del<n)
67
{
for(int i=del; i<n; i+=del)
{
for(int j=i; j<n-1; j++)
{
a[j]=a[j+1];
}
n--;
}
del++;

for(int i=0; i<n; i++)


{
System.out.print(a[i]+" ");
}
System.out.println();
} //end of while

System.out.print("\nHence, the Lucky Numbers Less than "+c+" are : ");


for(int i=0; i<n; i++)
{
System.out.print(a[i]+" ");
}
}
}

Output:

68
Variable data type description:
Variable Data Type Description
br BufferedReader BufferedReader for
reading user input from
the console
n int The number of elements
input by the user
a int[] An array holding integers
from 1 to n
c int A copy of the original
number of elements for
display purposes
del int The current index used to
determine which numbers
to delete from the array

Algorithm:
1. Input Handling:
- Create a `BufferedReader` to read input from the user.
- Prompt the user to enter the number of elements \( n \).

2. Array Initialization:
- Initialize an integer array `a` of size \( n \).
- Populate the array with values from 1 to \( n \).

3. Finding Lucky Numbers:


- Initialize `del` to 1 to start the deletion process.
- Use a `while` loop to perform deletions until `del` is less than \( n \).
- In each iteration, delete every `del`-th number from the array.
- After deletions, decrement \( n \) to reflect the new size of the array.
- Print the current state of the array after each pass.

4. Output:
- After all deletions, print the remaining numbers in the array as the lucky numbers.

19. Write a program to accept a date in the string format dd/mm/yyyy


69
and accept the name of the day on 1st January of the corresponding
year. Find the day for the given date.

Input:
Date: 5/7/2001
Day on 1st January: MONDAY
Output:
Day on 5/7/2001: THURSDAY

Test and run the program on the following inputs


Input date Day on 1st January Output day for the input date
4/9/1998 THURSDAY FRIDAY
31/8/1999 FRIDAY TUESDAY
6/12/2000 SATURDAY WEDNESDAY

Ans) import java.util.HashMap;


import java.util.Map;
import java.util.Scanner;

public class DayCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input date
System.out.print("Enter date (dd/mm/yyyy): ");
String dateInput = scanner.nextLine();

// Input day on 1st January


System.out.print("Enter the day on 1st January: ");
String firstJanuaryDay = scanner.nextLine().toUpperCase();

// Extract day, month, year from the input


String[] dateParts = dateInput.split("/");
int day = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
70
int year = Integer.parseInt(dateParts[2]);

// Calculate the day for the given date


String resultDay = calculateDay(day, month, year, firstJanuaryDay);
System.out.println("Day on " + dateInput + ": " + resultDay);
}

private static String calculateDay(int day, int month, int year, String
firstJanuaryDay) {
// Days of the week mapping
Map<String, Integer> daysMapping = new HashMap<>();
daysMapping.put("SUNDAY", 0);
daysMapping.put("MONDAY", 1);
daysMapping.put("TUESDAY", 2);
daysMapping.put("WEDNESDAY", 3);
daysMapping.put("THURSDAY", 4);
daysMapping.put("FRIDAY", 5);
daysMapping.put("SATURDAY", 6);

// Get the base day number for 1st January


int baseDay = daysMapping.get(firstJanuaryDay);

// Days in each month (considering leap years)


int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Adjust for leap year
if (isLeapYear(year)) {
daysInMonth[2] = 29;
}

// Calculate total days from January to the given month


int totalDays = 0;
for (int m = 1; m < month; m++) {
totalDays += daysInMonth[m];
}
totalDays += day; // Add the days of the given month
71
// Calculate the final day of the week
int finalDay = (baseDay + totalDays - 1) % 7;

// Return the corresponding day name


for (Map.Entry<String, Integer> entry : daysMapping.entrySet()) {
if (entry.getValue() == finalDay) {
return entry.getKey();
}
}
return ""; // Fallback (should not reach here)
}

private static boolean isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}

Output:

Variable Data Type Description:


Variable Data Type Description

72
scanner Scanner A Scanner object for
reading user input from
the console.
dateInput String Input string representing
the date in the format
dd/mm/yyyy.
firstJanuaryDay String Input string representing
the day of the week on
January 1st.
dateParts String[] An array that holds the
parts of the date (day,
month, year).
day int The day of the month
extracted from the input.
month int The month of the year
extracted from the input.
year int The year extracted from
the input.
resultDay String The calculated day of the
week for the given date.
daysMapping Map<String, Integer> A mapping of days of the
week to their
corresponding integer
values.
baseDay int The integer value
representing the day of
the week on January 1st.
daysInMonth int[] An array containing the
number of days in each
month, adjusted for leap
years.
totalDays int The total number of days
from January to the given
date.
finalDay int The final integer value
representing the
calculated day of the
week.
73
entry Map.Entry<String, A single entry in the
Integer> daysMapping for
retrieving the day name.
year int The year input by the
user to check for leap
year status.

Algorithm:
1. Input Handling:
- Create a `Scanner` object to read input from the user.
- Prompt the user to enter a date and the corresponding day of the week for
January 1st.
- Parse the input date to extract the day, month, and year.

2. Day Calculation:
- Create a `HashMap` to map the days of the week to their corresponding
integer values.
- Get the integer value for the day on January 1st.
- Initialize an array for the number of days in each month, accounting for leap
years.
- If the year is a leap year, adjust the number of days in February.
- Calculate the total days from January to the given month and add the day of
the month.

3. Final Calculation:
- Calculate the final day of the week using modulo arithmetic based on the base
day and the total number of days.
- Loop through the mapping to find the corresponding day name and return it.

4. Output:
- Print the day of the week corresponding to the entered date.

20. (i) Write a program to declare a square matrix A[][] of order N (N<20).
(ii) Allow the user to input positive integers into this matrix. Perform
the following tasks on the matrix.
(iii) Output the original matrix

74
(iv) Find the SADDLE POINT for the matrix. A saddle point is an
element of the matrix such that it is the minimum element for the
row and the maximum element for the column to which it
belongs. Saddle point for a given matrix is always unique. If the
matrix has no saddle point, output the message “NO SADDLE
POINT”.
(v) If the matrix has a saddle point element then sort the elements of
the left diagonal in ascending order using insertion sort technique.
All other elements should remain unchanged.
Test your program for the following data and some random data

Input:
N=4
Matrix A[][]= 2 5 6 9
8 4 12 3
6 7 3 1
12 24 2 11

Output:
Matrix A[][]= 2 5 6 7
8 4 12 3
6 7 3 1
12 24 2 11
No saddle point
Input:
N=3
Matrix A[][]= 4 6 12
2 6 14
1 3 6
Output:
Matrix A[][]= 4 6 12
2 8 14
1 3 6
Saddle Point=4
Matrix after sorting the principal diagon

4 6 12
2 6 14
75
1 3 8

Ans) import java.util.Scanner;

public class SaddlePointMatrix {


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

// Input order of the matrix


System.out.print("Enter the order of the matrix (N < 20): ");
int N = scanner.nextInt();

if (N >= 20) {
System.out.println("Order must be less than 20.");
return;
}

int[][] matrix = new int[N][N];

// Input matrix elements


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Output original matrix


System.out.println("Matrix A[][]=");
printMatrix(matrix);

// Find saddle point


int saddlePoint = findSaddlePoint(matrix);

if (saddlePoint == -1) {
System.out.println("No saddle point");
} else {
System.out.println("Saddle Point = " + saddlePoint);
// Sort the left diagonal
sortLeftDiagonal(matrix);
System.out.println("Matrix after sorting the principal diagonal:");
printMatrix(matrix);
}

76
scanner.close();
}

// Function to print the matrix


private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}

// Function to find the saddle point


private static int findSaddlePoint(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
// Find minimum element in the current row
int minRow = matrix[i][0];
int colIndex = 0;

for (int j = 1; j < matrix[i].length; j++) {


if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
colIndex = j;
}
}

// Check if this minimum element is the maximum in its column


boolean isSaddlePoint = true;
for (int k = 0; k < matrix.length; k++) {
if (matrix[k][colIndex] > minRow) {
isSaddlePoint = false;
break;
}
}

if (isSaddlePoint) {
return minRow; // Return the saddle point
}
}
return -1; // No saddle point found
}

// Function to sort the left diagonal using insertion sort


77
private static void sortLeftDiagonal(int[][] matrix) {
int n = matrix.length;
int[] diagonal = new int[n];

// Extract the left diagonal elements


for (int i = 0; i < n; i++) {
diagonal[i] = matrix[i][i];
}

// Sort the diagonal using insertion sort


for (int i = 1; i < n; i++) {
int key = diagonal[i];
int j = i - 1;

// Move elements of diagonal[0..i-1] that are greater than key


while (j >= 0 && diagonal[j] > key) {
diagonal[j + 1] = diagonal[j];
j--;
}
diagonal[j + 1] = key;
}

// Place sorted diagonal back into the matrix


for (int i = 0; i < n; i++) {
matrix[i][i] = diagonal[i];
}
}
}

Output:

78
Variable Data Type Description:
Variable Data Type Description
scanner Scanner A Scanner object for
reading user input from
the console.
N int The order of the matrix,
input by the user.`
matrix int[][] A 2D array representing
the matrix of size N x N.
saddlePoint int The value of the saddle
point found in the matrix,
or -1 if none exists.
i, j, k int Loop variables used for
iterating through the
matrix elements.
minRow int The minimum element
found in the current row
of the matrix.
colIndex int The column index of the
minimum element in the
current row.
isSaddlePoint boolean A flag to indicate
whether the minimum
element is a saddle point.
79
diagonal int[] An array holding the
elements of the left
diagonal of the matrix.
key int A variable used during
the insertion sort to hold
the current value being
sorted.
j int Loop variable used for
comparing and shifting
elements during sorting.`
`n int The size of the matrix (or
the length of the diagonal
array).`

Algorithm:
1. Input Handling:
- Create a `Scanner` object to read user input.
- Prompt the user to enter the order of the matrix, ensuring it is less than 20.
- Initialize a 2D array to hold the matrix values.
- Read the matrix elements from user input.

2. Matrix Output:
- Print the original matrix using a dedicated method.

3. Saddle Point Calculation:


- Iterate through each row of the matrix to find the minimum element.
- For the minimum element found, check if it is the maximum in its
corresponding column.
- If such a minimum element exists, return it as the saddle point. If no saddle
point is found, return -1.

4. Diagonal Sorting:
- If a saddle point is found, extract the left diagonal elements into a separate
array.
- Sort this diagonal array using the insertion sort algorithm.
- Place the sorted diagonal elements back into their original positions in the
matrix.

5. Output:
- Print the saddle point and the modified matrix with the sorted diagonal.

80
Conclusion

In this project, we developed and implemented a Java program designed


exclusively for computer-based execution. The use of Java's platform
independence, facilitated by the Java Virtual Machine (JVM), ensured that the
program could run on any device equipped with the JVM, providing significant
flexibility and accessibility. By leveraging Java's object-oriented programming
(OOP) principles, we constructed a modular and reusable codebase, enhancing
the program's maintainability and allowing for future scalability and feature
integration. Java's strong error-handling mechanisms enabled us to create a
resilient program capable of managing exceptions and unexpected inputs
gracefully, ensuring a seamless user experience.

Through careful algorithm selection and optimization, we achieved a balance


between performance and resource utilization, critical in creating responsive and
efficient software. The use of Integrated Development Environments (IDEs) like
Eclipse or IntelliJ IDEA streamlined the development process, offering features
such as code completion, debugging, and version control integration. Rigorous
testing was conducted to validate the program's functionality, performance, and
security, ensuring the final product met all specified requirements and performed
reliably in various scenarios.

While the current implementation achieves the project's goals, future


enhancements could include improving the graphical user interface (GUI) to
provide a more intuitive user experience, adding new features and functionalities
based on user feedback and emerging requirements, and further optimizing
algorithms and code execution for enhanced performance.

81
Bibliography

Here are some websites that helped me throughout this project:

1. Oracle Java Documentation.


[https://docs.oracle.com/javase/tutorial/](https://docs.oracle.com/javase/tutoria
l/)

2. GeeksforGeeks.
[https://www.geeksforgeeks.org/java/](https://www.geeksforgeeks.org/java/)

3. Stack Overflow.
[https://stackoverflow.com/questions/tagged/java](https://stackoverflow.com/q
uestions/tagged/java)

4. W3Schools.
[https://www.w3schools.com/java/](https://www.w3schools.com/java/)

5. Java Code Geeks.


[https://www.javacodegeeks.com/](https://www.javacodegeeks.com/)

6. Baeldung.
[https://www.baeldung.com/](https://www.baeldung.com/)

7. TutorialsPoint.
[https://www.tutorialspoint.com/java/index.htm](https://www.tutorialspoint.co
m/java/index.htm)

8. JavaWorld.
[https://www.javaworld.com/](https://www.javaworld.com/)

9. Javatpoint.
[https://www.javatpoint.com/java-tutorial](https://www.javatpoint.com/java-
tutorial)

10. Programiz.
[https://www.programiz.com/java-
programming](https://www.programiz.com/java-programming)

82

You might also like