0% found this document useful (0 votes)
9 views124 pages

Ar Comp

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)
9 views124 pages

Ar Comp

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/ 124

NAME-ARYAN SHARMA

CLASS- XII (TWELVE)


SECTION-‘C’
ROLL NUMBER-08
REGISTRATION NUMBER-2023/497
COMPUTER PROJECT FILE
Question 1:

A Prime-Adam integer is a positive integer (without leading zeroes) 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’ is 31, then, 132 = 169, and 312 = 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
ALGORITHM:
isPrime():
Step 1: Start of algorithm.
Step 2: If num <= 1, return false.
Step 3: Set i = 2.
Step 4: While i <= √num, do the following:
Step 4.1: If num % i == 0, return false.
Step 4.2: Increment i by 1.
Step 5: Return true.
Step 6: End of algorithm.

reverse():
Step 1: Start of algorithm.
Step 2: Set rev = 0.
Step 3: While num != 0, do the following:
Step 3.1: Set rev = rev * 10 + num % 10.
Step 3.2: Set num = num / 10.
Step 4: Return rev.
Step 5: End of algorithm.

isAdam():
Step 1: Start of algorithm.
Step 2: Set revNum = reverse(num).
Step 3: Set sqNum = num * num.
Step 4: Set sqRevNum = revNum * revNum.
Step 5: If sqNum == reverse(sqRevNum), return true.
Step 6: Otherwise, return false.
Step 7: End of algorithm.

main():
Step 1: Start of algorithm.
Step 2: Initialize Scanner sc.
Step 3: Prompt the user to enter m, store it in m.
Step 4: Prompt the user to enter n, store it in n.
Step 5: If m > n, print "Invalid Input." and exit.
Step 6: Initialize an array primeAdamNumbers to store results.
Step 7: Set count = 0.
Step 8: For i = m to n, do the following:
Step 8.1: If isPrime(i) == true and isAdam(i) == true, do the following:
Step 8.1.1: Store i in primeAdamNumbers[count].
Step 8.1.2: Increment count by 1.
Step 9: Print "The Prime-Adam integers are:".
Step 10: If count == 0, print "NIL".
Step 11: Else, for j = 0 to count - 1, do the following:
Step 11.1: Print primeAdamNumbers[j].
Step 12: Print "Frequency of Prime-Adam integers is: " + count.
Step 13: Close Scanner sc.
Step 14: End of algorithm.

SOURCE CODE:

import java.util.Scanner;

public class PrimeAdam {

// Function to check if a number is prime


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

// Function to reverse a number


public static int reverse(int num) {
int rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num = num / 10;
}
return rev;
}

// Function to check if a number is an Adam number


public static boolean isAdam(int num) {
int revNum = reverse(num);
int sqNum = num * num;
int sqRevNum = revNum * revNum;
return sqNum == reverse(sqRevNum);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input values for m and n


System.out.print("Enter value for m: ");
int m = sc.nextInt();
System.out.print("Enter value for n: ");
int n = sc.nextInt();

// Validate the input range


if (m > n) {
System.out.println("Invalid Input.");
sc.close();
return;
}

// Variables to store results


int[] primeAdamNumbers = new int[n - m + 1];
int count = 0;

// Find and store all Prime-Adam numbers in the range


for (int i = m; i <= n; i++) {
if (isPrime(i) && isAdam(i)) {
primeAdamNumbers[count] = i;
count++;
}
}

// Output the results


System.out.println("The Prime-Adam integers are:");
if (count == 0) {
System.out.println("NIL");
} else {
for (int i = 0; i < count; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(primeAdamNumbers[i]);
}
System.out.println();
}
System.out.println("Frequency of Prime-Adam integers is: " + count);

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
num int Number to be checked isPrime,
for primality or reverse,
reversed. isAdam
i int Loop index for checking isPrime
primality.
rev int Reversed number reverse
during the reversal
process.
revNum int Reversed version of the isAdam
input number.
sqNum int Square of the original isAdam
number.
sqRevNum int Square of the reversed isAdam
number.
sc Scanner Scanner object to read main
user input.
m int Lower bound of the main
range for finding Prime-
Adam numbers.
n int Upper bound of the main
range for finding Prime-
Adam numbers.
primeAdamNumbers int[] Array to store the main
Prime-Adam numbers
within the range.
count int Counter for the number main
of Prime-Adam
numbers found.
i int Loop index for iterating main
through the range [m,
n].
OUTPUT:
Question 2:

A MOBIUS function M(N) returns the value -1 or 0 or 1 for a natural number (N) by the
following conditions are defined:
When,
M(N) = 1 if N = 1
M(N) = 0 if any prime factor of N is contained in N more than once.
M(N) = (-1)P if N is the product of ‘P’ distinct prime factors.
Write a program to accept a positive natural number (N) and display the MOBIUS result with
proper message.
Design your program which will enable the output in the format given below:
Sample 1:
INPUT: 78
OUTPUT:
78 = 2 × 3 × 13
NUMBER OF DISTINCT PRIME FACTORS = 3
M(78) = -1
Sample 2:
INPUT: 34
OUTPUT:
34 = 2 × 17
NUMBER OF DISTINCT PRIME FACTORS = 2
M(34) = 1
Sample 3:
INPUT: 12
OUTPUT:
12 = 2 × 2 × 3
DUPLICATE PRIME FACTORS
M(12) = 0
Sample 4:
INPUT: 1
OUTPUT:
1=1
NO PRIME FACTORS
M(1) = 1
ALGORITHM:

mobius(int num):
Step 1: Start of algorithm.
Step 2: If `num == 1`, return `1`.
Step 3: Initialize `pCount = 0` to count distinct prime factors.
Step 4: Store the original value of `num` in `originalNum`.
Step 5: Initialize `factorization` as an empty string to store the prime factorization.
Step 6: For `i = 2` to `√num`, do the following:
Step 7: If `num % i == 0`, do the following:
Step 8: Initialize `factorCount = 0` to count occurrences of the prime factor `i`.
Step 9: While `num % i == 0`, do the following:
Step 10: Divide `num` by `i`.
Step 11: Increment `factorCount` by `1`.
Step 12: If `factorization` is empty, set `factorization = i + " x "`.
Step 13: Else, append `i + " x "` to `factorization`.
Step 14: If `factorCount > 1`, remove the last " x " from `factorization`.
Step 15: Print `originalNum + " = " + factorization`.
Step 16: Print "DUPLICATE PRIME FACTORS".
Step 17: Return `0`.
Step 18: Increment `pCount` by `1`.
Step 19: If `num > 1`, do the following:
Step 20: If `factorization` is empty, set `factorization = num`.
Step 21: Else, append `num` to `factorization`.
Step 22: Increment `pCount` by `1`.
Step 23: Else, remove the last " x " from `factorization`.
Step 24: Calculate `mobiusValue = (pCount % 2 == 0) ? 1 : -1`.
Step 25: Print `originalNum + " = " + factorization`.
Step 26: Print "NUMBER OF DISTINCT PRIME FACTORS = " + pCount`.
Step 27: Return `mobiusValue`.
Step 28: End of algorithm.

main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize `Scanner sc`.
Step 3: Prompt the user to input `N`, store it in `N`.
Step 4: Print "OUTPUT:".
Step 5: If `N == 1`, do the following:
Step 6: Print "1 = 1".
Step 7: Print "NO PRIME FACTORS".
Step 8: Print "M(1) = 1".
Step 9: Else, call `mobius(N)` and store the result in `result`.
Step 10: Print "M(" + N + ") = " + result`.
Step 11: Close `Scanner sc`.
Step 12: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class MobiusFunction {

// Function to calculate the Möbius function


public static int mobius(int num) {
if (num == 1) return 1; // M(1) = 1

int pCount = 0; // Count of distinct prime factors


int originalNum = num;
String factorization = ""; // String to store prime factorization

// Iterate through potential prime factors


for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
int factorCount = 0; // Count occurrences of the prime factor i

while (num % i == 0) {
num /= i;
factorCount++;
if (factorization.isEmpty()) {
factorization = i + " x ";
} else {
factorization += i + " x ";
}
}

if (factorCount > 1) {
factorization = factorization.substring(0, factorization.length() - 3);
System.out.println(originalNum + " = " + factorization);
System.out.println("DUPLICATE PRIME FACTORS");
return 0; // M(N) = 0 if any prime factor is repeated
}

pCount++;
}
}

// If num is still greater than 1, then num itself is a prime factor


if (num > 1) {
if (factorization.isEmpty()) {
factorization = num + "";
} else {
factorization += num;
}
pCount++;
} else {
factorization = factorization.substring(0, factorization.length() - 3); // Remove the last "
× "
}

int mobiusValue = (pCount % 2 == 0) ? 1 : -1; // M(N) = (-1)^p

System.out.println(originalNum + " = " + factorization);


System.out.println("NUMBER OF DISTINCT PRIME FACTORS = " + pCount);
return mobiusValue;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input the number


System.out.print("INPUT: ");
int N = sc.nextInt();

// Display the result


System.out.println("OUTPUT:");
if (N == 1) {
System.out.println("1 = 1");
System.out.println("NO PRIME FACTORS");
System.out.println("M(1) = 1");
} else {
int result = mobius(N);
System.out.println("M(" + N + ") = " + result);
}

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
num int Number to calculate the Mӧbius function mobius
for.
pCount int Count of distinct prime factors. mobius
originalNum int Original value of the input number. mobius
factorization String String to store the prime factorization of mobius
the number.
i int Loop index for checking potential prime mobius
factors.
factorCount int Count occurrences of a prime factor. mobius
num int Number to calculate the Mӧbius function mobius
for.
result int Result of the Mӧbius function calculation. main
N int Input number from the user. main
sc Scanner Scanner object to read user input. main

OUTPUT:
Question 3:

A Fascinating number is one which when multiplied by 2 and 3 and then, after the results are
concatenated with the original number, the new number contains all the digits from 1 to 9 exactly
once. There can be any number of zeroes and are to be ignored.
Example: 273
273 × 1 = 273
273 × 2 = 546
273 × 3 = 819
Concatenating the results we get, 273546819 which contains all digits from 1 to 9 exactly once.
Thus, 273 is a Fascinating number.
Accept two positive integers m and n, where m must be less than n and the values of both ‘m’
and ‘n’ must be greater than 99 and less than 10000 as user input. Display all Fascinating
numbers 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 = 100
n = 500
OUTPUT:
THE FASCINATING NUMBERS ARE:
192 219 273 327
FREQUENCY OF FASCINATING NUMBERS IS: 4
Example 2:
INPUT:
m = 900
n = 5000
OUTPUT:
THE FASCINATING NUMBERS ARE:
1902 1920 2019 2190 2703 2730 3027 3270
FREQUENCY OF FASCINATING NUMBERS IS: 8
Example 3:
INPUT:
m = 400
n = 900
OUTPUT:
THE FASCINATING NUMBERS ARE:
NIL
FREQUENCY OF FASCINATING NUMBERS IS: 0
Example 4:
INPUT:
m = 70
n = 450
OUTPUT:
INVALID INPUT
ALGORITHM:

isFasc():
STEP 1: Start of algorithm.
STEP 2: Initialize `n1` to `num`.
STEP 3: Initialize `n2` to `num * 2`.
STEP 4: Initialize `n3` to `num * 3`.
STEP 5: Concatenate `n1`, `n2`, and `n3` as strings and assign to `concat`.
STEP 6: Initialize a boolean array `digPres` of size 10 to `false`.
STEP 7: For each character `ch` in `concat`:
STEP 8: If `ch` is '0', continue to next character.
STEP 9: Convert `ch` to integer `dig`.
STEP 10: If `digPres[dig]` is `true`, return `false` (duplicate digit found).
STEP 11: Set `digPres[dig]` to `true`.
STEP 12: For integer `i` from 1 to 9:
STEP 13: If `digPres[i]` is `false`, return `false` (missing digit found).
STEP 14: Return `true` (all digits 1 to 9 present exactly once).
STEP 15: End of algorithm.

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nm = ".
STEP 4: Read integer input `m` from user.
STEP 5: Print "n = ".
STEP 6: Read integer input `n` from user.
STEP 7: If `m >= n` or `m < 100` or `n >= 10000`:
STEP 8: Print "INVALID INPUT".
STEP 9: Else:
STEP 10: Print "OUTPUT:".
STEP 11: Print "FASCINATING NUMBERS:".
STEP 12: Initialize `cnt` to 0.
STEP 13: For integer `i` from `m` to `n`:
STEP 14: If `isFasc(i)` returns `true`:
STEP 15: Print `i` followed by a space.
STEP 16: Increment `cnt` by 1.
STEP 17: If `cnt` is 0:
STEP 18: Print "NIL".
STEP 19: Else:
STEP 20: Print a newline.
STEP 21: Print "FREQUENCY OF FASCINATING NUMBERS IS: " followed by `cnt`.
STEP 22: Close the `Scanner` object `sc`.
STEP 23: End of algorithm.

SOURCE CODE:

import java.util.Scanner;

public class FascNum {

// Check if a number is fascinating


public static boolean isFasc(int num) {
int n1 = num;
int n2 = num * 2;
int n3 = num * 3;

// Concatenate the results


String concat = Integer.toString(n1) + Integer.toString(n2) + Integer.toString(n3);

// Check if the concatenated string contains all digits from 1 to 9 exactly once
boolean[] digPres = new boolean[10]; // Index 0 to 9

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


if (ch == '0') continue; // Ignore zeroes
int dig = ch - '0';
if (digPres[dig]) {
return false; // Duplicate digit found
}
digPres[dig] = true;
}

// Check if all digits from 1 to 9 are present exactly once


for (int i = 1; i <= 9; i++) {
if (!digPres[i]) {
return false; // Missing digit found
}
}

return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input the range


System.out.print("INPUT:\nm = ");
int m = sc.nextInt();
System.out.print("n = ");
int n = sc.nextInt();

// Validate the input


if (m >= n || m < 100 || n >= 10000) {
System.out.println("INVALID INPUT");
} else {
System.out.println("OUTPUT:");
System.out.println("FASCINATING NUMBERS:");
int cnt = 0;

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


if (isFasc(i)) {
System.out.print(i + " ");
cnt++;
}
}

if (cnt == 0) {
System.out.println("NIL");
} else {
System.out.println();
}

System.out.println("FREQUENCY OF FASCINATING NUMBERS IS: " + cnt);


}

sc.close();
}
}

VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
num int Number to check if it is fascinating. isFasc
n1 int Original number. isFasc
n2 int Number obtained by multiplying num by 2. isFasc
n3 int Number obtained by multiplying num by 3. isFasc
concat String Concatenated string of n1, n2, and n3. isFasc
digPres boolean[] Array to keep track of digits present in isFasc
concat.
ch char Character from the concatenated string. isFasc
dig int Numeric value of the character ch. isFasc
i int Loop index for iterating through the range main
[m, n].
m int Lower bound of the range for finding main
fascinating numbers.
n int Upper bound of the range for finding main
fascinating numbers.
cnt int Counter for the number of fascinating main
numbers found.
sc Scanner Scanner object to read user input. main

OUTPUT:
Question 4:

Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows and
‘N’ is the number of columns such that 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. 2 × 82 + 3 × 81 + 1 × 80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4 × 82 + 0 × 81 + 5 × 80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1 × 82 + 5 × 81 + 6 × 80)
Perform the following tasks on the matrix:
a) Display the original matrix.
b) 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:
144
Decimal Equivalent:
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:
1137
2106
0245
Decimal Equivalent:
607
1094
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.
ALGORITHM:

isValMSize():
STEP 1: Start of algorithm.
STEP 2: Return `true` if `m` is greater than 0 and less than 10, and `n` is greater than 2 and less
than 6.
STEP 3: Else return `false`.
STEP 4: End of algorithm.

isValOcDig():
STEP 1: Start of algorithm.
STEP 2: Return `true` if `digit` is greater than or equal to 0 and less than or equal to 7.
STEP 3: Else return `false`.
STEP 4: End of algorithm.

calcDeci():
STEP 1: Start of algorithm.
STEP 2: Initialize `deciVal` to 0.
STEP 3: Initialize `power` to the length of `octR` minus 1.
STEP 4: For each `digit` in `octR`:
STEP 5: Add `digit * Math.pow(8, power)` to `deciVal`.
STEP 6: Decrement `power` by 1.
STEP 7: Return `deciVal`.
STEP 8: End of algorithm.

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nM = ".
STEP 4: Read integer input `m` from user.
STEP 5: Print "N = ".
STEP 6: Read integer input `n` from user.
STEP 7: If `!isValMSize(m, n)`:
STEP 8: Print "Out of range.".
STEP 9: Close `Scanner` object `sc`.
STEP 10: Return from function.
STEP 11: Initialize a 2D array `matrix` of size `m` by `n`.
STEP 12: For integer `i` from 0 to `m - 1`:
STEP 13: Print "Enter elements for row " followed by `i + 1` and ": ".
STEP 14: For integer `j` from 0 to `n - 1`:
STEP 15: Read integer input `ele` from user.
STEP 16: If `!isValOcDig(ele)`:
STEP 17: Print "Invalid Input.".
STEP 18: Close `Scanner` object `sc`.
STEP 19: Return from function.
STEP 20: Set `matrix[i][j]` to `ele`.
STEP 21: Print "OUTPUT:\nFilled Matrix:".
STEP 22: For integer `i` from 0 to `m - 1`:
STEP 23: For integer `j` from 0 to `n - 1`:
STEP 24: Print `matrix[i][j]` followed by a space.
STEP 25: Print a newline.
STEP 26: Print "Decimal Equivalent:".
STEP 27: For integer `i` from 0 to `m - 1`:
STEP 28: Extract row `matrix[i]` into `row`.
STEP 29: Call `calcDeci(row)` and assign result to `deciEq`.
STEP 30: Print `deciEq`.
STEP 31: Close `Scanner` object `sc`.
STEP 32: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class MatOctToDeci {


// Function to validate input for M and N
public static boolean isValMSize(int m, int n) {
return (m > 0 && m < 10) && (n > 2 && n < 6);
}

// Function to check if a number is a valid octal digit


public static boolean isValOcDig(int digit)
{
return digit >= 0 && digit <= 7;
}

// Function to calculate the decimal equivalent of an octal number represented by an array


public static int calcDeci(int[] octR) {
int deciVal = 0;
int power = octR.length - 1;

for (int digit : octR) {


deciVal += digit * Math.pow(8, power);
power--;
}

return deciVal;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input matrix dimensions


System.out.print("INPUT:\nM = ");
int m = sc.nextInt();
System.out.print("N = ");
int n = sc.nextInt();

// Validate the dimensions


if (!isValMSize(m, n)) {
System.out.println("Out of range.");
sc.close();
return;
}

// Initialize the matrix


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

// Input the matrix eles


for (int i = 0; i < m; i++) {
System.out.print("Enter elements for row " + (i + 1) + ": ");
for (int j = 0; j < n; j++) {
int ele = sc.nextInt();
if (!isValOcDig(ele)) {
System.out.println("Invalid Input.");
sc.close();
return;
}
matrix[i][j] = ele;
}
}

// Display the filled matrix


System.out.println("OUTPUT:\nFilled 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 the decimal equivalents


System.out.println("Decimal Equivalent:");
for (int i = 0; i < m; i++) {
int[] row = matrix[i];
int deciEq = calcDeci(row);
System.out.println(deciEq);
}

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
m int Represents the number of rows in the matrix. main method
n int Represents the number of columns in the matrix. main method
matrix int[][] A 2D array to hold the matrix of octal digits. main method
ele int Temporary variable to store each matrix element input. main method
i int Loop index for rows of the matrix. main method
j int Loop index for columns of the matrix. main method
octR int[] Array representing a single row of the matrix. calcDeci method
deciVal int Holds the decimal equivalent of the octal number. calcDeci method
power int Power of 8 used in decimal conversion calculation. calcDeci method
digit int Each octal digit from the row array during conversion. calcDeci method
deciEq int Holds the decimal equivalent for each row of the matrix. main method
sc Scanner Scanner object for reading user input. main method

OUTPUT:
Question 5:

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
ALGORITHM:

isLeap():
STEP 1: Start of algorithm.
STEP 2: Return `true` if `yr % 4 == 0` and `yr % 100 != 0`, or `yr % 400 == 0`.
STEP 3: Else return `false`.
STEP 4: End of algorithm.

genDate():
STEP 1: Start of algorithm.
STEP 2: If `day` is less than 1 or greater than `(isLeap(yr) ? 366 : 365)`, return `null` (invalid day
number).
STEP 3: Initialize `dArr` to `leapDays` if `isLeap(yr)` is `true`, otherwise `days`.
STEP 4: Initialize `mon` to 0.
STEP 5: While `day` is greater than `dArr[mon]`:
STEP 6: Subtract `dArr[mon]` from `day`.
STEP 7: Increment `mon` by 1.
STEP 8: Return `day + " " + getMon(mon) + ", " + yr`.
STEP 9: End of algorithm.

getMon():
STEP 1: Start of algorithm.
STEP 2: Initialize `mons` array with month names.
STEP 3: Return `mons[mon]`.
STEP 4: End of algorithm.

getSuf():
STEP 1: Start of algorithm.
STEP 2: If `n` is between 11 and 13 inclusive, return "TH".
STEP 3: Switch on `n % 10`:
STEP 4: If `n % 10` is 1, return "ST".
STEP 5: If `n % 10` is 2, return "ND".
STEP 6: If `n % 10` is 3, return "RD".
STEP 7: Else return "TH".
STEP 8: End of algorithm.

addDays():
STEP 1: Start of algorithm.
STEP 2: Initialize `dArr` to `leapDays` if `isLeap(yr)` is `true`, otherwise `days`.
STEP 3: Add `n` to `day`.
STEP 4: While `day` is greater than `(isLeap(yr) ? 366 : 365)`:
STEP 5: Subtract `(isLeap(yr) ? 366 : 365)` from `day`.
STEP 6: Increment `yr` by 1.
STEP 7: Initialize `mon` to 0.
STEP 8: While `day` is greater than `dArr[mon]`:
STEP 9: Subtract `dArr[mon]` from `day`.
STEP 10: Increment `mon` by 1.
STEP 11: Return `day + " " + getMon(mon) + ", " + yr`.
STEP 12: End of algorithm.

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "DAY NUMBER: ".
STEP 4: Read integer input `day` from user.
STEP 5: Print "YEAR: ".
STEP 6: Read integer input `yr` from user.
STEP 7: Print "DAYS AFTER (N DAYS): ".
STEP 8: Read integer input `n` from user.
STEP 9: If `n` is less than 1 or greater than 100:
STEP 10: Print "DATE NUMBER AFTER (N DAYS) OUT OF RANGE".
STEP 11: Close `Scanner` object `sc`.
STEP 12: Return from function.
STEP 13: Call `genDate(day, yr)` and assign result to `date`.
STEP 14: If `date` is `null`:
STEP 15: Print "DAY NUMBER OUT OF RANGE".
STEP 16: Close `Scanner` object `sc`.
STEP 17: Return from function.
STEP 18: Call `addDays(day, n, yr)` and assign result to `futDate`.
STEP 19: Split `futDate` by space into `prts`.
STEP 20: Parse the third part of `prts` into `futYr`.
STEP 21: Initialize `maxYr` to `yr + 100`.
STEP 22: If `futYr` is equal to `maxYr` and `day` is greater than `n`:
STEP 23: Print "DATE AFTER " + n + " OUT OF RANGE".
STEP 24: Close `Scanner` object `sc`.
STEP 25: Return from function.
STEP 26: Print "OUTPUT:".
STEP 27: Parse the day number from `date` and store in `dayNum`.
STEP 28: Print "DATE: " + `dayNum` + `getSuf(dayNum)` + " " + `date.substring(03)`.
STEP 29: Parse the future day number from `futDate` and store in `futDayNum`.
STEP 30: Print "DATE AFTER " + n + " DAYS: " + `futDayNum` + `getSuf(futDayNum)` + " "
+ `futDate.substring(02)`.
STEP 31: Close `Scanner` object `sc`.
STEP 32: End of algorithm
.
SOURCE CODE:

import java.util.Scanner;

public class DateCalc {


// Array of days in each month for non-leap years
static final int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Array of days in each month for leap years
static final int[] leapDays = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Check if a year is a leap year


public static boolean isLeap(int yr) {
return (yr % 4 == 0 && yr % 100 != 0) || (yr % 400 == 0);
}

// Generate date from day number and year


public static String genDate(int day, int yr) {
if (day < 1 || day > (isLeap(yr) ? 366 : 365)) {
return null; // Invalid day number
}
int[] dArr = isLeap(yr) ? leapDays : days;
int mon = 0;
while (day > dArr[mon]) {
day -= dArr[mon];
mon++;
}
return day + " " + getMon(mon) + ", " + yr;
}

// Get the name of the month


public static String getMon(int mon) {
String[] mons = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER",
"DECEMBER" };
return mons[mon];
}

// Get suffix for the day of the month


public static String getSuf(int n) {
if (n >= 11 && n <= 13) {
return "TH";
}
switch (n % 10) {
case 1:
return "ST";
case 2:
return "ND";
case 3:
return "RD";
default:
return "TH";
}
}

// Add N days to a date and return the new date


public static String addDays(int day, int n, int yr) {
int[] dArr = isLeap(yr) ? leapDays : days;
day += n;

while (day > (isLeap(yr) ? 366 : 365)) {


day -= isLeap(yr) ? 366 : 365;
yr++;
}

int mon = 0;
while (day > dArr[mon]) {
day -= dArr[mon];
mon++;
}
return day+ " " + getMon(mon) + ", " + yr;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("DAY NUMBER: ");


int day = sc.nextInt();

System.out.print("YEAR: ");
int yr = sc.nextInt();

System.out.print("DAYS AFTER (N DAYS): ");


int n = sc.nextInt();

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


System.out.println("DATE NUMBER AFTER (N DAYS) OUT OF RANGE");
sc.close();
return;
}

String date = genDate(day, yr);


if (date == null) {
System.out.println("DAY NUMBER OUT OF RANGE");
sc.close();
return;
}

String futDate = addDays(day, n, yr);


String[] prts = futDate.split(" ");
int futYr = Integer.parseInt(prts[2]);
int maxYr = yr + 100;

if ((futYr == maxYr && day > n)) {


System.out.println("DATE AFTER " + n + "OUT OF RANGE");
sc.close();
return;
}

System.out.println("OUTPUT:");
int dayNum = Integer.parseInt(date.split(" ")[0]);
System.out.println("DATE: " + dayNum + getSuf(dayNum) + " " + date.substring(03));

int futDayNum = Integer.parseInt(futDate.split(" ")[0]);


System.out.println("DATE AFTER " + n + " DAYS: " + futDayNum + getSuf(futDayNum)
+ " " + futDate.substring(02));

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
days int[] Array of days in each month for non-leap years. Class level

leapDays int[] Array of days in each month for leap years. Class level

yr int Represents a year. isLeap,


genDate,
addDays,
main
methods
day int Represents the day number in a year. genDate,
addDays,
main
methods
mon int Represents the month index (0-based) in the year. genDate,
addDays
methods
dArr int[] Array representing the number of days in each month for the genDate,
current year. addDays
methods
n int Represents the number of days to add to the date. addDays,
main
methods
date String The formatted date string for a given day and year. main method

futDate String The future date string after adding n days. addDays,
main
methods
prts String[] Array of date parts split from futDate. main method

futYr int Year extracted from futDate. main method

maxYr int Maximum year considered for range validation. main method

dayNum int Day number extracted from date for output. main method

futDayNum int Day number extracted from futDate for output. main method

OUTPUT:
Question 6:

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:
a) Sort the elements of the single-dimensional array in ascending order using any standard
sorting technique and display the sorted elements.
b) 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:
1 2 5 8
1 2 5 1
1 2 1 2
1 1 2 5
c) 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
1 3 7
1 3 1
1 1 3
Example 2:
INPUT:
N = 13
OUTPUT:
MATRIX SIZE OUT OF RANGE

ALGORITHM:
sortArray(int[] array)
STEP 1: Start of algorithm.
STEP 2: Use the Arrays.sort() method to sort the array in ascending order.
STEP 3: End of algorithm.

fillMatrix(int[][] matrix, int[] sortedArray)


STEP 1: Start of algorithm.
STEP 2: Initialize N to the size of the matrix (number of rows and columns).
STEP 3: For each row index i from 0 to N−1N-1N−1:
STEP 3.1: For each column index j from 0 to N−1N-1N−1:
STEP 3.1.1: Set the matrix element at [i][j] to sortedArray[(i + j) % sortedArray.length].
STEP 4: End of algorithm.

displayMatrix(int[][] matrix)
STEP 1: Start of algorithm.
STEP 2: For each row in the matrix:
STEP 2.1: For each element in the row:
STEP 2.1.1: Print the element followed by a space.
STEP 2.2: Print a newline character after printing all elements of the row.
STEP 3: End of algorithm.

SOURCE CODE:

import java.util.Arrays;
import java.util.Scanner;

public class MatrixFiller {


// Function to sort the array in ascending order
public static void sortArray(int[] array) {
Arrays.sort(array);
}

// Function to fill the matrix based on the sorted array


public static void fillMatrix(int[][] matrix, int[] sortedArray) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = sortedArray[(i + j) % sortedArray.length];
}
}
}

// Function to display the matrix


public static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input for matrix size


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

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


System.out.println("MATRIX SIZE OUT OF RANGE");
sc.close();
return;
}

// Initialize single-dimensional array


int[] array = new int[N];
System.out.print("Enter " + N + " positive integers for the array: ");
for (int i = 0; i < N; i++) {
array[i] = sc.nextInt();
}

// Sort the array


sortArray(array);

// Display sorted array


System.out.print("SORTED ARRAY: ");
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();

// Initialize square matrix


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

// Fill the matrix


fillMatrix(matrix, array);

// Display the filled matrix


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

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
array int[] Single-dimensional array of integers to be sorted. Parameter in
sortArray
method
matrix int[][] 2D square matrix to be filled. Parameter in
fillMatrix
method and
displayMatri
x method

sortedArray int[] Sorted single-dimensional array used to fill the matrix. Parameter in
fillMatrix
method
N int Size of the square matrix (number of rows and columns). Local variable
in fillMatrix
method
i int Row index used for iterating through the matrix. Local variable
in fillMatrix
method
j int Column index used for iterating through the matrix. Local variable
in fillMatrix
method
day int Day number for generating dates and calculating future dates. Parameter in
genDate and
addDays
methods, and
in main
method
yr int Year for generating dates and calculating future dates. Parameter in
genDate,
addDays
methods, and
in main
method
sortedArray int[] Sorted array used to fill the matrix in a specific format. Parameter in
fillMatrix
method
date String Formatted date string generated from the day number and Local variable
year. in main
method
futDate String Formatted future date string after adding days. Local variable
in main
method
prts String[] Array of strings obtained by splitting futDate. Local variable
in main
method
futYr int Year component of the future date. Local variable
in main
method
maxYr int Maximum year limit for date calculation. Local variable
in main
method
dayNum int Day number extracted from the date string. Local variable
in main
method
futDayNum int Future day number extracted from the futDate string. Local variable
in main
method

OUTPUT:
Question 7:

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, 7 and 5, 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 = 30
OUTPUT:
Prime numbers are:
7, 23
11, 19
13, 17
Example 3:
INPUT:
N = 17
OUTPUT:
Invalid input. Number is odd.
Example 4:
INPUT:
N = 126
OUTPUT:
Invalid input. Number is out of range
.

ALGORITHM:

isPrime():
STEP 1: Start of algorithm.
STEP 2: If `num` is less than or equal to 1, return `false`.
STEP 3: For integer `i` from 2 to `sqrt(num)`:
STEP 4: If `num % i` is 0, return `false` (not a prime).
STEP 5: Return `true` (is a prime).
STEP 6: End of algorithm.

findPrimePairs():
STEP 1: Start of algorithm.
STEP 2: Print "Prime pairs are:".
STEP 3: For integer `i` from 3 to `N / 2`, increment by 2:
STEP 4: If `isPrime(i)` and `isPrime(N - i)`:
STEP 5: Print `i` and `N - i` as a pair.
STEP 6: End of algorithm.

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: If `N` is odd or `N` is less than 10 or greater than 50:
STEP 6: Print "OUTPUT:\nInvalid input. Number is " followed by "out of range." if `N` is even,
or "odd." if `N` is odd.
STEP 7: Else call `findPrimePairs(N)`.
STEP 8: Close `Scanner` object `sc`.
STEP 9: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class GoldbachNumber {

// Function to check if a number is prime


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

// Function to find and display prime pairs whose sum is N


public static void findPrimePairs(int N) {
System.out.println("Prime pairs are:");
for (int i = 3; i <= N / 2; i += 2) {
if (isPrime(i) && isPrime(N - i)) {
System.out.println(i + ", " + (N - i));
}
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("INPUT:\nN = ");
int N = sc.nextInt();

if (N % 2 != 0 || N < 10 || N > 50) {


System.out.println("OUTPUT:\nInvalid input. Number is " + (N % 2 == 0 ? "out of
range." : "odd."));
} else {
findPrimePairs(N);
}

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
num int The integer value to check if it's prime. Parameter in
isPrime
method
i int Loop variable used for checking divisors of num. Local variable
in isPrime
method
N int The integer input number to find prime pairs for. Parameter in
findPrimePai
rs method
and local
variable in
main method

sc Scanner Scanner object used to read user input. Local variable


in main
method
i int Loop variable for iterating through potential prime pairs. Local variable
in
findPrimePai
rs method

OUTPUT:
Question 8:

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.
ALGORITHM:

displayTeams():
STEP 1: Start of algorithm.
STEP 2: Initialize `maxLength` to 0.
STEP 3: For integer `i` from 0 to `numTeams - 1`:
STEP 4: If `teams[i].length()` is greater than `maxLength`:
STEP 5: Set `maxLength` to `teams[i].length()`.
STEP 6: For integer `i` from 0 to `maxLength - 1`:
STEP 7: For integer `j` from 0 to `numTeams - 1`:
STEP 8: If `i` is less than `teams[j].length()`:
STEP 9: Print `teams[j].charAt(i)` followed by two tabs.
STEP 10: Else print two tabs.
STEP 11: Print a newline.
STEP 12: End of algorithm.

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: Consume newline character.
STEP 6: If `N` is less than or equal to 2 or greater than or equal to 9:
STEP 7: Print "OUTPUT:\nInvalid input."
STEP 8: Close `Scanner` object `sc`.
STEP 9: Return from function.
STEP 10: Initialize a `String` array `teams` of size `N`.
STEP 11: For integer `i` from 0 to `N - 1`:
STEP 12: Print "Team " followed by `i + 1` and ": ".
STEP 13: Read a `String` input from user and store in `teams[i]`.
STEP 14: Print "OUTPUT:".
STEP 15: Call `displayTeams(teams, N)`.
STEP 16: Close `Scanner` object `sc`.
STEP 17: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class VerticalBanner {

public static void displayTeams(String[] teams, int numTeams) {


// Calculate the maximum length of team names
int maxLength = 0;
for (int i = 0; i < numTeams; i++) {
if (teams[i].length() > maxLength) {
maxLength = teams[i].length();
}
}

// Display teams vertically


for (int i = 0; i < maxLength; i++) {
for (int j = 0; j < numTeams; j++) {
if (i < teams[j].length()) {
System.out.print(teams[j].charAt(i) + "\t\t");
} else {
System.out.print(" \t\t");
}
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.nextLine(); // Consume newline

if (N <= 2 || N >= 9) {
System.out.println("OUTPUT:\nInvalid input.");
} else {
String[] teams = new String[N];
for (int i = 0; i < N; i++) {
System.out.print("Team " + (i + 1) + ": ");
teams[i] = sc.nextLine();
}

System.out.println("OUTPUT:");
displayTeams(teams, N);
}

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Data Description Scope
Name Type
teams String[] Array of team names. Parameter in displayTeams
method and local variable in
main method
numTeams int Number of teams (length of the Parameter in displayTeams
teams array). method and local variable in
main method
maxLength int Maximum length of team Local variable in displayTeams
names in the teams array. method
i int Loop variable used to iterate Local variable in displayTeams
over the rows of characters to method
display.
j int Loop variable used to iterate Local variable in displayTeams
over the team names. method
N int Number of teams entered by Local variable in main method
the user.
sc Scanner Scanner object used to read Local variable in main method
user input.
teams[i] String Team name at index i in the Local variable in main method
teams array.

OUTPUT:
Question 9:

A company manufactures packing cartons in four sizes, i.e. cartons to accomodate 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
ALGORITHM:

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: Consume newline character.
STEP 6: If `N` is less than 0 or greater than 1000:
STEP 7: Print "OUTPUT:\nINVALID INPUT".
STEP 8: Close `Scanner` object `sc`.
STEP 9: Return from function.
STEP 10: Calculate `cartons48` as `N / 48`.
STEP 11: Calculate `cartons24` as `(N % 48) / 24`.
STEP 12: Calculate `cartons12` as `((N % 48) % 24) / 12`.
STEP 13: Calculate `cartons6` as `(((N % 48) % 24) % 12) / 6`.
STEP 14: Calculate `remainingBoxes` as `(((N % 48) % 24) % 12) % 6`.
STEP 15: Calculate `totalCartons` as `cartons48 + cartons24 + cartons12 + cartons6`.
STEP 16: If `remainingBoxes` is greater than 0:
STEP 17: Increment `cartons6` by 1.
STEP 18: Increment `totalCartons` by 1.
STEP 19: Print "OUTPUT:".
STEP 20: Print "48 * " + `cartons48` + " = " + `(cartons48 * 48)` if `cartons48` is not 0.
STEP 21: Print "24 * " + `cartons24` + " = " + `(cartons24 * 24)` if `cartons24` is not 0.
STEP 22: Print "12 * " + `cartons12` + " = " + `(cartons12 * 12)` if `cartons12` is not 0.
STEP 23: Print "6 * " + `cartons6` + " = " + `(cartons6 * 6)` if `cartons6` is not 0.
STEP 24: If `remainingBoxes` is greater than 0:
STEP 25: Print "Remaining boxes = " + `remainingBoxes` + " * 1 = " + `remainingBoxes`.
STEP 26: Else if `remainingBoxes` is 0:
STEP 27: Print "Remaining boxes = 0".
STEP 28: Else print "Remaining boxes do not exist!".
STEP 29: Print "Total number of boxes = " + `N`.
STEP 30: Print "Total number of cartons = " + `totalCartons`.
STEP 31: Close `Scanner` object `sc`.
STEP 32: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class PackingCartons {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.nextLine(); // Consume newline

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


System.out.print("OUTPUT:\nINVALID INPUT");
} else {
int cartons48 = N / 48;
int cartons24 = (N % 48) / 24;
int cartons12 = ((N % 48) % 24) / 12;
int cartons6 = (((N % 48) % 24) % 12) / 6;
int remainingBoxes = (((N % 48) % 24) % 12) % 6;

int totalCartons = cartons48 + cartons24 + cartons12 + cartons6;


if (remainingBoxes > 0) {
cartons6++;
totalCartons++;
}

System.out.print("OUTPUT:");
System.out.print(cartons48!=0?("\n48 * " + cartons48 + " = " + (cartons48 * 48)):"");
System.out.print(cartons24!=0?"\n24 * " + cartons24 + " = " + (cartons24 * 24):"");
System.out.print(cartons12!=0?("\n12 * " + cartons12 + " = " + (cartons12 * 12)):"");
System.out.print(cartons6!=0?("\n6 * " + cartons6 + " = " + (cartons6 * 6)):"");
if (remainingBoxes > 0) {
System.out.print("\nRemaining boxes = " + remainingBoxes + " * 1 = " +
remainingBoxes);
}else if (remainingBoxes ==0)
System.out.print("\nRemaining boxes = 0");
else
System.out.print("\n Remaining boxes do not exist! ");
System.out.print("\nTotal number of boxes = " + N);
System.out.print("\nTotal number of cartons = " + totalCartons);
}

sc.close();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Name Data Description Scope
Type
N int Number of items to be packed into cartons. Local
variable in
main
method
cartons48 int Number of 48-item cartons needed. Local
variable in
main
method
cartons24 int Number of 24-item cartons needed. Local
variable in
main
method
cartons12 int Number of 12-item cartons needed. Local
variable in
main
method
cartons6 int Number of 6-item cartons needed. Local
variable in
main
method
remainingBoxes int Number of remaining items that do not fit into a carton. Local
variable in
main
method
totalCartons int Total number of cartons required, including any Local
additional ones for remaining items. variable in
main
method
sc Scanner Scanner object used to read user input. Local
variable in
main
method
OUTPUT:
Question 10:

The result of a quiz competition is to be prepared as follows:


The quiz has five questions with four multiple choices (A, B, C, D), with each question carrying
1 mark for the correct answer. Design a program to accept the number of participants N such that
N must be greater than 3 and less than 11. Create a double-dimensional array of size (N * 5) to
store the answers of each participant row-wise. Calculate the marks for each participant by
matching the correct answer stored in a single-dimensional array of size 5. Display the scores for
each participant and also the participants(s) having the highest score.
Example: If the value of N = 4, then the array would be:
Q1 Q2 Q3 Q4 Q5
Participant
1 A B B C A
Participant
2 D A D C B
Participant
3 A A B A C
Participant
4 D C C A B
Key to the
question: D C C A B
Note: Array entries are line fed (i.e. one entry per line)
Test your program for the following data and some random data.
Example 1:
INPUT:
N=5
Participant 1 D A B C C
Participant 2 A A D C B
Participant 3 B A C D B
Participant 4 D A D C B
Participant 5 B C A D D
Key: B C D A A
OUTPUT:
Scores:
Participant 1 = 0
Participant 2 = 1
Participant 3 = 1
Participant 4 = 1
Participant 5 = 2
Highest Score: Participant 5
Example 2:
INPUT:
N=4
Participant 1 A C C B D
Participant 2 B C A A C
Participant 3 B C B A A
Participant 4 C C D D B
Key: A C D B B
OUTPUT:
Scores:
Participant 1 = 3
Participant 2 = 1
Participant 3 = 1
Participant 4 = 3
Highest score:
Participant 1
Participant 4
Example 3:
INPUT:
N = 12
OUTPUT:
INPUT SIZE OUT OF RANGE.
ALGORITHM:

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: Consume newline character.
STEP 6: If `N` is less than or equal to 3 or greater than or equal to 11:
STEP 7: Print "OUTPUT:\nINPUT SIZE OUT OF RANGE."
STEP 8: Close `Scanner` object `sc`.
STEP 9: Return from function.
STEP 10: Initialize a `String` 2D array `answers` with dimensions `N` x 5.
STEP 11: Print "Enter participant's answers:".
STEP 12: For integer `i` from 0 to `N - 1`:
STEP 13: Print "Participant " followed by `i + 1` and " ".
STEP 14: Read a `String` input from user, trim it, and split it into parts, then store in
`answers[i]`.
STEP 15: Print "Key: ".
STEP 16: Read a `String` input from user, trim it, and split it into parts, then store in `key`.
STEP 17: Call `calculateScores(answers, key)` and store the result in `scores`.
STEP 18: Call `displayScores(scores)`.
STEP 19: Close `Scanner` object `sc`.
STEP 20: End of algorithm.

calculateScores():
STEP 1: Start of algorithm.
STEP 2: Initialize an `int` array `scores` with size equal to the number of participants.
STEP 3: For integer `i` from 0 to `answers.length - 1`:
STEP 4: For integer `j` from 0 to `answers[i].length - 1`:
STEP 5: If `answers[i][j]` equals `key[j]`:
STEP 6: Increment `scores[i]` by 1.
STEP 7: Return `scores`.
STEP 8: End of algorithm.

displayScores():
STEP 1: Start of algorithm.
STEP 2: Print "OUTPUT:\nScores:".
STEP 3: For integer `i` from 0 to `scores.length - 1`:
STEP 4: Print "Participant " followed by `i + 1` and " = " followed by `scores[i]`.
STEP 5: Initialize `maxScore` to 0.
STEP 6: For each `score` in `scores`:
STEP 7: If `score` is greater than `maxScore`:
STEP 8: Set `maxScore` to `score`.
STEP 9: Print "Highest score:".
STEP 10: For integer `i` from 0 to `scores.length - 1`:
STEP 11: If `scores[i]` equals `maxScore`:
STEP 12: Print "Participant " followed by `i + 1`.
STEP 13: End of algorithm.

SOURCE CODE:

import java.util.Scanner;
public class QuizCompetition {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.nextLine(); // Consume newline

if (N <= 3 || N >= 11) {


System.out.println("OUTPUT:\nINPUT SIZE OUT OF RANGE.");
} else {
String[][] answers = new String[N][5];
System.out.println("Enter participant's answers:");
for (int i = 0; i < N; i++) {
System.out.print("Participant " + (i + 1) + " ");
answers[i] = sc.nextLine().trim().split("\\s+");
}

System.out.print("Key: ");
String[] key = sc.nextLine().trim().split("\\s+");

int[] scores = calculateScores(answers, key);


displayScores(scores);
}

sc.close();
}

private static int[] calculateScores(String[][] answers, String[] key) {


int[] scores = new int[answers.length];
for (int i = 0; i < answers.length; i++) {
for (int j = 0; j < answers[i].length; j++) {
if (answers[i][j].equals(key[j])) {
scores[i]++;
}
}
}
return scores;
}

private static void displayScores(int[] scores) {


System.out.println("OUTPUT:\nScores:");
for (int i = 0; i < scores.length; i++) {
System.out.println("Participant " + (i + 1) + " = " + scores[i]);
}

int maxScore = 0;
for (int score : scores) {
if (score > maxScore) {
maxScore = score;
}
}

System.out.println("Highest score:");
for (int i = 0; i < scores.length; i++) {
if (scores[i] == maxScore) {
System.out.println("Participant " + (i + 1));
}
}
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
N int Number of participants in the quiz competition. Local variable in
main method

answers String[] 2D array holding the answers of each participant. Local variable in
[] main method

key String[] Array holding the correct answers for the quiz. Local variable in
main method

scores int[] Array holding the score of each participant based on correct Local variable in
answers. calculateScor
es method
i int Loop variable used to iterate over participants and answers. Local variable in
main,
calculateScor
es, and
displayScores
methods
j int Loop variable used to iterate over answers for each Local variable in
participant. calculateScor
es method

maxScore int The highest score among all participants. Local variable in
displayScores
method

sc Scanner Scanner object used to read user input. Local variable in


main method

OUTPUT:
Question 11:

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/a B/b C/c D/d E/e F/f G/g H/h I/i J/j K/k L/l M/m
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
S/ W/
N/n O/o P/p Q/q R/r s T/t U/u V/v w X/x Y/y Z/z
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! Ubj ner lbh?
Example 2:
INPUT:
Encryption helps to secure data.
OUTPUT:
The cipher text is:
Rapelcgvba urycf gb frpher qngn.
Example 3:
INPUT:
You
OUTPUT:
INVALID LENGTH
ALGORITHM:

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `scanner`.
STEP 3: Print "INPUT:".
STEP 4: Print "Enter the plain text: ".
STEP 5: Read `plainText` input from user.
STEP 6: If the length of `plainText` is less than or equal to 3 or greater than or equal to 100:
STEP 7: Print "OUTPUT:\nINVALID LENGTH".
STEP 8: Close `Scanner` object `scanner`.
STEP 9: Return from function.
STEP 10: Call `encrypt(plainText)` and store the result in `cipherText`.
STEP 11: Print "OUTPUT:\nThe cipher text is:\n" followed by `cipherText`.
STEP 12: Close `Scanner` object `scanner`.
STEP 13: End of algorithm.

encrypt():
STEP 1: Start of algorithm.
STEP 2: Initialize a `StringBuilder` object `cipherText`.
STEP 3: For integer `i` from 0 to `plainText.length() - 1`:
STEP 4: Get character `ch` from `plainText` at index `i`.
STEP 5: If `ch` is a letter:
STEP 6: Determine `base` as 'A' if `ch` is uppercase, else 'a'.
STEP 7: Update `ch` as `(((ch - base + 13) % 26) + base)`.
STEP 8: Append `ch` to `cipherText`.
STEP 9: Return `cipherText.toString()`.
STEP 10: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class CaesarCipher {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("INPUT:");
System.out.print("Enter the plain text: ");
String plainText = scanner.nextLine();

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


System.out.println("OUTPUT:\nINVALID LENGTH");
} else {
String cipherText = encrypt(plainText);
System.out.println("OUTPUT:\nThe cipher text is:\n" + cipherText);
}

scanner.close();
}

private static String encrypt(String plainText) {


StringBuilder cipherText = new StringBuilder();

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


char ch = plainText.charAt(i);

if (Character.isLetter(ch)) {
char base = Character.isUpperCase(ch) ? 'A' : 'a';
ch = (char) (((ch - base + 13) % 26) + base);
}

cipherText.append(ch);
}

return cipherText.toString();
}
}
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
scanner Scanner Scanner object used to read user input. Local variable
in main
method
plainText String The input text provided by the user to be encrypted. Local variable
in main
method
cipherText String The encrypted text generated from the plain text. Local variable
in main
method and
return value
of encrypt
method
ch char The current character being processed from plainText. Local variable
in encrypt
method
base char The base character for ASCII calculations ('A' for uppercase, 'a' Local variable
for lowercase). in encrypt
method
i int Loop variable used to iterate over each character of plainText. Local variable
in encrypt
method

OUTPUT:
Question 12:

Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than
100. Find the smallest integer that is greater than M and whose digits add up to N. For example,
if M = 100 and N = 11, then the smallest integer greater than 100 whose digits add up to 11 is
119.
Write a program to accept the numbers M and N from the user and print the smallest required
number whose sum of all its digits is equal to N. Also, print the total number of digits present in
the required number. The program should check for the validity of the inputs and display an
appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1:
INPUT:
M = 100
N = 11
OUTPUT:
The required number = 119
Total number of digits = 3
Example 2:
INPUT:
M = 1500
N = 25
OUTPUT:
The required number = 1699
Total number of digits = 4
Example 3:
INPUT:
M = 99
N = 11
OUTPUT:
INVALID INPUT
Example 4:
INPUT:
M = 112
N = 130
OUTPUT:
INVALID INPUT
ALGORITHM:

main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:".
STEP 4: Print "M = ".
STEP 5: Read integer `M` from user input.
STEP 6: Print "N = ".
STEP 7: Read integer `N` from user input.
STEP 8: If `M` is less than 100 or greater than 10000, or `N` is greater than or equal to 100:
STEP 9: Print "OUTPUT:\nINVALID INPUT".
STEP 10: Close `Scanner` object `sc`.
STEP 11: Return from function.
STEP 12: Call **findSmallestNumber(M, N)** and store the result in `smallestNumber`.
STEP 13: Call **countDigits(smallestNumber)** and store the result in `totalDigits`.
STEP 14: Print "OUTPUT:".
STEP 15: Print "The required number = " followed by `smallestNumber`.
STEP 16: Print "Total number of digits = " followed by `totalDigits`.
STEP 17: Close `Scanner` object `sc`.
STEP 18: End of algorithm.

findSmallestNumber(int M, int N):


STEP 1: Start of algorithm.
STEP 2: For integer `i` starting from `M + 1`:
STEP 3: If the sum of digits of `i` is equal to `N`:
STEP 4: Return `i`.
STEP 5: End of algorithm.

sumOfDigits(int number):
STEP 1: Start of algorithm.
STEP 2: Initialize `sum` to 0.
STEP 3: While `number` is greater than 0:
STEP 4: Add `number % 10` to `sum`.
STEP 5: Update `number` to `number / 10`.
STEP 6: Return `sum`.
STEP 7: End of algorithm.

countDigits(int number):
STEP 1: Start of algorithm.
STEP 2: Initialize `count` to 0.
STEP 3: While `number` is greater than 0:
STEP 4: Increment `count` by 1.
STEP 5: Update `number` to `number / 10`.
STEP 6: Return `count`.
STEP 7: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class SmallestInteger {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("INPUT:");
System.out.print("M = ");
int M = sc.nextInt();
System.out.print("N = ");
int N = sc.nextInt();

if (M < 100 || M > 10000 || N >= 100) {


System.out.println("OUTPUT:\nINVALID INPUT");
} else {
int smallestNumber = findSmallestNumber(M, N);
int totalDigits = countDigits(smallestNumber);

System.out.println("OUTPUT:");
System.out.println("The required number = " + smallestNumber);
System.out.println("Total number of digits = " + totalDigits);
}

sc.close();
}

private static int findSmallestNumber(int M, int N) {


for (int i = M + 1; ; i++) {
if (sumOfDigits(i) == N) {
return i;
}
}
}

private static int sumOfDigits(int number) {


int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}

private static int countDigits(int number) {


int count = 0;
while (number > 0) {
count++;
number /= 10;
}
return count;
}
}

VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
sc Scanner Scanner object used to read user input. Local variable in
main method

M int The lower bound for finding the smallest integer. Local variable in
main method

N int The target sum of digits for the smallest integer. Local variable in
main method

smallestNum int The smallest integer greater than M whose sum of digits Local variable in
ber equals N. main method,
return value of
findSmallestNum
ber method

totalDigits int The total number of digits in smallestNumber. Local variable in


main method

i int Loop variable used to find the smallest number whose Local variable in
sum of digits equals N. findSmallestNum
ber method

number int The current number being processed to find the sum of Local variable in
digits. sumOfDigits and
countDigits
methods
sum int The sum of the digits of number. Local variable in
sumOfDigits
method
count int The count of digits in number. Local variable in
countDigits
method

OUTPUT:
Question 13:

A composite magic number is a positive integer which is composite as well as a magic number.
Composite number: A composite number is a number that has more than two factors.
For example: 10
Factors are: 1, 2, 5, 10.
Magic number: A magic number is a number in which the eventual sum of the digits is equal to
1.
For example: 28
2 + 8 = 10.
1 + 0 = 1.
Accept two positive integers ‘m’ and ‘n’, where m is less than n as user input. Display the
number of composite magic integers that are in the range between ‘m’ and ‘n’ (both inclusive)
and output them along with the frequency, in the format specified below.
Test your program with the sample data and some random data:
Example 1:
INPUT:
m = 10
n = 100
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2:
INPUT:
m = 1200
n = 1300
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
1207, 1216, 1225, 1234, 1243, 1252, 1261, 1270, 1288
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9
Example 3:
INPUT:
m = 120
n = 99
OUTPUT:
INVALID INPUT
ALGORITHM:

main():
STEP 1: Start of algorithm.
STEP 2: Create a Scanner object sc.
STEP 3: Print "INPUT:".
STEP 4: Print "m = ".
STEP 5: Read integer m from user input.
STEP 6: Print "n = ".
STEP 7: Read integer n from user input.
STEP 8: If m is greater than or equal to n:
STEP 9: Print "OUTPUT:\nINVALID INPUT".
STEP 10: Close Scanner object sc.
STEP 11: Return from function.
STEP 12: Print "OUTPUT:".
STEP 13: Print "THE COMPOSITE MAGIC INTEGERS ARE:".
STEP 14: Call printCompositeMagicNumbers(m, n) and store the result in count.
STEP 15: Print "FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: " followed by count.
STEP 16: End of algorithm.

isComposite(int number):
STEP 1: Start of algorithm.
STEP 2: If number is less than or equal to 1:
STEP 3: Return false.
STEP 4: For integer i from 2 to the square root of number:
STEP 5: If number is divisible by i:
STEP 6: Return true.
STEP 7: Return false.
STEP 8: End of algorithm.

isMagicNumber(int number):
STEP 1: Start of algorithm.
STEP 2: While number is greater than 9:
STEP 3: Initialize sum to 0.
STEP 4: While number is greater than 0:
STEP 5: Add number % 10 to sum.
STEP 6: Update number to number / 10.
STEP 7: Update number to sum.
STEP 8: Return number equals 1.
STEP 9: End of algorithm.

printCompositeMagicNumbers(int m, int n):


STEP 1: Start of algorithm.
STEP 2: Initialize count to 0.
STEP 3: For integer i from m to n:
STEP 4: If i is composite and a magic number:
STEP 5: Print i with appropriate formatting.
STEP 6: Increment count by 1.
STEP 7: Print a new line.
STEP 8: Return count.
STEP 9: End of algorithm.

SOURCE CODE:

import java.util.Scanner;

public class CompositeMagicNumbers {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("INPUT:");
System.out.print("m = ");
int m = sc.nextInt();
System.out.print("n = ");
int n = sc.nextInt();

if (m >= n) {
System.out.println("OUTPUT:\nINVALID INPUT");
} else {
System.out.println("OUTPUT:");
System.out.println("THE COMPOSITE MAGIC INTEGERS ARE:");
int count = printCompositeMagicNumbers(m, n);
System.out.println("FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: " +
count);
}

sc.close();
}

private static boolean isComposite(int number) {


if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return true;
}
}
return false;
}
private static boolean isMagicNumber(int number) {
while (number > 9) {
int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
number = sum;
}
return number == 1;
}

private static int printCompositeMagicNumbers(int m, int n) {


int count = 0;
for (int i = m; i <= n; i++) {
if (isComposite(i) && isMagicNumber(i)) {
System.out.print(i==n?i: i+ ", ");
count++;
}
}
System.out.println();
return count;
}
}
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
sc Scanner Scanner object used to read user input. Local variable in main
method

m int The lower bound of the range to check for Local variable in main
composite magic numbers. method

n int The upper bound of the range to check for Local variable in main
composite magic numbers. method

count int The count of composite magic numbers found in Local variable in
the range. printCompositeMagicNum
bers method
i int Loop variable used to iterate through numbers in Local variable in
the range [m, n]. printCompositeMagicNum
bers method

number int The current number being checked in Local variable in


isComposite and isMagicNumber methods. isComposite and
isMagicNumber methods

sum int The sum of digits of number in the Local variable in


isMagicNumber method. isMagicNumber method

OUTPUT:
Question 14:

A prime palindrome integer is a positive integer (without leading zeroes) which is prime as well
as a palindrome. Given two positive integers m and n, where m < n, write a program to
determine how many prime palindrome integers are there in the range between m and n (both
inclusive) and output them.
The input contains two positive integers m and n where m < 3000 and n < 3000. Display the
number of prime palindrome integers in the specified range along with their values in the format
specified below:
Test your program with the sample data and some random data:
Example 1:
INPUT:
m = 100
n = 1000
OUTPUT:
THE PRIME PALINDROME INTEGERS ARE:
101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 919, 929
FREQUENCY OF PRIME PALINDROME INTEGERS: 15
Example 2:
INPUT:
m = 100
n = 5000
OUTPUT:
OUT OF RANGE.
ALGORITHM:

main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize Scanner sc.
Step 3: Print "INPUT:".
Step 4: Prompt the user to input m, store it in m.
Step 5: Prompt the user to input n, store it in n.
Step 6: If m >= 3000 or n >= 3000, do the following:
Step 7: Print "OUTPUT:\nOUT OF RANGE.".
Step 8: Else, do the following:
Step 9: Print "OUTPUT:".
Step 10: Print "THE PRIME PALINDROME INTEGERS ARE:".
Step 11: Initialize freq = 0 and first = true.
Step 12: For i = m to n, do the following:
Step 13: If isPrime(i) and isPalin(i), do the following:
Step 14: If first is false, print ", ".
Step 15: Print i.
Step 16: Increment freq by 1.
Step 17: Set first to false.
Step 18: If freq == 0, print "NIL".
Step 19: Else, print a newline.
Step 20: Print "FREQUENCY OF PRIME PALINDROME INTEGERS: " + freq.
Step 21: Close Scanner sc.
Step 22: End of algorithm.

isPrime(int num):
Step 1: Start of algorithm.
Step 2: If num <= 1, return false.
Step 3: For i = 2 to √num, do the following:
Step 4: If num % i == 0, return false.
Step 5: Return true.
Step 6: End of algorithm.

isPalin(int num):
Step 1: Start of algorithm.
Step 2: Initialize rev = 0 and orig = num.
Step 3: While orig != 0, do the following:
Step 4: Set dig = orig % 10.
Step 5: Update rev = rev * 10 + dig.
Step 6: Update orig /= 10.
Step 7: Return num == rev.
Step 8: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class PrimePalin {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("INPUT:");
System.out.print("m = ");
int m = sc.nextInt();
System.out.print("n = ");
int n = sc.nextInt();

if (m >= 3000 || n >= 3000) {


System.out.println("OUTPUT:\nOUT OF RANGE.");
} else {
System.out.println("OUTPUT:");
System.out.println("THE PRIME PALINDROME INTEGERS ARE:");

int freq = 0;
boolean first = true;

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


if (isPrime(i) && isPalin(i)) {
if (!first) {
System.out.print(", ");
}
System.out.print(i);
freq++;
first = false;
}
}

if (freq == 0) {
System.out.println("NIL");
} else {
System.out.println();
}

System.out.println("FREQUENCY OF PRIME PALINDROME INTEGERS: " + freq);


}

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

private static boolean isPalin(int num) {


int rev = 0;
int orig = num;

while (orig != 0) {
int dig = orig % 10;
rev = rev * 10 + dig;
orig /= 10;
}

return num == rev;


}
}
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
sc Scanner Scanner object used to read user input. Local variable
in main
method
m int Lower bound of the range to search for prime palindromes. Local variable
in main
method
n int Upper bound of the range to search for prime palindromes. Local variable
in main
method
freq int The frequency of prime palindrome integers found in the range. Local variable
in main
method
first boolean Flag to manage comma placement in output of prime Local variable
palindromes. in main
method
i int Loop variable used to iterate through the range [m, n]. Local variable
in main
method
num int Number to be checked for primality and palindrome properties. Local variable
in isPrime
and isPalin
methods
rev int Reversed number used to check if num is a palindrome. Local variable
in isPalin
method
orig int Original number used to reverse num in the isPalin method. Local variable
in isPalin
method
dig int Digit extracted from orig during reversal process. Local variable
in isPalin
method

OUTPUT:
Question 15:

Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows and
‘N’ is the number of columns such that both M and N must be greater than 2 and less than 20.
Allow the user to input integers into this matrix. Perform the following tasks on the matrix:
Display the input matrix.
Find the maximum and minimum value in the matrix and display them along with their position.
Sort the elements of the matrix in ascending order using any standard sorting technique and
rearrange them in the matrix.
Output the rearranged matrix.
Test your program with the sample data and some random data.
Example 1:
INPUT:
M=3
N=4
8 7 9 3
-2 0 4 5
1 3 6 -1
OUTPUT:
ORIGINAL MATRIX:
8 7 9 3
-2 0 4 5
1 3 6 -1
LARGEST NUMBER: 9
ROW = 0
COLUMN = 3
REARRANGED MATRIX:
-4 -2 0 1
3 3 4 5
6 7 8 9
Example 2:
INPUT:
M=3
N = 22
OUTPUT:
SIZE OUT OF RANGE
ALGORITHM:

main()
STEP 1: Start of algorithm.
STEP 2: Create a Scanner object sc.
STEP 3: Print "INPUT:\nM = ".
STEP 4: Read integer input M from user.
STEP 5: Print "N = ".
STEP 6: Read integer input N from user.
STEP 7: If M is less than or equal to 2, or M is greater than or equal to 20, or N is less than or
equal to 2, or N is greater than or equal to 20:
STEP 8: Print "OUTPUT:\nSIZE OUT OF RANGE".
STEP 9: Close Scanner object sc.
STEP 10: Return from function.
STEP 11: Create a 2D matrix matrix of size M by N.
STEP 12: Print "Enter the elements of the matrix:".
STEP 13: For each element in matrix, read the integer input from user.
STEP 14: Print "OUTPUT:".
STEP 15: Print "ORIGINAL MATRIX:".
STEP 16: Call printMatrix(matrix).
STEP 17: Create a 1D array flattenedMatrix to store matrix elements.
STEP 18: Flatten matrix into flattenedMatrix.
STEP 19: Find maximum value in flattenedMatrix and store in max.
STEP 20: Find minimum value in flattenedMatrix and store in min.
STEP 21: Find position of max in flattenedMatrix and store in maxPos.
STEP 22: Find position of min in flattenedMatrix and store in minPos.
STEP 23: Print "LARGEST NUMBER: " followed by max.
STEP 24: Print "ROW = " followed by row index of max in matrix.
STEP 25: Print "COLUMN = " followed by column index of max in matrix.
STEP 26: Print "SMALLEST NUMBER: " followed by min.
STEP 27: Print "ROW = " followed by row index of min in matrix.
STEP 28: Print "COLUMN = " followed by column index of min in matrix.
STEP 29: Sort flattenedMatrix.
STEP 30: Create a 2D matrix sortedMatrix to store sorted elements.
STEP 31: Rearrange sorted elements from flattenedMatrix into sortedMatrix.
STEP 32: Print "REARRANGED MATRIX:".
STEP 33: Call printMatrix(sortedMatrix).
STEP 34: Close Scanner object sc.
STEP 35: End of algorithm.

printMatrix(int[][] matrix)
STEP 1: Start of algorithm.
STEP 2: For each row in matrix:
STEP 3: For each value in the row:
STEP 4: Print the value followed by a space.
STEP 5: Print a new line.
STEP 6: End of algorithm.

findPosition(int[] array, int value)


STEP 1: Start of algorithm.
STEP 2: For each index i in array:
STEP 3: If array[i] equals value, return i.
STEP 4: Return -1 if not found.
STEP 5: End of algorithm.

SOURCE CODE:

import java.util.Arrays;
import java.util.Scanner;

public class MatrixOperations {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("INPUT:\nM = ");
int M = sc.nextInt();
System.out.print("N = ");
int N = sc.nextInt();

if (M <= 2 || M >= 20 || N <= 2 || N >= 20) {


System.out.println("OUTPUT:\nSIZE OUT OF RANGE");
} else {
int[][] matrix = new int[M][N];

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


for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = sc.nextInt();
}
}

System.out.println("OUTPUT:");
System.out.println("ORIGINAL MATRIX:");
printMatrix(matrix);

int[] flattenedMatrix = new int[M * N];


int index = 0;

// Flatten the matrix


for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
flattenedMatrix[index++] = matrix[i][j];
}
}

// Find min and max values


int max = Arrays.stream(flattenedMatrix).max().getAsInt();
int min = Arrays.stream(flattenedMatrix).min().getAsInt();

// Find positions of min and max


int maxPos = findPosition(flattenedMatrix, max);
int minPos = findPosition(flattenedMatrix, min);

System.out.println("LARGEST NUMBER: " + max);


System.out.println("ROW = " + (maxPos / N));
System.out.println("COLUMN = " + (maxPos % N));

System.out.println("SMALLEST NUMBER: " + min);


System.out.println("ROW = " + (minPos / N));
System.out.println("COLUMN = " + (minPos % N));

// Sort the flattened matrix


Arrays.sort(flattenedMatrix);

// Rearranged matrix
int[][] sortedMatrix = new int[M][N];
index = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
sortedMatrix[i][j] = flattenedMatrix[index++];
}
}

System.out.println("REARRANGED MATRIX:");
printMatrix(sortedMatrix);
}

sc.close();
}

private static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}

private static int findPosition(int[] array, int value) {


for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
}

VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
sc Scanner Scanner object for reading user input. Local variable
in main
method
M int Number of rows in the matrix. Local variable
in main
method
N int Number of columns in the matrix. Local variable
in main
method
matrix int[][] 2D array to store the input matrix. Local variable
in main
method
flattenedMat int[] 1D array to store the matrix elements in a flattened form. Local variable
rix in main
method
index int Index variable used for filling and accessing arrays. Local variable
in main
method
max int Maximum value found in the matrix. Local variable
in main
method
min int Minimum value found in the matrix. Local variable
in main
method
maxPos int Position of max in the flattened array. Local variable
in main
method
minPos int Position of min in the flattened array. Local variable
in main
method
sortedMatrix int[][] 2D array to store the sorted matrix. Local variable
in main
method
rev int Reversed number for palindrome check. Local variable
in isPalin
method
orig int Original number during reversal process. Local variable
in isPalin
method
dig int Digit extracted during the reversal process. Local variable
in isPalin
method

OUTPUT:
Question 16:

Write a program to input a natural number less than 1000 and display it in words.
Test your program for the given sample data and some random data.
INPUT: 29
OUTPUT: TWENTY NINE
INPUT: 17001
OUTPUT: OUT OF RANGE
INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN
INPUT: 500
OUTPUT: FIVE HUNDRED

ALGORITHM:

main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize `Scanner sc`.
Step 3: Print "INPUT: ".
Step 4: Prompt the user to input `n`, store it in `n`.
Step 5: If `isValid(n)` returns `true`, do the following:
Step 6: Print "OUTPUT: ".
Step 7: Print the result of `convertToWords(n)`.
Step 8: Else, print "OUTPUT: OUT OF RANGE".
Step 9: Close `Scanner sc`.
Step 10: End of algorithm.

isValid(int n):
Step 1: Start of algorithm.
Step 2: Return `true` if `n > 0` and `n < 1000`.
Step 3: Else, return `false`.
Step 4: End of algorithm.

convertToWords(int n):
Step 1: Start of algorithm.
Step 2: Initialize arrays `u` and `t` for unit and ten values respectively.
Step 3: If `n == 0`, return "ZERO".
Step 4: If `n < 20`, return the corresponding value from `u[n]`.
Step 5: If `n < 100`, return the combination of `t[n / 10]` and `u[n % 10]`.
Step 6: Return the combination of `u[n / 100]`, "HUNDRED", and the result of
`convertToWords(n % 100)` if `n % 100 != 0`.
Step 7: End of algorithm.
SOURCE CODE:

import java.util.Scanner;

public class InitWords {


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

System.out.print("INPUT: ");
int n = sc.nextInt();

if (isValid(n)) {
System.out.print("OUTPUT: ");
System.out.println(convertToWords(n));
} else {
System.out.println("OUTPUT: OUT OF RANGE");
}

sc.close();
}

private static boolean isValid(int n) {


return n > 0 && n < 1000;
}

private static String convertToWords(int n) {


String[] u = {"", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
"EIGHT", "NINE", "TEN",
"ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN",
"SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};

String[] t = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY",


"EIGHTY", "NINETY"};

if (n == 0) {
return "ZERO";
}
if (n < 20) {
return u[n];
}
if (n < 100) {
return t[n / 10] + " " + u[n % 10];
}
return u[n / 100] + " HUNDRED" + (n % 100 != 0 ? " AND " + convertToWords(n % 100) :
"");
}
}
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
sc Scanner Scanner object for reading user Local variable in main
input. method
n int Integer input provided by the user to Local variable in main
be converted to words. method
u String[] Array containing words for numbers Local variable in
from 1 to 19. convertToWords method
t String[] Array containing words for Local variable in
multiples of ten from 20 to 90. convertToWords method

OUTPUT:
Question 17:

Consider the sequence of natural numbers.


1, 2, 3, 4, 5, 6, 7 ………………………………….
Removing every second number produces the sequences
1, 3, 5, 7, 9, 11, 13, 15, 17 ………………………….
This process continues indefinitely by removing the fourth, 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 numbers less than a given number N < 50.
SAMPLE INPUT : N = 10
OUTPUT :
THE LUCKY NUMBERS LESS THAN 10 ARE:
1
3
7.
SAMPLE INPUT : N = 25
OUTPUT :
THE LUCKY NUMBERS LESS THAN 10 ARE:
1
3
7
13
19

ALGORITHM:

main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize `Scanner sc`.
Step 3: Print "INPUT N: ".
Step 4: Prompt the user to input `n`, store it in `n`.
Step 5: If `n >= 50`, print "N MUST BE LESS THAN 50." and close `Scanner sc`.
Step 6: Return from the function.
Step 7: Initialize an array `arr` of size `n`.
Step 8: Fill `arr` with values from 1 to `n`.
Step 9: Initialize `step` to 2.
Step 10: Enter a `while` loop that continues indefinitely.
Step 11: Initialize `len` to 0.
Step 12: Iterate over `arr` and copy elements that are not removed to a new position in `arr`,
updating `len`.
Step 13: If `len` equals `n`, break the loop.
Step 14: Update `n` to `len`.
Step 15: Increment `step` by 1.
Step 16: Print the lucky numbers less than 10 if `arr[0] < 10`, otherwise print less than 25.
Step 17: Print the elements of `arr` from index 0 to `n-1`.
Step 18: Close `Scanner sc`.
Step 19: End of algorithm.

SOURCE CODE:

import java.util.Scanner;

public class LuckyNums {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("INPUT N: ");
int n = sc.nextInt();

if (n >= 50) { // Ensure N is less than 50


System.out.println("N MUST BE LESS THAN 50.");
sc.close();
return;
}

// Array to store numbers from 1 to N


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

int step = 2; // Start by removing every second number

while (true) {
int len = 0; // Length of the new array after removing numbers

// Determine the new array length after removal


for (int i = 0; i < n; i++) {
if ((i + 1) % step != 0) {
arr[len++] = arr[i];
}
}

if (len == n) { // If length doesn't change, stop the process


break;
}

n = len; // Update the size of the array


step++; // Increment step to remove every next step-th number
}

// Output the lucky numbers


System.out.println("THE LUCKY NUMBERS LESS THAN " + (arr[0] < 10 ? 10 : 25) + "
ARE:");
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
}

sc.close();
}
}
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
sc Scanner Scanner object for reading user input. Local variable
in main
method
n int Integer input provided by the user, representing the size of the Local variable
array. in main
method
arr int[] Array to store numbers from 1 to n. Local variable
in main
method
step int Variable used to determine the step size for removing numbers. Local variable
in main
method
len int Length of the new array after removing numbers based on the Local variable
current step. in main
method

OUTPUT:
Question 18:

Read in an integer n (which can be at most 50). Then read in n integers one by one and store
them in an array data from index 0 to n-1. Now we want to rearrange the integers in data in the
following way :
Find the maximum value in data and put in the centre of the array (that is at (n/2);
find the next largest value and put it to its right; then the next largest and place it to its left and so
on alternating right and left until all integers in data are done. For example, if the array is
initially:
7, 3, 1, 6, 4, 2, 5 then after rearranging it becomes 1, 3, 5, 7, 6, 4, 2. However, since we have very
little memory, you are not allowed to use any other array from data.
Sample data:
Input:
Give the number of integers: 5
Give integer 1 : 7
Give integer 2 : 9
Give integer 3 : 2
Give integer 4 : 5
Give integer 5 : 6
Output:
Original array
79256
rearranged array
26975
Input:
Give the number of integers: 6
Give integer 1 : 5
Give integer 2 : 1
Give integer 3 : 9
Give integer 4 : 8
Give integer 5 : 2
Give integer 6 : 4

Output:
Original array
519824
rearranged array
259841
ALGORITHM:

main()
STEP 1: Start of algorithm.
STEP 2: Create a Scanner object sc to read user input.
STEP 3: Print "Give the number of integers: " and read integer input n from the user.
STEP 4: If n is greater than 50:
STEP 4.1: Print "Input exceeds limit of 50."
STEP 4.2: Close the Scanner object sc.
STEP 4.3: Return from function.
STEP 5: Initialize an integer array data of size n.
STEP 6: For each index i from 0 to n-1:
STEP 6.1: Print "Give integer " + (i + 1) + ": " and read integer input into data[i].
STEP 7: Print "Original array" and display the elements of the array data from index 0 to n-1.
STEP 8: Sort the array data in descending order.
STEP 9: Initialize an integer array result of size n.
STEP 10: Initialize left to 0 and right to n-1.
STEP 11: For each index i from 0 to n-1:
STEP 11.1: If i is even, place the i-th largest element of data at index left of result and increment
left by 1.
STEP 11.2: If i is odd, place the i-th largest element of data at index right of result and decrement
right by 1.
STEP 12: Print "Rearranged array" and display the elements of the array result from index 0 to n-
1.
STEP 13: Close the Scanner object sc.
STEP 14: End of algorithm.

SOURCE CODE:

import java.util.Arrays;
import java.util.Scanner;

public class RearrangeArray {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Read the number of integers


System.out.print("Give the number of integers: ");
int n = sc.nextInt();

// Check if n is valid
if (n <= 0 || n > 50) {
System.out.println("Invalid number of integers. Must be between 1 and 50.");
sc.close();
return;
}

// Read the integers and store them in the array


int[] data = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Give integer " + (i + 1) + " : ");
data[i] = sc.nextInt();
}

// Display the original array


System.out.println("Original array");
for (int num : data) {
System.out.print(num + " ");
}
System.out.println();

// Sort the array in ascending order


Arrays.sort(data);

// Rearrange the array as specified


int[] rearranged = new int[n];
int left = (n - 1) / 2;
int right = (n + 1) / 2;
int index = 0;

// Place the maximum element in the center


rearranged[left] = data[n - 1];
index = n - 2;

// Alternate placing elements to the right and left of the center


while (index >= 0) {
if (right < n) {
rearranged[right++] = data[index--];
}
if (left >= 0) {
rearranged[left--] = data[index--];
}
}

// Display the rearranged array


System.out.println("Rearranged array");
for (int num : rearranged) {
System.out.print(num + " ");
}
System.out.println();
sc.close();
}
}

VARIABLE DESCRIPTION TABLE:


Variable Name Data Description Scope
Type
sc Scanner Scanner object for reading user input. Local variable
in main
method
n int Number of integers to be read and processed. Local variable
in main
method
data int[] Array to store the input integers. Local variable
in main
method
rearranged int[] Array to store the rearranged integers. Local variable
in main
method
left int Index for placing elements to the left of the center in Local variable
rearranged. in main
method
right int Index for placing elements to the right of the center in Local variable
rearranged. in main
method
index int Index for iterating over sorted elements of data. Local variable
in main
method

OUTPUT:
Question 19:

Write a program to declare a square matrix A [ ] [ ]of order N (N < 20). Allow the user to input
positive integers in to this matrix. Perform the following task on the matrix:
(i) Output the original matrix.
(ii) Fins the SADDLE POINT for the matrix such that is the minimum element for the row to
which it belongs 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 ”.
Test your program for the following data and some random data :
SAMPLE DATA :
INPUT : N = 4
MATRIX A [ ] [ ] =
2569
8 4 12 3
6731
12 24 2 11
OUTPUT :
2569
8 4 12 3
6731
12 24 2 11
NO SADDLE POINT
MATRIX AFTER SORTING THE PRINCIPAL DIAGONAL
2569
8 4 12 3
6731
12 24 2 11
INPUT : N = 3
MATRIX A [ ] [ ] =
4 16 12
2 6 14
138
OUTPUT :
4 16 12
2 6 14
138
SADDLE POINT = 4
MATRIX AFTER SORTING THE PRINCIPAL DIAGONAL
4 16 12
2 6 14
138

ALGORITHM:

main(String[] args):
Step 1: Initialize `Scanner sc`.
Step 2: Print "Enter the order of the matrix N (N < 20):".
Step 3: Prompt the user to input `n`, store it in `n`.
Step 4: Create a 2D array `mat` of size `n x n`.
Step 5: Print "Enter the elements of the matrix:".
Step 6: Iterate over `i` from 0 to `n-1`.
Step 7: Iterate over `j` from 0 to `n-1`.
Step 8: Input matrix element at `mat[i][j]`.
Step 9: Print "Original Matrix:".
Step 10: Iterate over `i` from 0 to `n-1`.
Step 11: Iterate over `j` from 0 to `n-1`.
Step 12: Print matrix element `mat[i][j]` followed by a space.
Step 13: Print a newline after each row.
Step 14: Initialize `hasSaddlePoint` to `false` and `saddlePoint` to 0.
Step 15: Iterate over `i` from 0 to `n-1`.
Step 16: Initialize `minRow` to `mat[i][0]` and `minColIndex` to 0.
Step 17: Iterate over `j` from 1 to `n-1`.
Step 18: Update `minRow` and `minColIndex` if `mat[i][j]` is less than `minRow`.
Step 19: Initialize `isSaddle` to `true`.
Step 20: Iterate over `k` from 0 to `n-1`.
Step 21: Set `isSaddle` to `false` if `mat[k][minColIndex]` is greater than `minRow`.
Step 22: Break the loop if `isSaddle` is `false`.
Step 23: If `isSaddle` is `true`, set `saddlePoint` to `minRow`, set `hasSaddlePoint` to `true`, and
break the loop.
Step 24: Print the saddle point if `hasSaddlePoint` is `true`, otherwise print "NO SADDLE
POINT".
Step 25: Iterate over `i` from 0 to `n-2`.
Step 26: Iterate over `j` from `i+1` to `n-1`.
Step 27: Swap `mat[i][i]` with `mat[j][j]` if `mat[i][i]` is greater than `mat[j][j]`.
Step 28: Print "Matrix after sorting the principal diagonal:".
Step 29: Iterate over `i` from 0 to `n-1`.
Step 30: Iterate over `j` from 0 to `n-1`.
Step 31: Print matrix element `mat[i][j]` followed by a space.
Step 32: Print a newline after each row.
Step 33: Close `Scanner sc`.
Step 34: End of algorithm.

SOURCE CODE:

import java.util.Scanner;

public class SaddlePointMatrix {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Step 1: Input the order of the matrix


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

int[][] mat = new int[n][n];

// Step 2: Input the 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++) {
mat[i][j] = sc.nextInt();
}
}

// Step 3: Output the original matrix


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

// Step 4: Find the saddle point


boolean hasSaddlePoint = false;
int saddlePoint = 0;

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


int minRow = mat[i][0];
int minColIndex = 0;

// Find the minimum element in the current row


for (int j = 1; j < n; j++) {
if (mat[i][j] < minRow) {
minRow = mat[i][j];
minColIndex = j;
}
}

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


boolean isSaddle = true;
for (int k = 0; k < n; k++) {
if (mat[k][minColIndex] > minRow) {
isSaddle = false;
break;
}
}

// If a saddle point is found


if (isSaddle) {
saddlePoint = minRow;
hasSaddlePoint = true;
break;
}
}

// Step 5: Output the saddle point or indicate that there is no saddle point
if (hasSaddlePoint) {
System.out.println("SADDLE POINT = " + saddlePoint);
} else {
System.out.println("NO SADDLE POINT");
}

// Step 6: Sort the principal diagonal of the matrix


for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (mat[i][i] > mat[j][j]) {
int temp = mat[i][i];
mat[i][i] = mat[j][j];
mat[j][j] = temp;
}
}
}

// Step 7: Output the matrix after sorting the principal diagonal


System.out.println("Matrix after sorting the principal diagonal:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}

sc.close();
}
}

VARIABLE DESCRIPTION TABLE:

Variable Type Description Scope


sc Scanner Scanner object used to read user input. Local to
main()
n int Order of the matrix (i.e., number of rows and columns) entered Local to
by the user. main()
mat int[][] 2D array representing the matrix of size n × n where the Local to
matrix elements are stored. main()
hasSaddlePo boolean Flag indicating whether a saddle point was found in the matrix. Local to
int main()
saddlePoint int Value of the saddle point if found. Local to
main()
minRow int Minimum value in the current row during saddle point Local to
calculation. main()
minColIndex int Column index of the minimum value in the current row. Local to
main()
temp int Temporary variable used for swapping elements during the Local to
sorting of the principal diagonal. main()
i int Loop index for iterating through rows or diagonals. Local to
main()
j int Loop index for iterating through columns or diagonals. Local to
main()
k int Loop index used for checking elements in columns during Local to
saddle point calculation. main()
OUTPUT:
Question 20:

A simple encryption system uses a shifting process to hide a message. The value of the shift can
be in the range 1 to 26. For example a shift of 7 means that A = U, B =V,C = W, etc.i e.
Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T
Fist an extra space is added to the end of the string. To make things little more difficult, spaces
within the original text are replaced with QQ before the text is encrypted. Double Q (QQ) was
selected because no English word ends in Q or contains QQ.
Additionally the coded message is printed in blocks of six characters separated by spaces. The
last block might not contain six characters. Write a program that takes the coded text (less than
100 characters), the shift value and prints the decoded original text. Your program must reject
any non-valid value for shift and display an error message “INVALID SHIFT VALUE)”.Assume
all characters are upper case. Test your program for the following data and some data that you
have coded, using the rules given above:
SAMLE DATA:
INPUT:
CODED TEXT : “UHINBY LKKQCH HYLKK”
SHIFT : 7
OUTPUT:
DECODED TEXT : ANOTHER VALUE
INPUT:
CODED TEXT : “RUIJGG EVGGBK SAGG”
SHIFT : 11
OUTPUT:
DECODED TEST : BEST OF LUCK
INPUT:
CODED TEXT : “DKSMMW NAMMUK QMM”
SHIFT : 29
OUTPUT:
INVALID SHIFT VALUE
ALGORITHM:

main()
1. Start the algorithm.
2. Create a Scanner object scanner to read user inputs.
3. Print "INPUT:" and read the codedText from the user.
4. Print "SHIFT:" and read the shift value from the user.
5. Check if shift is outside the valid range (1 to 26):
o If yes, print "INVALID SHIFT VALUE" and end the program.
6. Decode the codedText using the decodeMessage method with the given shift.
7. Print the decoded message.
8. Close the scanner object.
9. End the algorithm.
decodeMessage(codedText, shift)
1. Remove spaces from the codedText.
2. Calculate the reverse shift value: 26 - (shift % 26).
3. Initialize an empty StringBuilder for the decoded message.
4. Iterate over each character in the codedText:
o If the character is 'Q' followed by another 'Q':
 Append a space to the decodedMessage.
 Skip the next character.
o Else, decode the character using the reverse shift and append it to the
decodedMessage.
5. Return the decoded message.
SOURCE CODE:

import java.util.Scanner;

public class DecryptMessage {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the encoded text and the shift value


System.out.print("INPUT:\nCODED TEXT: ");
String codedText = scanner.nextLine();
System.out.print("SHIFT: ");
int shift = scanner.nextInt();

// Validate the shift value


if (shift < 1 || shift > 26) {
System.out.println("OUTPUT:\nINVALID SHIFT VALUE");
scanner.close();
return;
}

// Decode the message


String decodedText = decodeMessage(codedText, shift);

// Print the decoded message


System.out.println("OUTPUT:\nDECODED TEXT: " + decodedText);

scanner.close();
}

private static String decodeMessage(String codedText, int shift) {


// Remove spaces from the coded text
codedText = codedText.replace(" ", "");

// Reverse the shift to get the original message


int reverseShift = 26 - (shift % 26);

StringBuilder decodedMessage = new StringBuilder();


for (int i = 0; i < codedText.length(); i++) {
char ch = codedText.charAt(i);
if (ch == 'Q' && (i + 1 < codedText.length() && codedText.charAt(i + 1) == 'Q')) {
decodedMessage.append(' ');
i++; // Skip the next Q as well
} else {
decodedMessage.append((char) (((ch - 'A' + reverseShift) % 26 + 26) % 26 + 'A'));
}
}

return decodedMessage.toString();
}
}

VARIABLE DESCRIPTION TABLE:

Variable Type Description Scope


scanner Scanner Object used to read user input. Local to main()
codedText String Encoded message string provided by the user. Local to main()
shift int Shift value used for decoding the message. Local to main()
reverseShift int Calculated shift value for decoding (reverse of the Local to
original shift). decodeMessag
e()
decodedMessa StringBuild String builder to construct the decoded message. Local to
ge er decodeMessag
e()
ch char Character from the codedText being processed. Local to
decodeMessag
e()
i int Index for iterating through the codedText and Local to
handling 'Q' replacements. decodeMessag
e()

OUTPUT:
Question 21:

The manager of a company wants to analyse the machine uses from the records to find the
utilization of the machine. He wants to know how long each user used the machine. When the
user wants to use the machine he must login to the machine and after finishing the work he must
log off the machine.
Each log record consists of:
User identification number.
Login time and date.
Logout time and date.
Time consists of:
Hours
Minutes
Date consists of:
Day
Month
You may assume all logins and logouts are in the same year and there are 100 users at the most.
The time format is 24 hours and minutes.
Design a program:
(a) To find the duration for which each user has logged. Output all records along with the
duration in hours (format hours: minutes).
(b) Output the record of the user who logged for the longest duration.You may assume that no
user will login for more than 40 minutes.
Test your program for the following data and some random data.
SAMPLE DATA;
INPUT:
Number of users : 3
USER LOGIN LOGOUT
IDENTIFICATION TIME & DATE TIME & DATE
149 20:10 20-12 2:50 21-12
173 12:30 20-12 12:30 21-12
142 16:20 20-12 16:30 20-12
OUTPUT:
USER LOGIN LOGOUT DURATION
IDENTIFICATION TIME & DATE TIME & DATE HOURS : MINS
149 20:10 20-12 2:50 21-12 6 : 40
173 12:30 20-12 12:30 21-12 24 : 00
142 16:20 20-12 16:30 20-12 00 : 10
THE USER WHO LOGGED IN FOR THE LONGEST DURATION:
173 12:30 20-12 12:30 21-12 24 : 00

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 22:

A wondrous square is an n by n grid which fulfils the following conditions:


(i) It contains integers from 1 to n2, Where each integer appears only once.
(ii) The some of integers in any row or column must add up to 0.5×n×(n2+1).
For example the following grid is a wondrous square when 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 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 or not.
Also output all the prime numbers in the grid along with their row index and column index as
shown in the output. A natural number is said to be prime if it has exactly two divisors.
E.g.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.
SAMPLE DATA :
INPUT
N=4
16 15 1 2
6 4 10 14
9 8 12 5
3 7 11 13
OUTPUT :
YES IT REPRESENTS A WONDROUS SQUARE.
PRIME ROW INDEX COLUMN INDEX
203
330
523
731
11 3 2
13 3 3
15 0 1
INPUT
N=3
124
375
896
OUTPUT :
NOT A WONDROUS SQUARE.
PRIME ROW INDEX COLUMN INDEX
201
310
512
711
INPUT :
N=2
23
32
OUTPIUT:
NOT A WONDROUS SQUARE
PRIME ROW INDEX COLUMN INDEX
200
301
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 23:
Write a program to accept a date in the string format dd/mm/yyyy and accept
the name of the day on 1st of January of the corresponding year. Find the day
for the given date.
Example:
INPUT
Date : 5/7/2002
Day on 1st January : MONDAY
OUTPUT
Day on 5/7/2001 : THURSDAY
Test run the program on the following inputs.
INPUT DATE DAY ON 1ST JANUARY OUTPUT DAY FOR INPUT DATE
4/9/1989 THURSDAY FRIDAY
3/9/1999 FRIDAY TUESDAY
6/12/2000 SATURDAY WEDNESDAY
The program should include the part for validating the inputs namely the date
and the day on 1st January of that year.
ALGORITHM:
findDay(int day, int month, int year, String dayOn1stJanuary):
STEP 1: Initialize daysInMonth array for non-leap years
STEP 2: Compute totalDays from the start of the year to the given date
STEP 3: Add an extra day if it's a leap year and the month is after February
STEP 4: Find the index of dayOn1stJanuary in the DAYS_OF_WEEK array
STEP 5: Calculate targetDayIndex using (startDayIndex + totalDays) % 7
STEP 6: Return the day of the week from the DAYS_OF_WEEK array at targetDayIndex
isLeapYear(int year):
STEP 1: Check if the year is divisible by 4 and not divisible by 100, or divisible by 400
STEP 2: Return true if it is a leap year, otherwise false
findDayIndex(String day):
STEP 1: Iterate through DAYS_OF_WEEK array to find the index of the day
STEP 2: Return the index if found
STEP 3: Throw an IllegalArgumentException if the day is invalid
SOURCE CODE:
import java.util.Scanner;

public class DateFinder {

// Array of days of the week


private static final String[] DAYS_OF_WEEK = {"SUNDAY", "MONDAY", "TUESDAY",
"WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};

// Method to find the day of the week for a given date


public static String findDay(int day, int month, int year, String dayOn1stJanuary) {
// Days in each month (non-leap year)
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totalDays = 0;

// Add days for months before the given month


for (int i = 0; i < month - 1; i++) {
totalDays += daysInMonth[i];
}

// Add days for the current month


totalDays += day - 1;

// Check for leap year and adjust days in February


if (isLeapYear(year) && month > 2) {
totalDays += 1;
}
// Find the index of the given day on 1st January
int startDayIndex = findDayIndex(dayOn1stJanuary);

// Calculate the day of the week for the given date


int targetDayIndex = (startDayIndex + totalDays) % 7;
return DAYS_OF_WEEK[targetDayIndex];
}

// Check if a year is a leap year


private static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// Find the index of the given day in the DAYS_OF_WEEK array


private static int findDayIndex(String day) {
for (int i = 0; i < DAYS_OF_WEEK.length; i++) {
if (DAYS_OF_WEEK[i].equalsIgnoreCase(day)) {
return i;
}
}
throw new IllegalArgumentException("Invalid day of the week");
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input the date


System.out.print("Date (dd/mm/yyyy): ");
String dateInput = sc.nextLine();
String[] dateParts = dateInput.split("/");
int day = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);

// Input the day on 1st January


System.out.print("Day on 1st January: ");
String dayOn1stJanuary = sc.nextLine().toUpperCase();

// Validate the date


if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1) {
System.out.println("Invalid date.");
return;
}

if (month == 2 && day > (isLeapYear(year) ? 29 : 28)) {


System.out.println("Invalid date.");
return;
}

if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {


System.out.println("Invalid date.");
return;
}

// Find the day of the week for the given date


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

VARIABLE DESCRIPTION TABLE:


OUTPUT:
Question 24:
Given the two positive integers p and q, where p < q. Write a program to determine how many
kaprekar numbers are there in the range between 'p' and 'q'(both inclusive )and output them. This
is a program on kaprekar number. About 'kaprekar' number:
A positive whole number 'n' that has 'd' number of digits is squared and split into 2 pieces, a right
hand piece that has 'd' digits and a left hand piece that has remaining 'd' or 'd-1' digits. If sum of
the pieces is equal to the number then
it's a Kaprekar number.
SAMPLE DATA:
INPUT:
p=1
Q=1000
OUTPUT:
THE KAPREKAR NUMBERS ARE:
1,9,45,55,99,297,999
FREQUENCY OF KAPREKAR NUMBERS IS:8
ALGORITHM:
isKaprekar(int n):
STEP 1: Calculate the square of n and convert it to a string
STEP 2: Determine the length of the square and the number of digits in n
STEP 3: Split the square string into rightPart and leftPart based on the number of digits in n
STEP 4: Convert rightPart and leftPart to integers, with leftPart defaulting to 0 if empty
STEP 5: Check if the sum of leftPart and rightPart equals n
STEP 6: Return true if the condition is met, otherwise false
main(String[] args):
STEP 1: Read integers p and q from the user as the starting and ending range values
STEP 2: Print the header "THE KAPREKAR NUMBERS ARE:"
STEP 3: Initialize a counter count to 0
STEP 4: Iterate through each number i from p to q inclusive
STEP 5: Check if i is a Kaprekar number using isKaprekar(i)
STEP 6: Print i if it is a Kaprekar number and increment count
STEP 7: After the loop, print the frequency of Kaprekar numbers
SOURCE CODE:
import java.util.Scanner;
public class KaprekarNumbers {

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


public static boolean isKaprekar(int n) {
// Calculate the square of the number
long square = (long) n * n;
String strSquare = Long.toString(square);
int len = strSquare.length();
int d = Integer.toString(n).length();

// Split the square into left and right parts


String rightPart = strSquare.substring(Math.max(0, len - d));
String leftPart = strSquare.substring(0, Math.max(0, len - d));

// Convert parts to integers


int rightNum = Integer.parseInt(rightPart);
int leftNum = leftPart.isEmpty() ? 0 : Integer.parseInt(leftPart);

// Check if the sum of left and right parts equals the original number
return (leftNum + rightNum) == n;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("P = ");
int p = sc.nextInt(); // Starting range value
System.out.print("Q = ");
int q = sc.nextInt(); // Ending range value
// Print header for output
System.out.println("THE KAPREKAR NUMBERS ARE:");

int count = 0;
for (int i = p; i <= q; i++) {
if (isKaprekar(i)) {
System.out.print(i + " ");
count++;
}
}

// Print the frequency of Kaprekar numbers


System.out.println();
System.out.println("FREQUENCY OF KAPREKAR NUMBERS IS:" + count);
}
}

VARIABLE DESCRIPTION TABLE:


OUTPUT:
Question 25:
A class Personal contains employee details and another class Retire calculates the employee’s
Provident Fund and Gratuity. The details of the two classes are given below:
Class name : Personal
Data Members:
Name : stores the employee name
Pan : stores the employee PAN number
basic_pay : stores the employee basic salary (in decimals)
acc_no : stores the employee bank account number
Member functions:
Personal( …. ) : parameterized constructor to assign value to data members
void display( ) : to display the employee details

Class name : Retire


Data Members:
Yrs : stores the employee years of service
Pf : stores the employee provident fund amount ( in decimals )
Grat : stores the employee gratuity amount ( in decimals )
Member functions:
Retire (….) : parameterized constructor to assign value to data members of both the
classes.
void provident( ) : calculates the PF as (2% of the basic pay) * years
of service.
void gratuity( ) : calculates the gratuity as 12 months salary, if the years of service is
more or equal to 10 years else the gratuity amount is nil.
void display1( ) : Displays the employee details along with the PF
(Provident Fund ) and gratuity amount.

Specify the class Personal giving details of the constructor and member functions void
display( ). Using the concept of inheritance, specify the class Retire giving details of
constructor, and the member functions void provident( ), void gratuity( ) and the void
display1( ). The main function need not be written.

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 26:
Chain is an entity which can hold at the most 50 integers. The chain enables the user to add and
remove integers from both the ends i.e. front and rear. Define a class Chain with the following
details:
Class name : Chain
Data Members:
ele[ ] : the array to hold the integer elements.
Cap : stores the maximum capacity of the array.
front : to point the index of the front.
rear : to point the index of the rear.
Member functions:
Chain(int max) : constructor to initialize the data cap = max, front = rear = 0 and to
create the integer array.
void pushfront(int v) : to add integers from the front index if possible else display the
message(“full from front”).
int popfront( ) : to remove the return elements from front. If array is empty then return-
999.
void pushrear(int v) : to add integers from the front index if possible else display the
message(“full from rear”).
int poprear( ) : to remove and return elements from rear. If the array is empty then
return-999.
(a) Specify the class Chain giving details of the constructor and member function void
pushfront(int), int popfront( ), void pushrear(int) and int poprear ( ).The main function need not
be written.

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 27:
Design a “AutoSort” class having the following data members and member functions:
Data Members
int arr[] : stores a list of n integers accepted from the user
int n : stores the size of the array arr
Member functions:
AutoSort()
void insert() : insert the elements within the array in such a way that the elements are
all arranged in the ascending order.
void display() : display the contents of the array
AutoSort merge(AutoSort m) : merges the contents of both the arrays in such way that after
merging the merged array has the elements in ascending order. Do not use any sorting algorithm
to sort the merged array.

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 28:
A Keith number is an n-digit integer N>9 such that if a Fibonacci-like sequence (in which each
term in the sequence is the sum of the n previous terms) is formed with the first n terms taken as
the decimal digits of the number N, then N itself occurs as a term in the sequence. For example,
197 is a Keith number since it generates the sequence 1, 9, 7, , ,
, , .
Design a class named “Keith” having the following data members and member functions :
Data Members:
int n : an integer variable storing the number to be checked.
Member Functions:
void storenum() accepts the number from the user.
boolean checkKeith() Returns true if the number is a Keith as defined above
otherwise returns false.
void findKeithNums(int x,int y) displays all the Keith numbers between x and y(both
inclusive).

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 29:
The Mayan civilisation used three different calendars. In their long count calendar there were 20
days (called kins) in a uinal, 18 uinals in a tun, 20 tuns in a katun and 20 katuns in a baktun. In
our calendar, we specify a date by giving the day, then month, and finally the year. The Maya
specified dates in reverse, giving the baktun (1-20), then katun (1-20), then tun (1-20), then uinal
(1-18) and finally the kin (1-20).
The Mayan date 13 20 7 16 3 corresponds to the date 1 January 2000 (which was a Saturday).
Write a program which, given a Mayan date (between 13 20 7 16 3 and 14 1 15 12 3 inclusive),
outputs the corresponding date in our calendar. You should output the month as a number.
You are reminded that, in our calendar, the number of days in each month is:

1 January 31

2 February 28 / 29 (leap year)

3 March 31

4 April 30

5 May 31

6 June 30

7 July 31

8 August 31

9 September 30

10 October 31

11 November 30

12 December 31

Within the range of dates for this question, every year divisible by 4 is a leap year.
Sample run
13 20 9 2 9
22 3 2001

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 30:
An interface Data is defined with a data member and a method volume() which returns the
volume of the implementing shape. A super class Base has been defined to contain the radius of a
geometrical shape. Define a sub-class CalVol which uses the properties of the interface Data and
the class Base and calculates the volume of a cylinder.
The details of the members of the interface and both the classes are given below:
Interface name: Data
Data member:
double pi: initialize pi = 3.142.
Member function/method:
double volume()
Class name: Base
Data member/instance variable:
rad: to store the radius in decimal.
Member functions/methods:
Base(…): parameterized constructor to initialize the data members.
void show(): displays the radius with an appropriate message.
Class name: CalVol
Data member/instance variable:
ht: to store the height in decimal.
Member functions/methods:
CalVol(…): parameterized constructor to initialize the data members of both the classes.
double volume(): calculates the volume of a sphere by using the formula (pi × radius2 × height)
void show(): displays the data members of both the classes and the volume of the sphere with
appropriate message.
Assume that the interface Data and the super class Base has been defined. Using the concept of
inheritance, specify the class CalVol giving details of the constructor, double volume() and void
show().
The interface, super class, main() function and algorithm need not be written.

ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:

You might also like