Computer 2024-2025
Computer 2024-2025
I would like to express my sincere gratitude to all those who have contributed to
the successful completion of this computer project.
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.
1
INDEX
2
INTRODUCTION
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
if (n % 2 == 0 || n <= 0) {
System.out.println("Please enter a valid odd natural number.");
return;
}
matrix[x][y] = value++;
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
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;
}
Output:
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.
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
Output:
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.
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
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
16
3 0 1
3 1 0
//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");
}
/*
* seenArr is used to check that
* numbers are not repeated
*/
boolean seenArr[] = new boolean[nSq];
18
if (seenArr[arr[i][j] - 1]) {
return false;
}
seenArr[arr[i][j] - 1] = true;
rSum += arr[i][j];
cSum += arr[j][i];
}
return true;
}
int n = arr.length;
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
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()
class SortAlpha {
// Data members/instance variables
private String sent;
private int m;
// 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();
sorted.display(original);
}
}
Output:
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:
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.
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.
Input:
ABDOMEN
Output:
It is a magic string
Input:
COMPUTER
Output:
It is not a magic string
Ans) import java.util.Scanner;
if (isMagicStr)
System.out.println("It is a magic string");
else
System.out.println("It is not a magic string");
29
}
Output:
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.
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;
// 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();
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:
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
// 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);
}
}
35
Output:
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.
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;
39
Sphenic sphenic = new Sphenic();
sphenic.Check(n);
}
}
Output:
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`.
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
// 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];
}
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.
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.
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’)
modifiedString.append(newChar);
} else {
// If it's not a letter, append it as it is
modifiedString.append(c);
}
}
return modifiedString.toString();
}
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.
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[][]
// Default constructor
public matrix_image() {
arr1 = new double[15][15];
arr2 = new double[15][15];
m = 0;
n = 0;
}
// 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();
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.
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.
// Default constructor
public chaarray() {
this.ch = new char[100]; // Initialize array with a max size of 100
this.size = 0;
}
scanner.close();
}
}
Output:
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.
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.
// Constructor
public Stringop() {
txt = "";
}
// Member Functions/Methods
// 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
}
}
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.
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
64
if (sum == n) {
combinations.add(new ArrayList<>(currentCombination));
}
}
}
Output:
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`.
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
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++;
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 \).
4. Output:
- After all deletions, print the remaining numbers in the array as the lucky numbers.
Input:
Date: 5/7/2001
Day on 1st January: MONDAY
Output:
Day on 5/7/2001: THURSDAY
// Input date
System.out.print("Enter date (dd/mm/yyyy): ");
String dateInput = scanner.nextLine();
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);
Output:
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
if (N >= 20) {
System.out.println("Order must be less than 20.");
return;
}
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();
}
if (isSaddlePoint) {
return minRow; // Return the saddle point
}
}
return -1; // No saddle point found
}
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.
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
81
Bibliography
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/)
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