0% found this document useful (0 votes)
11 views77 pages

Computer Science Project25-1

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

Computer Science Project25-1

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

Computer Science Project 2024-25

Class: XII

Q1.
A Goldbach number is a positive even integer that can be expressed as the sum of
two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example:
6=3+3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs, i.e.
3 and 7, 5 and 5.
Write a program to accept an even integer 'N' where N > 9 and N < 50. Find all the
odd prime pairs whose sum is equal to the number 'N'.
Test your program with the following data and some random data:
Example 1
INPUT:
N = 14
OUTPUT:
PRIME PAIRS ARE:
3, 11
7, 7
Example 2
INPUT:
N = 17
OUTPUT:
INVALID INPUT. NUMBER IS ODD.
Example 3
INPUT:
N = 126
OUTPUT:
INVALID INPUT. NUMBER OUT OF RANGE.
Solution:

import java.util.Scanner;

public class GoldbachNumber

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.print("Enter an even integer N (10 < N < 50): ");

int N = sc.nextInt();

// Validate the input

if (N % 2 != 0)

System.out.println("INVALID INPUT. NUMBER IS ODD.");

else if (N <= 9 || N >= 50)

System.out.println("INVALID INPUT. NUMBER OUT OF RANGE.");

else

System.out.println("PRIME PAIRS ARE:");

// Loop through all odd numbers from 3 to N/2

for (int i = 3; i <= N / 2; i += 2)

int complement = N - i;

// Check if i is prime

int iDivisors = 0;

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

{
if (i % j == 0)

iDivisors++;

// Check if complement is prime

int complementDivisors = 0;

for (int j = 1; j <= complement; j++)

if (complement % j == 0)

complementDivisors++;

// Print the pair if both are prime

if (iDivisors == 2 && complementDivisors == 2)

System.out.println(i + ", " + complement);

}
Q2
A Prime-Adam integer is a positive integer (without leading zeros) which is a prime
as well as an Adam number.
Prime number: A number which has only two factors, i.e. 1 and the number itself.
Example: 2, 3, 5, 7 ... etc.
Adam number: The square of a number and the square of its reverse are reverse to
each other.
Example: If n = 13 and reverse of 'n' = 31, then,
(13)2 = 169
(31)2 = 961 which is reverse of 169
thus 13, is an Adam number.
Accept two positive integers m and n, where m is less than n as user input. Display
all Prime-Adam integers that are in the range between m and n (both inclusive) and
output them along with the frequency, in the format given below:
Test your program with the following data and some random data:
Example 1
INPUT:
m=5
n = 100
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
11 13 31
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 2
INPUT:
m = 100
n = 200
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
101 103 113
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 3
INPUT:
m = 50
n = 70
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
NIL
FREQUENCY OF PRIME-ADAM INTEGERS IS: 0
Example 4
INPUT:
m = 700
n = 450
OUTPUT:
INVALID INPUT
Solution:

import java.util.Scanner;

public class PrimeAdam {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the value of m: ");

int m = sc.nextInt();

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

int n = sc.nextInt();

// Validate input

if (m > n || m <= 0 || n <= 0) {

System.out.println("INVALID INPUT");

} else {

System.out.println("THE PRIME-ADAM INTEGERS ARE:");

int frequency = 0;

// Loop through numbers from m to n

for (int num = m; num <= n; num++) {

// Check if the number is prime

int divisorCount = 0;

for (int i = 1; i <= num; i++) {

if (num % i == 0) {

divisorCount++;

}
// Proceed only if the number is prime

if (divisorCount == 2) {

// Reverse the number

int original = num;

int reverse = 0;

while (original > 0) {

reverse = reverse * 10 + (original % 10);

original /= 10;

// Compute the square of the number and its reverse

int numSquare = num * num;

int reverseSquare = reverse * reverse;

// Reverse the square of the reverse

int reverseOfReverseSquare = 0;

int temp = reverseSquare;

while (temp > 0) {

reverseOfReverseSquare = reverseOfReverseSquare * 10 + (temp %


10);

temp /= 10;

// Check if the squares are reverse of each other

if (numSquare == reverseOfReverseSquare) {

System.out.print(num + " ");

frequency++;

}
}

// Handle the case where no Prime-Adam integers are found

if (frequency == 0) {

System.out.println("NIL");

System.out.println();

System.out.println("FREQUENCY OF PRIME-ADAM INTEGERS IS: " +


frequency);

}
Q3.

Write a program to declare a matrix A[][] of order (M x N) where 'M' is the number of
rows and 'N' is the number of columns such that the value of 'M' must be greater
than 0 and less than 10 and the value of 'N' must be greater than 2 and less than 6.
Allow the user to input digits (0 - 7) only at each location, such that each row
represents an octal number.
Example:
2 3 1 (decimal equivalent of 1st row = 153 i.e. 2x82 + 3x81 + 1x80)

4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4x82 + 0x81 + 5x80)

1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1x82 + 5x81 + 6x80)

Perform the following tasks on the matrix:

1. Display the original matrix.

2. Calculate the decimal equivalent for each row and display as per the format
given below.

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

Example 1:

INPUT:
M=1
N=3
ENTER ELEMENTS FOR ROW 1: 1 4 4

OUTPUT:

FILLED MATRIX DECIMAL EQUIVALENT

1 4 4 100

Example 2:

INPUT:
M=3
N=4
ENTER ELEMENTS FOR ROW 1: 1 1 3 7
ENTER ELEMENTS FOR ROW 2: 2 1 0 6
ENTER ELEMENTS FOR ROW 3: 0 2 4 5

OUTPUT:
FILLED MATRIX DECIMAL EQUIVALENT

1 1 3 7 607

2 1 0 6 1094

0 2 4 5 165

Example 3:

INPUT:
M=3
N=3
ENTER ELEMENTS FOR ROW 1: 2 4 8

OUTPUT:
INVALID INPUT

Example 4:

INPUT:
M=4
N=6

OUTPUT:
OUT OF RANGE
Solution:

import java.util.Scanner;

public class OctalMatrix {

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();

// Input validation

if (M <= 0 || M >= 10 || N <= 2 || N >= 6) {

System.out.println("OUT OF RANGE");

} else {

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

boolean invalidInput = false;

// Input the matrix

System.out.println("ENTER ELEMENTS FOR MATRIX (only digits 0-7):");

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

System.out.print("ENTER ELEMENTS FOR ROW " + (i + 1) + ": ");

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

matrix[i][j] = sc.nextInt();

// Check if the input is a valid octal digit

if (matrix[i][j] < 0 || matrix[i][j] > 7) {

invalidInput = true;
}

// Display invalid input if found

if (invalidInput) {

System.out.println("INVALID INPUT");

} else {

// Display the filled matrix

System.out.println("FILLED MATRIX");

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

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

System.out.print(matrix[i][j] + " ");

System.out.println();

// Calculate and display decimal equivalents

System.out.println("DECIMAL EQUIVALENT");

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

int decimalValue = 0;

int power = N - 1;

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

decimalValue += matrix[i][j] * Math.pow(8, power);

power--;

System.out.println(decimalValue);

}
}

}
Q4.

Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
only. The words are to be separated by a single blank space and are in UPPER CASE.

Perform the following tasks:

1. Check for the validity of the accepted sentence only for the terminating
character.

2. Arrange the words in ascending order of their length. If two or more words
have the same length, then sort them alphabetically.

3. Display the original sentence along with the converted sentence.

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

Example 1:

INPUT:
AS YOU SOW SO SHALL YOU REAP.

OUTPUT:
AS YOU SOW SO SHALL YOU REAP.
AS SO SOW YOU YOU REAP SHALL

Example 2:

INPUT:
SELF HELP IS THE BEST HELP.

OUTPUT:
SELF HELP IS THE BEST HELP.
IS THE BEST HELP HELP SELF

Example 3:

INPUT:
BE KIND TO OTHERS.

OUTPUT:
BE KIND TO OTHERS.
BE TO KIND OTHERS

Example 4:

INPUT:
NOTHING IS IMPOSSIBLE#

OUTPUT:
INVALID INPUT
Solution:

import java.util.*;

class Stringsort {

void main() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the String");

String inp = sc.nextLine();

// Check if the input ends with a valid punctuation ('.', '?', or '!')

char lastChar = inp.charAt(inp.length() - 1);

if (lastChar != '.' && lastChar != '?' && lastChar != '!') {

System.out.println("INVALID INPUT");

return;

// Display the original sentence

System.out.println(inp);

// Remove the terminating punctuation and split the sentence into words

String arr[] = inp.substring(0, inp.length() - 1).split(" ");

// Bubble sort for arranging words by length, and alphabetically if lengths are
equal

boolean swapped = false;

for (int i = 0; i < arr.length - 1; i++) {

for (int j = 0; j < arr.length - 1 - i; j++) {

String temp = "";


if (arr[j].length() > arr[j + 1].length()) {

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

swapped = true;

} else if (arr[j].length() == arr[j + 1].length()) {

if (arr[j].compareTo(arr[j + 1]) > 0) {

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

swapped = true;

if (!swapped)

break;

// Display the sorted words as the converted sentence

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

System.out.print(arr[i] + " ");

}
Q5.

Write a program to declare a square matrix A[][] of order (M × M) where 'M' must be
greater than 3 and less than 10. Allow the user to input positive integers into this
matrix. Perform the following tasks on the matrix:

1. Sort the non-boundary elements in ascending order using any standard sorting
technique and rearrange them in the matrix.

2. Calculate the sum of both the diagonals.

3. Display the original matrix, rearranged matrix and only the diagonal elements
of the rearranged matrix with their sum.

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

Example 1

INPUT:
M=4
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8

OUTPUT:
ORIGINAL MATRIX
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
REARRANGED MATRIX
9 2 1 5
8 3 6 4
15 8 13 11
7 12 23 8
DIAGONAL ELEMENTS
9 5
3 6
8 13
7 8
SUM OF THE DIAGONAL ELEMENTS = 59

Example 2

INPUT:
M=5
7 4 1 9 5
8 2 6 10 19
13 1 3 5 1
10 0 5 12 16
1 8 17 6 8

OUTPUT:
ORIGINAL MATRIX
7 4 1 9 5
8 2 6 10 19
13 1 3 5 1
10 0 5 12 16
1 8 17 6 8
REARRANGED MATRIX
7 4 1 9 5
8 0 1 2 19
13 3 5 5 1
10 6 10 12 16
1 8 17 6 8
DIAGONAL ELEMENTS
7 5
0 2
5
6 12
1 8
SUM OF THE DIAGONAL ELEMENTS = 46

Example 3

INPUT:
M=3

OUTPUT:
THE MATRIX SIZE IS OUT OF RANGE
.Solution:

import java.util.*;

class SumDiag {

void main() {

Scanner sc = new Scanner(System.in);

// Input size of matrix

System.out.println("Enter the size of the square matrix (M): ");

int M = sc.nextInt();

// Check if M is within range

if (M <= 3 || M >= 10) {

System.out.println("THE MATRIX SIZE IS OUT OF RANGE.");

return;

// Declare and input the matrix

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

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 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] + "\t");

System.out.println();

// Extract non-boundary elements

List<Integer> nonBoundaryElements = new ArrayList<>();

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

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

nonBoundaryElements.add(matrix[i][j]);

// Sort non-boundary elements

Collections.sort(nonBoundaryElements);

// Rearrange sorted elements back into the matrix

int index = 0;

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

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

matrix[i][j] = nonBoundaryElements.get(index++);

// Display rearranged matrix

System.out.println("REARRANGED MATRIX");

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

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


System.out.print(matrix[i][j] + "\t");

System.out.println();

// Calculate sum of both diagonals

int primaryDiagonalSum = 0;

int secondaryDiagonalSum = 0;

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

primaryDiagonalSum += matrix[i][i];

secondaryDiagonalSum += matrix[i][M - i - 1];

int totalDiagonalSum = primaryDiagonalSum + secondaryDiagonalSum;

// Display diagonal elements and their sum

System.out.println("DIAGONAL ELEMENTS");

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

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

if (i == j || j == M - i - 1) {

System.out.print(matrix[i][j] + "\t");

} else {

System.out.print("\t");

System.out.println();

System.out.println("SUM OF THE DIAGONAL ELEMENTS = " +


totalDiagonalSum);

}
}

Q6.

Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
only. The words may be separated by more than one blank space and are in UPPER
CASE.

Perform the following tasks:

1. Find the number of words beginning and ending with a vowel.

2. Place the words which begin and end with a vowel at the beginning, followed
by the remaining words as they occur in the sentence.

Test your program with the sample data and some random data:

Example 1

INPUT:
ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.

OUTPUT:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL

Example 2

INPUT:
YOU MUST AIM TO BE A BETTER PERSON TOMORROW THAN YOU ARE TODAY.

OUTPUT:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 2
A ARE YOU MUST AIM TO BE BETTER PERSON TOMORROW THAN YOU TODAY

Example 3

INPUT:
LOOK BEFORE YOU LEAP.

OUTPUT:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 0
LOOK BEFORE YOU LEAP

Example 4

INPUT:
HOW ARE YOU@

OUTPUT:
INVALID INPUT
Solution:

import java.util.*;

class StringVowel {

void main() {

// Input and cleaning

Scanner sc = new Scanner(System.in);

String inp = "";

System.out.println("Enter the sentence (ending with '.', '?' or '!'):");

inp = sc.nextLine();

// Validate input for correct ending

int len = inp.length();

char endChar = inp.charAt(len - 1);

if (!(endChar == '.' || endChar == '?' || endChar == '!')) {

System.out.println("INVALID INPUT");

return;

inp = inp.trim(); // Remove leading and trailing spaces

inp = inp.replaceAll("\\s+", " "); // Replace multiple spaces with a single space

// Removing punctuation from the end for processing

inp = inp.substring(0, len - 1);

// Split the input sentence into words

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


// Arrays to hold words based on vowel condition

String[] vowelWords = new String[words.length];

String[] nonVowelWords = new String[words.length];

int vowelCount = 0, nonVowelCount = 0;

// Process each word

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

String word = words[i];

char firstChar = word.charAt(0);

char lastChar = word.charAt(word.length() - 1);

// Check if word starts and ends with a vowel

if ((firstChar == 'A' || firstChar == 'E' || firstChar == 'I' || firstChar == 'O' ||


firstChar == 'U') &&

(lastChar == 'A' || lastChar == 'E' || lastChar == 'I' || lastChar == 'O' ||


lastChar == 'U')) {

vowelWords[vowelCount] = word; // Store vowel words

vowelCount++;

} else {

nonVowelWords[nonVowelCount] = word; // Store non-vowel words

nonVowelCount++;

// Output the result

System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A


VOWEL = " + vowelCount);
// Print vowel words followed by non-vowel words

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

System.out.print(vowelWords[i] + " ");

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

System.out.print(nonVowelWords[i] + " ");

System.out.println();

}
Q7.

Design a program to accept a day number (between 1 and 366), year (in 4 digits)
from the user to generate and display the corresponding date. Also, accept 'N' (1 <=
N <= 100) from the user to compute and display the future date corresponding to
'N' days after the generated date. Display an error message if the value of the day
number, year and N are not within the limit or not according to the condition
specified.

Test your program with the following data and some random data:

Example 1

INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22

OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018

Example 2

INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45

OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019

Example 3

INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33

OUTPUT:
DAY NUMBER OUT OF RANGE

Example 4
INPUT:
DAY NUMBER: 150
YEAR: 2018
DATE AFTER (N DAYS): 330

OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE

Solution:

import java.util.*;

class DateCalculator {

void main() {

Scanner sc = new Scanner(System.in);

// Accepting the day number, year and N value

System.out.println("Enter the day number (1-366):");

int dayNumber = sc.nextInt();

System.out.println("Enter the year (4-digit):");

int year = sc.nextInt();

System.out.println("Enter the number of days to add (1-100):");

int nDays = sc.nextInt();

// Validate the input range

if (dayNumber < 1 || dayNumber > 366) {

System.out.println("DAY NUMBER OUT OF RANGE");

return;

if (year < 1000 || year > 9999) {

System.out.println("INVALID YEAR");

return;

}
if (nDays < 1 || nDays > 100) {

System.out.println("DATE AFTER (N DAYS) OUT OF RANGE");

return;

// Determine if the given year is a leap year

boolean isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 ==


0));

// Month days for the given year

int[] monthDays = isLeapYear ?

new int[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} :

new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// Finding the date corresponding to the day number

int month = 0;

int dayOfMonth = 0;

// Determine the corresponding month and day of the month

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

if (dayNumber <= monthDays[i]) {

month = i;

dayOfMonth = dayNumber;

break;

} else {

dayNumber -= monthDays[i];

}
// Display the original date

System.out.printf("DATE: %dTH %s, %d\n", dayOfMonth,


getMonthName(month), year);

// Calculate the future date after adding N days

dayNumber += nDays;

// Validate the future date after adding N days

if (dayNumber > (isLeapYear ? 366 : 365)) {

System.out.println("DATE AFTER (N DAYS) OUT OF RANGE");

return;

// Recalculate the future date

int futureMonth = 0;

int futureDay = 0;

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

if (dayNumber <= monthDays[i]) {

futureMonth = i;

futureDay = dayNumber;

break;

} else {

dayNumber -= monthDays[i];

// Display the future date

System.out.printf("DATE AFTER %d DAYS: %dTH %s, %d\n", nDays, futureDay,


getMonthName(futureMonth), year);

}
// Helper function to get the month name

String getMonthName(int month) {

String[] months = {"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",


"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};

return months[month];

} }

Q8.

Write a program to declare a single-dimensional array a[] and a square matrix b[][]
of size N, where N > 2 and N < 10. Allow the user to input positive integers into the
single dimensional array.

Perform the following tasks on the matrix:

1. Sort the elements of the single-dimensional array in ascending order using any
standard sorting technique and display the sorted elements.

2. Fill the square matrix b[][] in the following format:


If the array a[] = {5, 2, 8, 1} then, after sorting a[] = {1, 2, 5, 8}
Then, the matrix b[][] would fill as below:

1258

1251

1212

1125

3. Display the filled matrix in the above format.

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

Example 1

INPUT:
N=3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7

OUTPUT:
SORTED ARRAY: 1 3 7
FILLED MATRIX

137

131
113

Example 2

INPUT:
N = 13

OUTPUT:
MATRIX SIZE OUT OF RANGE
Solution:

import java.util.*;

class MatrixArrayOperations {

void main() {

Scanner sc = new Scanner(System.in);

// Accept N for matrix size and validate the range

System.out.println("Enter the matrix size N (N > 2 and N < 10):");

int N = sc.nextInt();

if (N <= 2 || N >= 10) {

System.out.println("MATRIX SIZE OUT OF RANGE");

return;

// Declare a single-dimensional array

int[] a = new int[N];

System.out.println("Enter " + N + " elements for the single-dimensional


array:");

// Accept elements for the single-dimensional array

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

a[i] = sc.nextInt();

// Sort the array in ascending order using Arrays.sort()

Arrays.sort(a);

// Display the sorted array


System.out.println("SORTED ARRAY:");

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

System.out.print(a[i] + " ");

System.out.println();

// Create a square matrix b of size N

int[][] b = new int[N][N];

// Fill the matrix b[][] according to the specified format

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

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

b[i][j] = a[i] * a[j];

// Display the filled matrix

System.out.println("FILLED MATRIX:");

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

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

System.out.print(b[i][j]);

System.out.println();

}
Q9.

Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’
only. The words are to be separated by a single blank space and are in uppercase.

Perform the following tasks:

(a) Check for the validity of the accepted sentence.

(b) Convert the non-palindrome words of the sentence into palindrome words by
concatenating the word by its reverse (excluding the last character).

Example:

The reverse of the word HELP would be LEH (omitting the last alphabet) and by
concatenating both, the new palindrome word is HELPLEH. Thus, the word HELP
becomes HELPLEH.

Note: The words which end with repeated alphabets, for example ABB would
become ABBA and not ABBBA and XAZZZ becomes XAZZZAX.

[Palindrome word: Spells same from either side. Example: DAD, MADAM etc.]

(c) Display the original sentence along with the converted sentence.

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

Example 1

INPUT:
THE BIRD IS FLYING.

OUTPUT:
THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNIYLF

Example 2

INPUT:
IS THE WATER LEVEL RISING?

OUTPUT:
IS THE WATER LEVEL RISING?
ISI THEHT WATERETAW LEVEL RISINGNISIR

Example 3

INPUT:
THIS MOBILE APP LOOKS FINE.

OUTPUT:
THIS MOBILE APP LOOKS FINE.
THISIHT MOBILELIBOM APPA LOOKSKOOL FINENIF
Example 3

INPUT:
YOU MUST BE CRAZY#

OUTPUT:
INVALID INPUT
Solution:

import java.util.*;

class PalindromeSentence {

void main() {

Scanner sc = new Scanner(System.in);

// Accept the sentence

System.out.println("Enter a sentence:");

String sentence = sc.nextLine();

// Validate the sentence

if (!sentence.matches("[A-Z ]*[.!?]$")) {

System.out.println("INVALID INPUT");

return;

// Remove the last character (punctuation) for processing

char punctuation = sentence.charAt(sentence.length() - 1);

sentence = sentence.substring(0, sentence.length() - 1);

// Split the sentence into words

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

// Process each word and convert non-palindrome words into palindromes

StringBuilder convertedSentence = new StringBuilder();

for (String word : words) {

String convertedWord = word;


if (!isPalindrome(word)) {

convertedWord = makePalindrome(word);

convertedSentence.append(convertedWord).append(" ");

// Output the original and converted sentences

System.out.println(sentence + punctuation);

System.out.println(convertedSentence.toString().trim() + punctuation);

// Method to check if a word is a palindrome

private boolean isPalindrome(String word) {

int len = word.length();

for (int i = 0; i < len / 2; i++) {

if (word.charAt(i) != word.charAt(len - i - 1)) {

return false;

return true;

// Method to make a word palindrome by appending its reverse (excluding the last
character)

private String makePalindrome(String word) {

StringBuilder reverse = new StringBuilder(word).reverse();

return word + reverse.substring(1);

}
Q10.

A company manufactures packing cartons in four sizes, i.e. cartons to accommodate


6 boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to accept the number
of boxes to be packed (N) by the user (maximum up to 1000 boxes) and display the
break-up of the cartons used in descending order of capacity (i.e. preference should
be given to the highest capacity available, and if boxes left are less than 6, an extra
carton of capacity 6 should be used.)

Test your program with the following data and some random data:

Example 1

INPUT:
N = 726

OUTPUT:
48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16

Example 2

INPUT:
N = 140

OUTPUT:
48 * 2 = 96
24 * 1 = 24
12 * 1 = 12
6*1=6
Remaining boxes = 2 * 1 = 2
Total number of boxes = 140
Total number of cartons = 6

Example 3

INPUT:
N = 4296

OUTPUT:
INVALID INPUT
Solution:

import java.util.*;

class CartonPacking {

void main() {

Scanner sc = new Scanner(System.in);

// Accept the number of boxes to be packed

System.out.println("Enter the number of boxes to be packed (max 1000): ");

int N = sc.nextInt();

// Check for invalid input

if (N < 1 || N > 1000) {

System.out.println("INVALID INPUT");

return;

// Carton sizes

int[] cartonSizes = {48, 24, 12, 6};

int[] cartonCounts = new int[cartonSizes.length];

// Calculate the carton break-up

int totalBoxes = N;

int totalCartons = 0;

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

cartonCounts[i] = totalBoxes / cartonSizes[i];

totalBoxes = totalBoxes % cartonSizes[i];

totalCartons += cartonCounts[i];

}
// If boxes left are less than 6, we add an extra carton of 6 capacity

if (totalBoxes > 0) {

cartonCounts[3] += 1;

totalCartons += 1;

totalBoxes = 0;

// Display the break-up of cartons

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

if (cartonCounts[i] > 0) {

System.out.println(cartonSizes[i] + " * " + cartonCounts[i] + " = " +


(cartonSizes[i] * cartonCounts[i]));

// If there are any remaining boxes less than 6, print them

if (totalBoxes > 0) {

System.out.println("Remaining boxes = " + totalBoxes + " * 1 = " +


totalBoxes);

// Display the total number of boxes and cartons

System.out.println("Total number of boxes = " + N);

System.out.println("Total number of cartons = " + totalCartons);

}
Q11.

Caesar Cipher is an encryption technique which is implemented as ROT13 ('rotate by


13 places'). It is a simple letter substitution cipher that replaces a letter with the
letter 13 places after it in the alphabets, with the other characters remaining
unchanged.

ROT13

A/ B/ C/ D/ E/ G/ H/ K/ M/
F/f I/i J/j L/l
a b c d e g h k m

↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕

N/ O/ P/ Q/ S/ U/ V/ W/ X/ Y/
R/r T/t Z/z
n o p q s u v w x y

Write a program to accept a plain text of length L, where L must be greater than 3
and less than 100.

Encrypt the text if valid as per the Caesar Cipher.

Test your program with the sample data and some random data.

Example 1

INPUT:
Hello! How are you?

OUTPUT:
The cipher text is:
Uryyb! Ubjnerlbh?

Example 2

INPUT:
Encryption helps to secure data.

OUTPUT:
The cipher text is:
Rapelcgvbaurycfgbfrpherqngn.

Example 3

INPUT:
You

OUTPUT:
INVALID LENGTH
Solution:

import java.util.*;

class CaesarCipher{

void main() {

Scanner sc = new Scanner(System.in);

// Accept input text

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

String inp = sc.nextLine();

// Validate the length of the input string

if (inp.length() <= 3 || inp.length() >= 100) {

System.out.println("INVALID LENGTH");

return;

// Convert input text to uppercase

inp = inp.toUpperCase();

// Initialize the encrypted string

String encrypted = "";

// Process each character for ROT13 encryption

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

char ch = inp.charAt(i);
// If the character is a letter, apply ROT13 encryption

if (Character.isLetter(ch)) {

// Shift character by 13 positions

if (ch >= 'A' && ch <= 'M') {

ch = (char) (ch + 13); // Shift within the first half of the alphabet

} else if (ch >= 'N' && ch <= 'Z') {

ch = (char) (ch - 13); // Shift within the second half of the alphabet

encrypted += ch;

// Display the encrypted string

System.out.println("The cipher text is:");

System.out.println(encrypted);

}
Q12.

Write a program to take an array of integers and arrange its elements in ascending
order using Insertion sort method.
Solution:

import java.util.*;

class InsertionSortExample {

void main() {

// Accepting the array size from the user

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of elements in the array (between 1 and


100):");

int n = sc.nextInt();

// Validate the array size

if (n < 1 || n > 100) {

System.out.println("INVALID INPUT");

return;

// Declaring the array of size n

int[] arr = new int[n];

// Accepting array elements from the user

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

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

arr[i] = sc.nextInt();

// Performing insertion sort on the array

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

int key = arr[i];


int j = i - 1;

// Move elements of arr[0..i-1] that are greater than key, to one position
ahead

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key; // Place the key at the correct position

// Displaying the sorted array

System.out.println("The sorted array is:");

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

System.out.print(arr[i] + " ");

}
Q13.

The names of the teams participating in a competition should be displayed on a


banner vertically, to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display
them in vertical order, side by side with a horizontal tab (i.e. eight spaces).

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

Example 1

INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote

OUTPUT:
E R C
m o o
u a y
s d o
t
R e
o
l
s

Example 2

INPUT:
N=4
Team 1: Royal
Team 2: Mars
Team 3: De Rose
Team 4: Kings

OUTPUT:
R M D K
o a e i
y r n
a s R g
l o s
s
e

Example 3
INPUT:
N = 10

OUTPUT:
INVALID INPUT
Solution:

import java.util.*;

class TeamBanner {

void main() {

Scanner sc = new Scanner(System.in);

// Accept the number of teams

System.out.println("Enter the number of teams (2 < N < 9):");

int N = sc.nextInt();

// Validate N

if (N < 3 || N > 8) {

System.out.println("INVALID INPUT");

return;

// Accept team names

sc.nextLine(); // consume the newline character

String[] teams = new String[N];

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

System.out.println("Team " + (i + 1) + ":");

teams[i] = sc.nextLine();

// Determine the maximum length of the team names

int maxLength = 0;

for (String team : teams) {

if (team.length() > maxLength) {

maxLength = team.length();
}

// Display the teams vertically side by side

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

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

// Print the character at the current position of the team name, or a blank
space if it is out of bounds

if (i < teams[j].length()) {

System.out.print(teams[j].charAt(i));

} else {

System.out.print(" ");

// Print a horizontal tab between team names

if (j < N - 1) {

System.out.print("\t");

System.out.println();

}
Q14.

Write a Program in Java to fill a square matrix of size ‘n*n” in a circular fashion
(clockwise) with natural numbers from 1 to n*n, taking ‘n’ as input.

For example: if n = 4, then n*n = 16, hence the array will be filled as given below.
Solution:

import java.util.Scanner;

public class CircularMatrix {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Accepting input for the size of the matrix

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

int n = sc.nextInt();

// Check if n is valid

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

System.out.println("INVALID INPUT");

return;

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

int num = 1; // Start filling with 1

// Filling the matrix in a circular fashion

int top = 0, bottom = n - 1, left = 0, right = n - 1;

while (top <= bottom && left <= right) {

// Fill top row

for (int i = left; i <= right; i++) {

matrix[top][i] = num++;

top++;
// Fill right column

for (int i = top; i <= bottom; i++) {

matrix[i][right] = num++;

right--;

// Fill bottom row (if there are still rows left)

if (top <= bottom) {

for (int i = right; i >= left; i--) {

matrix[bottom][i] = num++;

bottom--;

// Fill left column (if there are still columns left)

if (left <= right) {

for (int i = bottom; i >= top; i--) {

matrix[i][left] = num++;

left++;

// Display the filled matrix

System.out.println("Filled Matrix:");

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

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

System.out.print(matrix[i][j] + "\t");
}

System.out.println();

}
Q15.

The encryptions of alphabets are to be done as follows:

A =1
B =2
C =3
.
.
.
Z = 26

The potential of a word is found by adding the encrypted value of the alphabets.

Example: KITE

Potential = 11 + 9 + 20 + 5 = 45

Accept a sentence which is terminated by either “ . ” , “ ? ” or “ ! ”. Each word of


sentence is separated by single space. Decode the words according to their
potential and arrange them in ascending order.

Output the result in format given below:

INPUT: THE SKY IS THE LIMIT.

POTENTIAL:

THE = 33

SKY = 55

IS = 28

HE = 33

LIMIT = 63

OUTPUT: IS THE THE SKY LIMIT


Solution:

import java.util.Scanner;

public class WordPotential {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Taking the sentence input

System.out.println("Enter a sentence:");

String sentence = sc.nextLine().trim();

// Check if the sentence ends with a valid punctuation mark

char lastChar = sentence.charAt(sentence.length() - 1);

if (!(lastChar == '.' || lastChar == '?' || lastChar == '!')) {

System.out.println("INVALID INPUT");

return;

// Remove punctuation mark and extra spaces

sentence = sentence.substring(0, sentence.length() - 1).trim();

// Define a maximum number of words (we assume a max of 50 words for this
example)

String[] words = new String[50];

int wordCount = 0;

String word = "";

// Loop through the sentence and extract words

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


char ch = sentence.charAt(i);

if (ch == ' ') {

if (!word.isEmpty()) {

words[wordCount] = word;

wordCount++;

word = ""; // Reset word for the next one

} else {

word += ch;

// Add the last word (if any)

if (!word.isEmpty()) {

words[wordCount] = word;

wordCount++;

// Create an array to store the potential of each word

int[] potentials = new int[wordCount];

// Calculate the potential of each word

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

int potential = 0;

for (int j = 0; j < words[i].length(); j++) {

char ch = words[i].charAt(j);

// Calculate the value of the alphabet (A=1, B=2, ..., Z=26)

if (ch >= 'A' && ch <= 'Z') {


potential += (ch - 'A' + 1);

potentials[i] = potential;

// Sort the words based on their potential using simple sorting (bubble sort)

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

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

if (potentials[i] > potentials[j]) {

// Swap potentials

int temp = potentials[i];

potentials[i] = potentials[j];

potentials[j] = temp;

// Swap the corresponding words

String tempWord = words[i];

words[i] = words[j];

words[j] = tempWord;

// Display the output

System.out.println("OUTPUT: ");

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

System.out.print(words[i] + " ");

System.out.println();
}}

Q16.

Write a Program in Java to input a number and check whether it is a Fascinating


Number or not..

Fascinating Numbers: Some numbers of 3 digits or more exhibit a very interesting


property. The property is such that, when the number is multiplied by 2 and 3, and
both these products are concatenated with the original number, all digits from 1 to 9
are present exactly once, regardless of the number of zeroes.

Let’s understand the concept of Fascinating Number through the following example:

Consider the number 192,


192 x 1 = 192
192 x 2 = 384
192 x 3 = 576

Concatenating the results: 192384576

It could be observed that ‘192384576’ consists of all digits from 1 to 9 exactly once.
Hence, it could be concluded that 192 is a Fascinating Number.

Some examples of fascinating Numbers are: 192, 219, 273, 327, 1902,
1920, 2019 etc.
Solution:

import java.util.Scanner;

class FascinatingNumber {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Take input number from user

System.out.println("Enter a number:");

int num = sc.nextInt();

// Check if the number has 3 digits or more

if (num < 100) {

System.out.println("Not a valid number for Fascinating Number check.");

} else {

// Create the concatenated string of the number and its multiples

String concatenated = "" + num + (num * 2) + (num * 3);

// Check if the concatenated string has all digits from 1 to 9 exactly once

if (isFascinating(concatenated)) {

System.out.println(num + " is a Fascinating Number.");

} else {

System.out.println(num + " is not a Fascinating Number.");

// Method to check if the concatenated string contains all digits from 1 to 9


exactly once
public static boolean isFascinating(String str) {

// Check if the string length is exactly 9

if (str.length() != 9) {

return false;

// Create an array to mark digits

boolean[] digitsPresent = new boolean[10]; // 0-9 digits

// Traverse through the concatenated string

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

int digit = str.charAt(i) - '0'; // Convert char to int

// If the digit is 0 or it has already appeared, return false

if (digit == 0 || digitsPresent[digit]) {

return false;

// Mark the digit as present

digitsPresent[digit] = true;

// If all digits from 1 to 9 are present exactly once, return true

return true;

}
Q17.

A class Adder has been defined to add any two accepted time.

For Example:

Time A – 6 hours 35 minutes

Time B – 7 hours 45 minutes

Their sum= 14 hours 20 minutes

The details of the member of the class are given below:

Class name : Adder

Data member/instance variables :

ar[ ] : integer array to holds two elements

(Hours and minutes)

Member function/methods :

Adder ( ) : constructor to assign 0 to the array


element

void readTime( ) : to accept the elements of the array

order without any duplicates

void addtime(Adder x, Adder y) : adds the time of the two parametrized

object X and Y and stores the sum


in the

current object

void display( ) : displays the array elements with an

appropriate message

Specify the class, Adder giving details of the constructor( ), void readTime( ),
void addtime( )

and void display ( ). Define the main ( ) function to create an object and call the
function

accordingly to enable the task.


Solution:

import java.util.Scanner;

class Adder {

// Data member to hold hours and minutes

int[] ar = new int[2];

// Constructor to initialize array elements to 0

Adder() {

ar[0] = 0; // Hours

ar[1] = 0; // Minutes

// Method to read time for the object

void readTime() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter hours: ");

ar[0] = sc.nextInt(); // Hours

System.out.print("Enter minutes: ");

ar[1] = sc.nextInt(); // Minutes

// Method to add time of two objects and store the sum in the current object

void addTime(Adder x, Adder y) {

this.ar[0] = x.ar[0] + y.ar[0]; // Sum of hours


this.ar[1] = x.ar[1] + y.ar[1]; // Sum of minutes

// Adjust for any overflow of minutes

if (this.ar[1] >= 60) {

this.ar[1] -= 60;

this.ar[0] += 1; // Add 1 hour for every 60 minutes

// Method to display the time

void display() {

System.out.println("Total time: " + ar[0] + " hours " + ar[1] + " minutes");

// Main method to execute the program

public static void main(String[] args) {

// Create two objects of Adder class

Adder time1 = new Adder();

Adder time2 = new Adder();

// Reading time for both objects

System.out.println("Enter details for Time A:");

time1.readTime();

System.out.println("Enter details for Time B:");

time2.readTime();

// Create a third object to store the sum of time1 and time2

Adder sum = new Adder();

sum.addTime(time1, time2); // Add time of time1 and time2


// Display the sum of times

sum.display();

}}

Q18.

Register is an entity which can hold a maximum of 100 names. The register
enables the user to add and remove names from the top most end only. Define a
class Register with the following details:

Class name : Register

Data members/instance variables :

stud[ ] : array to store the names of the


students

cap : stores the maximum capacity of the array

top : to point the index of the top end

Member function/methods :

Register(int max) : constructor to initialize the data member

cap=max, top=-1 and


create the string array

void push(String n) : to add names in the register at the


top if

possible, otherwise
display the message

“OVERFLOW”

String pop( ) : removes and returns the name from


the top

of the register if possible,


otherwise returns

“$$”

void display( ) : display all the names stored in the


register
Write a main function to create an object and call the above member
functions to enable the task.
Solution:

import java.util.Scanner;

class Register {

String[] stud;

int cap;

int top;

// Constructor to initialize the register with the given capacity

Register(int max) {

cap = max;

top = -1;

stud = new String[cap];

// Method to add a name to the top of the register

void push(String n) {

if (top < cap - 1) {

stud[++top] = n;

} else {

System.out.println("OVERFLOW");

// Method to remove a name from the top of the register

String pop() {

if (top >= 0) {

return stud[top--];

} else {
return "$$";

// Method to display all the names in the register

void display() {

if (top == -1) {

System.out.println("No names in the register.");

} else {

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

System.out.println(stud[i]);

// Main function to test the methods

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the maximum capacity of the register: ");

int max = sc.nextInt();

sc.nextLine(); // To consume the newline character

Register reg = new Register(max);

while (true) {

System.out.println("\nChoose an option:");

System.out.println("1. Add name");

System.out.println("2. Remove name");


System.out.println("3. Display all names");

System.out.println("4. Exit");

int choice = sc.nextInt();

sc.nextLine(); // To consume the newline character

switch (choice) {

case 1:

System.out.print("Enter name to add: ");

String name = sc.nextLine();

reg.push(name);

break;

case 2:

String removed = reg.pop();

if (removed.equals("$$")) {

System.out.println("No names to remove.");

} else {

System.out.println("Removed: " + removed);

break;

case 3:

reg.display();

break;

case 4:

System.out.println("Exiting...");

sc.close();

return;

default:

System.out.println("Invalid option.");

}}}}
Q19.

A Library issues books on rental basis at a 2% charge on the cost price of


the book per day. As per the rules of the library, a book can be retained for
7 days without any fine. If a book is returned after 7 days, a fine will also
be charged for the excess days as per the chart given below:

Number of Excess days Fine per day ( in Rs.)

1 to 5 2.00

6 to 10 3.00

above 10 days 5.00

Design a class Library and another class Compute to perform the task. The
details of the two classes are given below:

Class name : Library

Data members/instance variables :

name : name of the book

author : author of the book

price : price of the book

Member function/member methods:

Library(…….) : parameterized constructor to


assign values

to data members

void show( ) : displays the book details

Class name : Compute

d : number of days taken in returning the


book

to store the fine

Member function/member methods:

Compute(…..) : parameterized constructor to


assign values
to data members
of both the classes

void fine( ) : calculates the fine for the excess


days

void display( ) : displays the book details along


with the

number of days,
fine and total amount to

be paid. Total
amount is calculated as:

(2% of price of
book*total number of days)+fine

Write the main ( )to create an object and call the above member functions
to enable the task.
Solution:

import java.util.Scanner;

class Library {

String name; // name of the book

String author; // author of the book

double price; // price of the book

Library(String bName, String bAuthor, double bPrice) {

name = bName;

author = bAuthor;

price = bPrice;

void show() {

System.out.println("Book Name: " + name);

System.out.println("Author: " + author);

System.out.println("Price: Rs. " + price);

class Compute extends Library {

int d; // number of days taken to return the book

Compute(String bName, String bAuthor, double bPrice, int dTaken) {

super(bName, bAuthor, bPrice);

d = dTaken;

}
void fine() {

double fine = 0;

if (d > 7) {

int excessDays = d - 7;

if (excessDays >= 1 && excessDays <= 5) {

fine = excessDays * 2;

} else if (excessDays >= 6 && excessDays <= 10) {

fine = excessDays * 3;

} else if (excessDays > 10) {

fine = excessDays * 5;

double rentalCharge = (2.0 / 100) * price * d;

double totalAmount = rentalCharge + fine;

show();

System.out.println("Days Taken: " + d);

System.out.println("Fine: Rs. " + fine);

System.out.println("Total Amount to Pay: Rs. " + totalAmount);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter Book Name: ");

String bName = sc.nextLine();

System.out.print("Enter Author Name: ");

String bAuthor = sc.nextLine();

System.out.print("Enter Price of the Book: ");


double bPrice = sc.nextDouble();

System.out.print("Enter Number of Days to Return the Book: ");

int dTaken = sc.nextInt();

Compute compute = new Compute(bName, bAuthor, bPrice, dTaken);

compute.fine();

sc.close();

}
Q20.

Given a square matrix list [ ] [ ] of order ‘n’. The maximum value possible for ‘n’ is
20. Input the value for ‘n’ and the positive integers in the matrix and perform the
following tasks:

Display the original matrix

1. Print the row and column position of the largest element of the matrix

2. Print the row and column position of the second largest element of the matrix

3. Sort the elements of the rows in the ascending order and display the new
matrix

Sample Data:

INPUT:

N=3

LIST [ ] [ ]

5 1 3

7 4 6

9 8 2

OUTPUT

5 1 3

7 4 6

9 8 2

The largest element 9 is in row 3 and column 1

The second largest element 8 is in row 3 and column 2

Sorted list

1 3 5

4 6 7

2 8 9
Solution:

import java.util.Scanner;

class MatrixOperations {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the value of N: ");

int n = sc.nextInt();

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

// Input the matrix

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] = sc.nextInt();

// Display the original matrix

System.out.println("\nOriginal Matrix:");

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

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

System.out.print(matrix[i][j] + "\t");

System.out.println();

}
// Find the largest and second largest elements

int largest = Integer.MIN_VALUE;

int secondLargest = Integer.MIN_VALUE;

int largestRow = 0, largestCol = 0;

int secondLargestRow = 0, secondLargestCol = 0;

// Traverse the matrix to find the largest and second largest elements

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

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

if (matrix[i][j] > largest) {

secondLargest = largest;

secondLargestRow = largestRow;

secondLargestCol = largestCol;

largest = matrix[i][j];

largestRow = i;

largestCol = j;

} else if (matrix[i][j] > secondLargest && matrix[i][j] != largest) {

secondLargest = matrix[i][j];

secondLargestRow = i;

secondLargestCol = j;

// Output largest and second largest element positions

System.out.println("\nThe largest element " + largest + " is in row " +


(largestRow + 1) + " and column " + (largestCol + 1));

System.out.println("The second largest element " + secondLargest + " is in row


" + (secondLargestRow + 1) + " and column " + (secondLargestCol + 1));
// Sort each row in ascending order

System.out.println("\nSorted List:");

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

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

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

if (matrix[i][j] > matrix[i][k]) {

int temp = matrix[i][j];

matrix[i][j] = matrix[i][k];

matrix[i][k] = temp;

// Display the sorted matrix

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

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

System.out.print(matrix[i][j] + "\t");

System.out.println();

sc.close();

You might also like