0% found this document useful (0 votes)
3 views

Computer Project Xii

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Computer Project Xii

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 203

ISC COMPUTER SCience

PRACTICAL FILE 2024-2025

NAME-RAJRUP CHATTOPADHYAY
CLASS- XII (TWELVE)
SECTION- ‘C’
ROLL NUMBER-25
REGISTRATION NUMBER-2012/169
SESSION: 2024-2025

1
CONTENTS:
TOPIC PAGE NUMBER
Personal Profile 1
Contents 2
QUESTION 1 3-8
QUESTION 2 9-

2
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

3
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].
4
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();

5
// 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();
}
}

6
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].

7
OUTPUT:

8
9
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

10
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.

11
12
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++;
13
} 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();
}
}

14
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

15
OUTPUT:

16
17
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:
18
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.

19
STEP 21: Print "FREQUENCY OF FASCINATING NUMBERS IS: " followed by `cnt`.
STEP 22: Close the `Scanner` object `sc`.
STEP 23: End of algorithm.

20
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) {
21
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
22
fascinating numbers.
cnt int Counter for the number of fascinating main
numbers found.
sc Scanner Scanner object to read user input. main

OUTPUT:

23
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.

24
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`:

25
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--;

26
}

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


27
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

28
OUTPUT:

29
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

30
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.

31
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
.

32
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:
33
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;
}
34
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();
}
}

35
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

36
OUTPUT:

37
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

38
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.

39
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: ");

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

41
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
displayMatrix
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 year. Local
variable in
main method

42
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

43
OUTPUT:

44
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

45
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.

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

47
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
findPrimePairs
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
findPrimePairs
method

48
OUTPUT:

49
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.

50
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.

51
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);
}

52
sc.close();
}
}

53
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.

54
OUTPUT:

55
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

56
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.

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

58
}

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

59
OUTPUT:

60
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
61
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.

62
63
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`:

64
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;

65
}

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

66
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
answers. in
calculateScores
method
i int Loop variable used to iterate over participants and answers. Local variable
in main,
calculateScores,
and
displayScores
methods

j int Loop variable used to iterate over answers for each participant. Local variable
in
calculateScores
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

67
OUTPUT:

68
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

69
70
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.

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

72
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
for lowercase). variable in
encrypt
method
i int Loop variable used to iterate over each character of plainText. Local
variable in
encrypt
method

OUTPUT:

73
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

74
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.

75
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;
}

76
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

smallestNumber int The smallest integer greater than M whose sum of digits Local variable in
equals N. main method,
return value of
findSmallestNumber
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 sum Local variable in
of digits equals N. findSmallestNumber
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

77
count int The count of digits in number. Local variable in
countDigits method

78
OUTPUT:

79
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

80
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.

81
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) {

82
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;
}
}

83
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 composite Local variable in main
magic numbers. method

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

count int The count of composite magic numbers found in the Local variable in
range. printCompositeMagicNumbers
method

i int Loop variable used to iterate through numbers in the Local variable in
range [m, n]. printCompositeMagicNumbers
method

number int The current number being checked in isComposite and Local variable in
isMagicNumber methods. isComposite and
isMagicNumber methods

sum int The sum of digits of number in the isMagicNumber Local variable in
method. isMagicNumber method

84
OUTPUT:

85
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.

86
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.

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

88
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;


}
}

89
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
palindromes. variable 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

90
OUTPUT:

91
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:
92
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.

93
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];
}
}

94
// 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) {
95
return i;
}
}
return -1;
}
}

96
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
flattenedMatrix int[] 1D array to store the matrix elements in a flattened form. Local
variable 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

97
dig int Digit extracted during the reversal process. Local
variable in
isPalin method

OUTPUT:

98
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:
99
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) :
"");
}
}

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:

101
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`.
102
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
}

103
// 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
array. variable 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
current step. variable in
main method

104
OUTPUT:

105
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

106
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;
107
}

// 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();
}
108
}

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 rearranged. Local
variable in
main method
right int Index for placing elements to the right of the center in rearranged. Local
variable in
main method
index int Index for iterating over sorted elements of data. Local
variable in
main method

OUTPUT:

109
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
110
2 6 14
138

111
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.

112
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;
}
}

113
// 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();
}
}
114
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 matrix Local to
elements are stored. main()
hasSaddlePoint boolean Flag indicating whether a saddle point was found in the matrix. Local to
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()

115
OUTPUT:

116
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

117
ALGORITHM:

main(String[] args):

Step 1: Initialize `Scanner sc`.


Step 2: Print "Enter the coded text:".
Step 3: Input the coded text, store it in `code`.
Step 4: Print "Enter the shift value (1-26):".
Step 5: Input the shift value, store it in `shift`.
Step 6: If `shift` is less than 1 or greater than 26, print "INVALID SHIFT VALUE" and return.
Step 7: Initialize an empty string `result`.
Step 8: Iterate over `i` from 0 to `code.length()-1`.
Step 9: Set `ch` to the character at index `i` in `code`.
Step 10: If `ch` is a space, continue to the next iteration.
Step 11: Calculate `decodedChar` by subtracting `shift` from `ch`.
Step 12: If `decodedChar` is less than 'A', add 26 to `decodedChar`.
Step 13: Append `decodedChar` to `result`.
Step 14: Replace "QQ" with a single space in `result`.
Step 15: Initialize an empty `StringBuilder` called `decodedText`.
Step 16: Iterate over `i` from 0 to `result.length()-1`.
Step 17: Append the character at index `i` in `result` to `decodedText`.
Step 18: If `(i + 1) % 6 == 0` and `i` is less than `result.length() - 1`, append a space to
`decodedText`.
Step 19: Print "DECODED TEXT:" followed by the trimmed content of `decodedText`.
Step 20: Close `Scanner sc`.
Step 21: End of algorithm.

118
SOURCE CODE:

import java.util.Scanner;

public class Q20 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Step 1: Input the encoded text and the shift value


System.out.print("Enter the coded text: ");
String code = sc.nextLine().toUpperCase();
System.out.print("Enter the shift value (1-26): ");
int shift = sc.nextInt();

// Step 2: Validate the shift value


if (shift < 1 || shift > 26) {
System.out.println("INVALID SHIFT VALUE");
return;
}

// Step 3: Remove spaces and split into blocks


String result = "";
int len = code.length();

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


char ch = code.charAt(i);

// Skip spaces
if (ch == ' ') continue;

// Step 4: Decrypt the character based on the shift value


char decodedChar = (char) (ch + shift);
if (decodedChar > 'Z') {
decodedChar -= 26; // Wrap around if the character exceeds 'Z'
}

result += decodedChar;

// Add a space after every 6 characters


if (result.length() % 6 == 0 && i < len - 1) {
result += ' ';
}
}

// Step 5: Replace QQ with spaces in the decoded message


119
String decodedText = "";
len = result.length();
for (int i = 0; i < len; i++) {
char ch = result.charAt(i);

// Replace QQ with a single space


if (i < len - 1 && ch == 'Q' && result.charAt(i + 1) == 'Q') {
decodedText += ' ';
i++; // Skip the next 'Q'
} else {
decodedText += ch;
}
}

// Step 6: Output the decoded text


System.out.println("DECODED TEXT: " + decodedText.trim());

sc.close();
}
}

120
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 original Local to
shift). decodeMessage()

decodedMessage StringBuilder String builder to construct the decoded message. Local to


decodeMessage()

ch char Character from the codedText being processed. Local to


decodeMessage()

i int Index for iterating through the codedText and handling 'Q' Local to
replacements. decodeMessage()

121
OUTPUT:

122
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

123
ALGORITHM:

main(String[] args):
Step 1: Initialize `Scanner sc`.
Step 2: Print "Enter the number of users:".
Step 3: Input the number of users, store it in `numUsers`.
Step 4: Create arrays `userId`, `loginTime`, `loginDate`, `logoutTime`,
`logoutDate`, and `duration` of size `numUsers`.
Step 5: Iterate over `i` from 0 to `numUsers-1`.
Step 6: Input `userId[i]`, `loginTime[i]`, `loginDate[i]`, `logoutTime[i]`, and
`logoutDate[i]`.
Step 7: Split `loginTime[i]` and `logoutTime[i]` into hours and minutes.
Step 8: Split `loginDate[i]` and `logoutDate[i]` into day and month.
Step 9: Calculate the total duration in minutes by subtracting login time from
logout time. Account for changes in the day or month if necessary.
Step 10: Convert the total duration from minutes to hours and minutes.
Step 11: Store the calculated duration in `duration[i]`.
Step 12: Print all records with their durations in hours and minutes.
Step 13: Find the user with the longest duration by iterating through the `duration`
array.
Step 14: Print the record of the user with the longest duration.
Step 15: Close `Scanner sc`.
Step 16: End of algorithm.

SOURCE CODE:

import java.util.Scanner;

public class Q21 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Step 2: Input the number of users


System.out.print("Enter the number of users: ");
int numUsers = sc.nextInt();

// Step 4: Initialize arrays


int[] userId = new int[numUsers];
124
String[] loginTime = new String[numUsers];
String[] loginDate = new String[numUsers];
String[] logoutTime = new String[numUsers];
String[] logoutDate = new String[numUsers];
int[] duration = new int[numUsers];

// Step 5: Input data for each user


for (int i = 0; i < numUsers; i++) {
System.out.print("Enter user ID: ");
userId[i] = sc.nextInt();
System.out.print("Enter login time (HH:MM): ");
loginTime[i] = sc.next();
System.out.print("Enter login date (DD-MM): ");
loginDate[i] = sc.next();
System.out.print("Enter logout time (HH:MM): ");
logoutTime[i] = sc.next();
System.out.print("Enter logout date (DD-MM): ");
logoutDate[i] = sc.next();

// Step 7: Parse login and logout times


String[] loginTimeParts = loginTime[i].split(":");
String[] logoutTimeParts = logoutTime[i].split(":");
String[] loginDateParts = loginDate[i].split("-");
String[] logoutDateParts = logoutDate[i].split("-");

int loginHour = Integer.parseInt(loginTimeParts[0]);


int loginMinute = Integer.parseInt(loginTimeParts[1]);
int logoutHour = Integer.parseInt(logoutTimeParts[0]);
int logoutMinute = Integer.parseInt(logoutTimeParts[1]);

int loginDay = Integer.parseInt(loginDateParts[0]);


int logoutDay = Integer.parseInt(logoutDateParts[0]);

// Step 9: Calculate duration in minutes


int totalLoginMinutes = loginHour * 60 + loginMinute + loginDay * 24 *
60;
int totalLogoutMinutes = logoutHour * 60 + logoutMinute + logoutDay *
24 * 60;
int totalDurationMinutes = totalLogoutMinutes - totalLoginMinutes;

// Convert minutes to hours and minutes


125
int durationHours = totalDurationMinutes / 60;
int durationMinutes = totalDurationMinutes % 60;

// Store the duration


duration[i] = totalDurationMinutes;

// Step 12: Print user record with duration


System.out.printf("%d %s %s %s %s %02d : %02d\n", userId[i],
loginTime[i], loginDate[i], logoutTime[i], logoutDate[i], durationHours,
durationMinutes);
}

// Step 13: Find the user with the longest duration


int maxDurationIndex = 0;
for (int i = 1; i < numUsers; i++) {
if (duration[i] > duration[maxDurationIndex]) {
maxDurationIndex = i;
}
}

// Step 14: Print the user who logged in for the longest duration
System.out.println("THE USER WHO LOGGED IN FOR THE LONGEST
DURATION:");
int maxDurationHours = duration[maxDurationIndex] / 60;
int maxDurationMinutes = duration[maxDurationIndex] % 60;
System.out.printf("%d %s %s %s %s %02d : %02d\n",
userId[maxDurationIndex], loginTime[maxDurationIndex],
loginDate[maxDurationIndex], logoutTime[maxDurationIndex],
logoutDate[maxDurationIndex], maxDurationHours, maxDurationMinutes);

// Step 15: Close scanner


sc.close();
}
}

126
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description


Type
sc Scanner Scanner object used for taking input from
the user.
numUsers int Stores the number of users for which data
is to be entered.
userId[] int[] Array storing the unique identification
numbers of the users.
loginTime[] String[] Array storing the login times of the users
in "HH
" format.
loginDate[] String[] Array storing the login dates of the users
in "DD-MM" format.
logoutTime[] String[] Array storing the logout times of the
users in "HH
" format.
logoutDate[] String[] Array storing the logout dates of the
users in "DD-MM" format.
duration[] int[] Array storing the duration (in minutes)
each user was logged in.
loginTimeParts[] String[] Temporary array for storing hours and
minutes after splitting loginTime (HH
and MM separately).
logoutTimeParts[] String[] Temporary array for storing hours and
minutes after splitting logoutTime (HH
and MM separately).
loginDateParts[] String[] Temporary array for storing day and
month after splitting loginDate (DD and
MM separately).
logoutDateParts[] String[] Temporary array for storing day and
month after splitting logoutDate (DD and
MM separately).
loginHour int Stores the hour part of the login time
after parsing from loginTime.
loginMinute int Stores the minute part of the login time
after parsing from loginTime.
logoutHour int Stores the hour part of the logout time
after parsing from logoutTime.
127
logoutMinute int Stores the minute part of the logout time
after parsing from logoutTime.
loginDay int Stores the day part of the login date after
parsing from loginDate.
logoutDay int Stores the day part of the logout date
after parsing from logoutDate.
totalLoginMinutes int Stores the total minutes from the
beginning of the month till the login time
(used to calculate duration).
totalLogoutMinutes int Stores the total minutes from the
beginning of the month till the logout
time (used to calculate duration).
totalDurationMinutes int Stores the total duration (in minutes)
each user was logged in.
durationHours int Stores the hours part of the calculated
duration for each user.
durationMinutes int Stores the minutes part of the calculated
duration for each user.
maxDurationIndex int Index of the user with the longest login
duration.
maxDurationHours int Stores the hours part of the longest
duration.
maxDurationMinutes int Stores the minutes part of the longest
duration.

128
OUTPUT:

129
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
130
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

131
ALGORITHM:

main()
Step 1: Initialize `Scanner sc`.
Step 2: Print "Enter the value of N (2 < N < 10):".
Step 3: Prompt the user to input `n`, store it in `n`.
Step 4: If `n` is less than or equal to 2 or greater than or equal to 10, print "Invalid
value of N. Please enter a value between 3 and 9." and terminate.
Step 5: Create a 2D array `grid` of size `n x n`.
Step 6: Print "Enter the values in the grid:".
Step 7: Iterate over `i` from 0 to `n-1`.
Step 8: Iterate over `j` from 0 to `n-1`.
Step 9: Input grid element at `grid[i][j]`.
Step 10: Calculate the magic constant `magicSum` as `(int) (0.5 * n * (n * n + 1))`.
Step 11: Initialize `isWondrous` to `true`.
Step 12: Iterate over `i` from 0 to `n-1`.
Step 13: Initialize `rowSum` and `colSum` to 0.
Step 14: Iterate over `j` from 0 to `n-1`.
Step 15: Add `grid[i][j]` to `rowSum`.
Step 16: Add `grid[j][i]` to `colSum`.
Step 17: If `rowSum` or `colSum` is not equal to `magicSum`, set `isWondrous` to
`false` and break the loop.
Step 18: Print "YES IT REPRESENTS A WONDROUS SQUARE." if
`isWondrous` is `true`, otherwise print "NO IT DOES NOT REPRESENT A
WONDROUS SQUARE.".
Step 19: Print "PRIME\tROW INDEX\tCOLUMN INDEX".
Step 20: Iterate over `i` from 0 to `n-1`.
Step 21: Iterate over `j` from 0 to `n-1`.
132
Step 22: If `grid[i][j]` is a prime number, print `grid[i][j]`, `i`, and `j`.
Step 23: Close `Scanner sc`.
Step 24: End of algorithm.

isPrime(int num):
Step 1: If `num` is less than 2, return `false`.
Step 2: Iterate `i` from 2 to `sqrt(num)`.
Step 3: If `num` modulo `i` equals 0, return `false`.
Step 4: Return `true`.

133
SOURCE CODE:
import java.util.Scanner;

public class WondrousSquare {

// Function to check if a number is prime


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

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Step 1: Input the value of n


System.out.print("Enter the value of N (2 < N < 10): ");
int n = sc.nextInt();

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


System.out.println("Invalid value of N. Please enter a value between 3 and
9.");
return;

134
}

int[][] grid = new int[n][n];

// Step 2: Input the grid values


System.out.println("Enter the values in the grid:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = sc.nextInt();
}
}

// Step 3: Calculate the magic constant for a wondrous square


int magicSum = (int) (0.5 * n * (n * n + 1));

// Step 4: Check rows and columns for the magic sum


boolean isWondrous = true;
for (int i = 0; i < n; i++) {
int rowSum = 0;
int colSum = 0;
for (int j = 0; j < n; j++) {
rowSum += grid[i][j];
colSum += grid[j][i];
}
if (rowSum != magicSum || colSum != magicSum) {
isWondrous = false;

135
break;
}
}

// Step 5: Output if the grid is a wondrous square


if (isWondrous) {
System.out.println("YES IT REPRESENTS A WONDROUS SQUARE.");
} else {
System.out.println("NO IT DOES NOT REPRESENT A WONDROUS
SQUARE.");
}

// Step 6: Find and print all prime numbers in the grid with their indices
System.out.println("PRIME\tROW INDEX\tCOLUMN INDEX");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (isPrime(grid[i][j])) {
System.out.println(grid[i][j] + "\t" + i + "\t\t" + j);
}
}
}

sc.close();
}
}

136
VARIABLE DESCRIPTION TABLE:

Variable Name Data Type Description Scope

sc Scanner Scanner object used for Local (in `main`


taking input from the method)
user.

num int Stores the number Local (in `isPrime`


being checked for method)
primality.

i int Loop counter for Local (in `isPrime` and


iteration in both `main` methods)
`isPrime` and `main`
methods.

n int Stores the size of the Local (in `main`


grid (dimension) and method)
used for validation.

grid int[][] 2D array representing Local (in `main`


the grid of numbers. method)

magicSum int Stores the calculated Local (in `main`


magic constant for a method)
wondrous square.

isWondrous boolean Flag indicating whether Local (in `main`


the grid satisfies the method)
wondrous condition.

rowSum int Stores the sum of the Local (in `main`


current row elements. method)

colSum int Stores the sum of the Local (in `main`


current column method)
elements.

137
OUTPUT:

138
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.

139
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

140
SOURCE CODE:
import java.util.Scanner;

public class DateDayCalculator {

// Function to get the day of the week for a given date


static String getDayOfWeek(int day, int month, int year) {
int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
monthDays[1] = 29; // February has 29 days in a leap year
}

int totalDays = day;


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

// Zeller's Congruence algorithm to find the day of the week


int k = year % 100; // The year within the century
int j = year / 100; // The zero-based century (actually year / 100)
int dayOfWeek = (day + (13 * (month + 1)) / 5 + k + k / 4 + j / 4 + 5 * j) % 7;

// Convert result to day of the week


String[] days = {"SATURDAY", "SUNDAY", "MONDAY", "TUESDAY",
"WEDNESDAY", "THURSDAY", "FRIDAY"};
return days[dayOfWeek];
}

// Function to check if a year is a leap year

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

// Function to validate the date


static boolean isValidDate(int day, int month, int year) {
if (year < 1 || month < 1 || month > 12 || day < 1) {
return false;
}

int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
monthDays[1] = 29;
}

return day <= monthDays[month - 1];


}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input date and day on January 1st


System.out.print("Enter date (dd/mm/yyyy): ");
String dateInput = sc.nextLine();
System.out.print("Enter day on 1st January of that year: ");
String dayOnJan1 = sc.nextLine().toUpperCase();

// Parse the input date


String[] dateParts = dateInput.split("/");

142
int day = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);

// Validate the date and day on January 1st


if (!isValidDate(day, month, year) || !isValidDay(dayOnJan1)) {
System.out.println("Invalid input.");
return;
}

// Find the day of the week for January 1st of the given year
String startDayOfWeek = getDayOfWeek(1, 1, year);

// Calculate the difference in days from January 1st


int dayDifference = getDayDifference(day, month, year);
String targetDayOfWeek = getDayOfWeek(dayDifference, 1, year);

// Output the result


System.out.println("Day on " + dateInput + " : " + targetDayOfWeek);

sc.close();
}

// Function to get the difference in days from January 1st


static int getDayDifference(int day, int month, int year) {
int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
monthDays[1] = 29;
}

143
int totalDays = day;
for (int i = 0; i < month - 1; i++) {
totalDays += monthDays[i];
}
return totalDays - 1; // Subtract 1 because January 1st is considered as day 0
}

// Function to validate day names


static boolean isValidDay(String day) {
String[] validDays = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY",
"THURSDAY", "FRIDAY", "SATURDAY"};
for (String validDay : validDays) {
if (validDay.equals(day)) {
return true;
}
}
return false;
}
}
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;
}

144
// Find the day of the week for the given date
String resultDay = findDay(day, month, year, dayOn1stJanuary);
System.out.println("Day on " + dateInput + " : " + resultDay);
}
}

145
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
monthDays int[] Array holding the Local to getDayOfWeek
number of days in each and isValidDate
month functions
totalDays int Sum of days from the Local to getDayOfWeek
start of the year to the function
given date
k int Year within the century Local to getDayOfWeek
function
j int Zero-based century Local to getDayOfWeek
(year / 100) function
dayOfWeek int Calculated day of the Local to getDayOfWeek
week using Zeller’s function
Congruence
days String[] Array holding the Local to getDayOfWeek
names of the days of the function
week
sc Scanner Scanner object for Local to main function
reading user input
dateInput String User input for the date Local to main function
in dd/mm/yyyy format

146
OUTPUT:

147
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

148
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

149
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 = ");
150
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);
}
}

151
VARIABLE DESCRIPTION TABLE:

Variable Name Data Type Description Scope

sc Scanner Scanner object used Local (in `main`


for taking input from method)
the user.

p int Starting range value Local (in `main`


for checking method)
Kaprekar numbers.

q int Ending range value Local (in `main`


for checking method)
Kaprekar numbers.

count int Stores the count of Local (in `main`


Kaprekar numbers method)
found.

square long Stores the square of Local (in


the number being `isKaprekar` method)
checked.

strSquare String String representation Local (in


of the squared `isKaprekar` method)
number.

len int Length of the string Local (in


representation of the `isKaprekar` method)
squared number.

d int Length of the original Local (in


number being `isKaprekar` method)
checked.

rightPart String Right part of the split Local (in


squared number. `isKaprekar` method)

leftPart String Left part of the split Local (in


squared number. `isKaprekar` method)

rightNum int Integer value of the Local (in


right part of the `isKaprekar` method)
squared number.

152
153
OUTPUT:

154
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

155
constructor, and the member functions void provident( ), void gratuity( ) and the void
display1( ). The main function need not be written.

ALGORITHM:

Personal Class:

Constructor Personal(String name, String pan, double basicPay, String


accNo):
Step 1: Initialize `name` with the provided value.
Step 2: Initialize `pan` with the provided value.
Step 3: Initialize `basicPay` with the provided value.
Step 4: Initialize `accNo` with the provided value.

void display():
Step 1: Print "Name: " followed by the value of `name`.
Step 2: Print "PAN: " followed by the value of `pan`.
Step 3: Print "Basic Pay: " followed by the value of `basicPay`.
Step 4: Print "Account Number: " followed by the value of `accNo`.

---

Retire Class (extends Personal):

Constructor Retire(String name, String pan, double basicPay, String accNo,


int yrs):

156
Step 1: Call the superclass constructor `Personal(name, pan, basicPay, accNo)`.
Step 2: Initialize `yrs` with the provided value.
Step 3: Call the `provident()` method to calculate the provident fund.
Step 4: Call the `gratuity()` method to calculate the gratuity.

void provident():
Step 1: Calculate the provident fund as `0.02 * basicPay * yrs`.
Step 2: Store the result in `pf`.

void gratuity():
Step 1: If `yrs` is greater than or equal to 10, set `grat` to `12 * basicPay`.
Step 2: Otherwise, set `grat` to 0.

void display1():
Step 1: Call the `display()` method from the superclass to print employee details.
Step 2: Print "Provident Fund: " followed by the value of `pf`.
Step 3: Print "Gratuity: " followed by the value of `grat`.

157
SOURCE CODE:
// Class Personal
class Personal {
// Data members
String name;
String pan;
double basicPay;
String accNo;

// Parameterized constructor
Personal(String name, String pan, double basicPay, String accNo) {
this.name = name;
this.pan = pan;
this.basicPay = basicPay;
this.accNo = accNo;
}

// Method to display employee details


void display() {
System.out.println("Name: " + name);
System.out.println("PAN: " + pan);
System.out.println("Basic Pay: " + basicPay);
System.out.println("Account Number: " + accNo);
}
}

158
// Class Retire that extends Personal
class Retire extends Personal {
// Data members
int yrs;
double pf;
double grat;

// Parameterized constructor
Retire(String name, String pan, double basicPay, String accNo, int yrs) {
super(name, pan, basicPay, accNo);
this.yrs = yrs;
provident();
gratuity();
}

// Method to calculate the provident fund (PF)


void provident() {
pf = 0.02 * basicPay * yrs;
}

// Method to calculate the gratuity


void gratuity() {
if (yrs >= 10) {
grat = 12 * basicPay;
} else {
grat = 0;

159
}
}

// Method to display employee details along with PF and gratuity


void display1() {
display(); // Call display method of the superclass
System.out.println("Provident Fund: " + pf);
System.out.println("Gratuity: " + grat);
}
}

160
VARIABLE DESCRIPTION TABLE:

Variable Name Data Type Description Scope

name String Stores the name of the Instance (in `Personal`


employee. class)

pan String Stores the PAN number Instance (in `Personal`


of the employee. class)

basicPay double Stores the basic pay of Instance (in `Personal`


the employee. class)

accNo String Stores the account Instance (in `Personal`


number of the class)
employee.

yrs int Stores the number of Instance (in `Retire`


years the employee has class)
worked.

pf double Stores the calculated Instance (in `Retire`


provident fund (PF) class)
amount.

grat double Stores the calculated Instance (in `Retire`


gratuity amount. class)

161
OUTPUT:

162
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.

163
ALGORITHM:

Chain Constructor (int max):


Step 1: Input maximum capacity `max`.
Step 2: Initialize `cap` with `max`.
Step 3: Initialize `front` and `rear` to 0.
Step 4: Initialize `size` to 0.
Step 5: Create an integer array `ele` with capacity `cap`.

pushfront(int v):
Step 1: Check if `size` is greater than or equal to `cap`.
Step 2: If true, print "full from front".
Step 3: If false, adjust `front` index to `(front - 1 + cap) % cap`.
Step 4: Set `ele[front]` to `v`.
Step 5: Increment `size` by 1.

popfront():
Step 1: Check if `size` is 0.
Step 2: If true, return -999.
Step 3: If false, store `ele[front]` in `value`.
Step 4: Adjust `front` index to `(front + 1) % cap`.
Step 5: Decrement `size` by 1.
Step 6: Return `value`.

pushrear(int v):
Step 1: Check if `size` is greater than or equal to `cap`.

164
Step 2: If true, print "full from rear".
Step 3: If false, set `ele[rear]` to `v`.
Step 4: Adjust `rear` index to `(rear + 1) % cap`.
Step 5: Increment `size` by 1.

poprear():
Step 1: Check if `size` is 0.
Step 2: If true, return -999.
Step 3: If false, adjust `rear` index to `(rear - 1 + cap) % cap`.
Step 4: Store `ele[rear]` in `value`.
Step 5: Decrement `size` by 1.
Step 6: Return `value`.

165
SOURCE CODE:
// Class to represent a chain of integers with operations at both ends
class Chain {
// Data members
private int[] ele; // Array to hold integer elements
private int cap; // Maximum capacity of the array
private int front; // Index of the front
private int rear; // Index of the rear
private int size; // Number of elements currently in the chain

// Constructor to initialize the Chain


Chain(int max) {
cap = max;
front = 0;
rear = 0;
size = 0;
ele = new int[cap]; // Create integer array with given capacity
}

// Method to add an integer from the front


void pushfront(int v) {
if (size >= cap) {
System.out.println("full from front");
} else {
// Adjust front index
front = (front - 1 + cap) % cap;

166
ele[front] = v;
size++;
}
}

// Method to remove and return an integer from the front


int popfront() {
if (size == 0) {
return -999; // Return -999 if the chain is empty
} else {
int value = ele[front];
// Adjust front index
front = (front + 1) % cap;
size--;
return value;
}
}

// Method to add an integer from the rear


void pushrear(int v) {
if (size >= cap) {
System.out.println("full from rear");
} else {
ele[rear] = v;
// Adjust rear index
rear = (rear + 1) % cap;

167
size++;
}
}

// Method to remove and return an integer from the rear


int poprear() {
if (size == 0) {
return -999; // Return -999 if the chain is empty
} else {
// Adjust rear index
rear = (rear - 1 + cap) % cap;
int value = ele[rear];
size--;
return value;
}
}
}

168
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
ele int[] Array to hold integer Instance variable of Chain
elements class
cap int Maximum capacity of the Instance variable of Chain
array class
front int Index of the front Instance variable of Chain
class
rear int Index of the rear Instance variable of Chain
class
size int Number of elements Instance variable of Chain
currently in the chain class
max int Maximum capacity passed Local variable in Chain
to the constructor constructor
v int Value to be added to the Parameter in pushfront and
chain pushrear methods
value int Value removed from the Local variable in popfront
chain and poprear methods

169
OUTPUT:

After two elements are 5 and 6. They are pushed into the chain fromm rear
and front respectively:

170
171
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:

AutoSort Constructor:
Step 1: Initialize `n` to 0.
Step 2: Initialize `arr` as a new integer array of size 0.

insert(int[] elements):
Step 1: Calculate `newSize` as the sum of `n` and the length of `elements`.
Step 2: Create a new integer array `newArr` of size `newSize`.
Step 3: Initialize indices `i`, `j`, and `k` to 0.
Step 4: Merge `arr` and `elements` into `newArr` as follows:
- While `i < n` and `j < elements.length`:
- If `arr[i] <= elements[j]`, set `newArr[k++]` to `arr[i++]`.

172
- Otherwise, set `newArr[k++]` to `elements[j++]`.
Step 5: Copy remaining elements from `arr` to `newArr` if `i < n`.
Step 6: Copy remaining elements from `elements` to `newArr` if `j <
elements.length`.
Step 7: Replace `arr` with `newArr`.
Step 8: Update `n` to `newSize`.

display():
Step 1: If `n` is 0, print "Array is empty." and return.
Step 2: Iterate over `i` from 0 to `n-1`.
- Print `arr[i]` followed by a space.
Step 3: Print a newline character.

merge(AutoSort m):
Step 1: Create a new `AutoSort` object `result`.
Step 2: Create an integer array `mergedArr` of size `this.n + m.n`.
Step 3: Initialize indices `i`, `j`, and `k` to 0.
Step 4: Merge `this.arr` and `m.arr` into `mergedArr` as follows:
- While `i < this.n` and `j < m.n`:
- If `this.arr[i] <= m.arr[j]`, set `mergedArr[k++]` to `this.arr[i++]`.
- Otherwise, set `mergedArr[k++]` to `m.arr[j++]`.
Step 5: Copy remaining elements from `this.arr` to `mergedArr` if `i < this.n`.
Step 6: Copy remaining elements from `m.arr` to `mergedArr` if `j < m.n`.
Step 7: Initialize `result.arr` with `mergedArr`.
Step 8: Set `result.n` to the length of `mergedArr`.
Step 9: Return `result`.

173
SOURCE CODE:
// Class to represent an auto-sorting array
class AutoSort {
// Data members
private int[] arr; // Array to store integers
private int n; // Size of the array

// Default constructor
AutoSort() {
n = 0;
arr = new int[0];
}

// Method to insert elements into the array in sorted order


void insert(int[] elements) {
// Create a new array to accommodate new elements
int newSize = n + elements.length;
int[] newArr = new int[newSize];

int i = 0, j = 0, k = 0;

// Merge current array with new elements


while (i < n && j < elements.length) {
if (arr[i] <= elements[j]) {
newArr[k++] = arr[i++];
} else {

174
newArr[k++] = elements[j++];
}
}

// Copy remaining elements if any


while (i < n) {
newArr[k++] = arr[i++];
}
while (j < elements.length) {
newArr[k++] = elements[j++];
}

// Replace old array with the new sorted array


arr = newArr;
n = newSize;
}

// Method to display the contents of the array


void display() {
if (n == 0) {
System.out.println("Array is empty.");
return;
}
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}

175
System.out.println();
}

// Method to merge two AutoSort objects


AutoSort merge(AutoSort m) {
// Create a new AutoSort object for the merged result
AutoSort result = new AutoSort();

// Merge the contents of both arrays


int[] mergedArr = new int[this.n + m.n];
int i = 0, j = 0, k = 0;

// Merge both arrays into mergedArr


while (i < this.n && j < m.n) {
if (this.arr[i] <= m.arr[j]) {
mergedArr[k++] = this.arr[i++];
} else {
mergedArr[k++] = m.arr[j++];
}
}

// Copy remaining elements if any


while (i < this.n) {
mergedArr[k++] = this.arr[i++];
}
while (j < m.n) {

176
mergedArr[k++] = m.arr[j++];
}

// Initialize the result AutoSort object with the merged array


result.arr = mergedArr;
result.n = mergedArr.length;

return result;
}
}

VARIABLE DESCRIPTION TABLE:


Variable Data Description Scope
Name Type
arr int[] Array to store integers Instance variable in
AutoSort class
n int Size of the array Instance variable in
AutoSort class
elements int[] Array of elements to be Parameter in insert
inserted method
newSize int New size of the array Local variable in insert
after insertion method
newArr int[] New array to Local variable in insert
accommodate new method
elements
i int Index for current array Local variable in insert
and merge methods
j int Index for elements array Local variable in insert

177
and merge methods
k int Index for new array Local variable in insert
and merge methods
m AutoSort Another AutoSort object Parameter in merge
to be merged method
result AutoSort New AutoSort object for Local variable in
the merged result merge method
mergedArr int[] Array to store merged Local variable in
elements merge method

OUTPUT:

178
Output through Display() function after entering the array elements through
command line interface:

179
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, 1+ 9+7 = 17, 9+7+17= 33,
7+17+33= 57, 17+ 33 + 57 = 107 , 33 + 57 + 107 = 197 .
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).

180
ALGORITHM:

storenum():
Step 1: Initialize `Scanner sc`.
Step 2: Print "Enter the number to be checked:".
Step 3: Read the integer input from the user and store it in `n`.
Step 4: Close `Scanner sc`.
Step 5: End of method.

checkKeith():
Step 1: Initialize `temp` with `n`.
Step 2: Initialize `numDigits` to 0.
Step 3: Create an integer array `digits` with size 10.
Step 4: Extract digits from `temp` and store them in `digits`.
Step 5: Increment `numDigits` for each digit extracted.
Step 6: Reverse the `digits` array.
Step 7: Create an integer array `sequence` with size `numDigits`.
Step 8: Copy the `digits` array to `sequence`.
Step 9: Enter an infinite loop.
Step 10: Initialize `nextTerm` to 0.
Step 11: Compute the next term by summing all elements in `sequence`.
Step 12: If `nextTerm` equals `n`, return `true`.
Step 13: If `nextTerm` exceeds `n`, return `false`.
Step 14: Shift the elements in `sequence` to the left by one position.
Step 15: Set the last element of `sequence` to `nextTerm`.
Step 16: Repeat from Step 9.

181
Step 17: End of method.

findKeithNums(int x, int y):


Step 1: Print "Keith numbers between x and y:".
Step 2: Iterate `i` from `x` to `y`.
Step 3: Create a new instance of `Keith` called `k`.
Step 4: Set `k.n` to `i`.
Step 5: If `k.checkKeith()` returns `true`, print `i`.
Step 6: Print a space after each number.
Step 7: Print a newline after the loop completes.
Step 8: End of method.

182
SOURCE CODE:
import java.util.Scanner;

// Class to represent a Keith number


class Keith {
// Data member to store the number to be checked
private int n;

// Method to accept the number from the user


void storenum() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number to be checked: ");
n = sc.nextInt();
}

// Method to check if the number is a Keith number


boolean checkKeith() {
// Convert number to its digits
int temp = n;
int numDigits = 0;
int[] digits = new int[10]; // Array to store digits (size 10 should be enough for
any practical number)

// Extract digits and store in array


while (temp > 0) {
digits[numDigits++] = temp % 10;

183
temp /= 10;
}

// Reverse the digits array


for (int i = 0; i < numDigits / 2; i++) {
int tempDigit = digits[i];
digits[i] = digits[numDigits - i - 1];
digits[numDigits - i - 1] = tempDigit;
}

// Generate the Fibonacci-like sequence


int[] sequence = new int[numDigits];
System.arraycopy(digits, 0, sequence, 0, numDigits);

while (true) {
int nextTerm = 0;
// Compute the next term in the sequence
for (int i = 0; i < numDigits; i++) {
nextTerm += sequence[i];
}

if (nextTerm == n) {
return true; // Number found in sequence
} else if (nextTerm > n) {
return false; // Number not found and exceeded
}

184
// Shift the sequence and add the new term
for (int i = 1; i < numDigits; i++) {
sequence[i - 1] = sequence[i];
}
sequence[numDigits - 1] = nextTerm;
}
}

// Method to find and display all Keith numbers between x and y (inclusive)
void findKeithNums(int x, int y) {
System.out.println("Keith numbers between " + x + " and " + y + ":");
for (int i = x; i <= y; i++) {
Keith k = new Keith();
k.n = i; // Set the number
if (k.checkKeith()) {
System.out.print(i + " ");
}
}
System.out.println();
}
}

185
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
n int Number to be checked if it Instance variable in
is a Keith number Keith class
sc Scanner Scanner object for reading Local variable in
user input storenum method
temp int Temporary variable to hold Local variable in
the number during digit checkKeith method
extraction
numDigits int Number of digits in the Local variable in
number checkKeith method
digits int[] Array to store the digits of Local variable in
the number checkKeith method
tempDigit int Temporary variable for Local variable in
swapping digits checkKeith method
sequence int[] Array to store the Local variable in
Fibonacci-like sequence checkKeith method
nextTerm int Next term in the Fibonacci- Local variable in
like sequence checkKeith method
x int Lower bound of the range Parameter in
to find Keith numbers findKeithNums
method
y int Upper bound of the range Parameter in
to find Keith numbers findKeithNums
method

186
OUTPUT:

Output by the function void findkeithNums(int x, int y) for input x = 10, y =


1000

187
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

188
ALGORITHM:
isLeapYear(int year):
Step 1: If `year` is divisible by 4, return `true`.
Step 2: Otherwise, return `false`.
Step 3: End of method.

daysInMonth(int month, int year):


Step 1: If `month` is 1 (January), return 31.
Step 2: If `month` is 2 (February), return 29 if `year` is a leap year; otherwise,
return 28.
Step 3: If `month` is 3 (March), return 31.
Step 4: If `month` is 4 (April), return 30.
Step 5: If `month` is 5 (May), return 31.
Step 6: If `month` is 6 (June), return 30.
Step 7: If `month` is 7 (July), return 31.
Step 8: If `month` is 8 (August), return 31.
Step 9: If `month` is 9 (September), return 30.
Step 10: If `month` is 10 (October), return 31.
Step 11: If `month` is 11 (November), return 30.
Step 12: If `month` is 12 (December), return 31.
Step 13: Return 0 if `month` is invalid.
Step 14: End of method.

convertMayanToGregorian(int baktun, int katun, int tun, int uinal, int kin):
Step 1: Calculate `daysFromStart` as follows:
- `daysFromStart` = (baktun - 13) * 144000 +

189
(katun - 20) * 7200 +
(tun - 7) * 360 +
(uinal - 16) * 20 +
(kin - 3)
Step 2: Initialize `year` to 2000, `month` to 1, and `day` to 1.
Step 3: While `daysFromStart` is greater than 0:
- Step 3.1: Get the number of days in the current month using
`daysInMonth(month, year)`.
- Step 3.2: If `day + daysFromStart` is less than or equal to `daysThisMonth`,
update `day` to `day + daysFromStart`, set `daysFromStart` to 0.
- Step 3.3: Otherwise, subtract `(daysThisMonth - day + 1)` from
`daysFromStart`, set `day` to 1, increment `month`.
- Step 3.4: If `month` is greater than 12, reset `month` to 1 and increment `year`.
Step 4: Print `day`, `month`, and `year`.
Step 5: End of method.

main(String[] args):
Step 1: Initialize `Scanner sc`.
Step 2: Print "Enter the Mayan date (baktun katun tun uinal kin):".
Step 3: Read `baktun`, `katun`, `tun`, `uinal`, and `kin` from user input.
Step 4: If `baktun`, `katun`, `tun`, `uinal`, or `kin` are out of valid range, print
"Invalid Mayan date."
Step 5: Otherwise, call `convertMayanToGregorian(baktun, katun, tun, uinal, kin)`.
Step 6: Close `Scanner sc`.
Step 7: End of method.

190
SOURCE CODE:
import java.util.Scanner;

public class MayanToGregorian {

// Function to calculate if a year is a leap year


static boolean isLeapYear(int year) {
return year % 4 == 0;
}

// Function to get the number of days in a month


static int daysInMonth(int month, int year) {
switch (month) {
case 1: return 31; // January
case 2: return isLeapYear(year) ? 29 : 28; // February
case 3: return 31; // March
case 4: return 30; // April
case 5: return 31; // May
case 6: return 30; // June
case 7: return 31; // July
case 8: return 31; // August
case 9: return 30; // September
case 10: return 31; // October
case 11: return 30; // November
case 12: return 31; // December
default: return 0; // Invalid month

191
}
}

// Function to convert Mayan date to Gregorian date


static void convertMayanToGregorian(int baktun, int katun, int tun, int uinal, int
kin) {
// Calculate the total number of days since 13.20.7.16.3
int daysFromStart = (baktun - 13) * 144000 +
(katun - 20) * 7200 +
(tun - 7) * 360 +
(uinal - 16) * 20 +
(kin - 3);

// Calculate Gregorian start date (1 January 2000)


int year = 2000;
int month = 1;
int day = 1;

// Adjust days for each month and year


while (daysFromStart > 0) {
int daysThisMonth = daysInMonth(month, year);
if (day + daysFromStart <= daysThisMonth) {
day += daysFromStart;
daysFromStart = 0;
} else {
daysFromStart -= (daysThisMonth - day + 1);
day = 1;
192
month++;
if (month > 12) {
month = 1;
year++;
}
}
}

// Print the Gregorian date


System.out.printf("%d %d %d\n", day, month, year);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input Mayan date


System.out.print("Enter the Mayan date (baktun katun tun uinal kin): ");
int baktun = sc.nextInt();
int katun = sc.nextInt();
int tun = sc.nextInt();
int uinal = sc.nextInt();
int kin = sc.nextInt();

// Validate Mayan date


if (baktun < 13 || baktun > 14 ||
katun < 1 || katun > 20 ||

193
tun < 1 || tun > 20 ||
uinal < 1 || uinal > 18 ||
kin < 1 || kin > 20) {
System.out.println("Invalid Mayan date.");
} else {
// Convert and output Gregorian date
convertMayanToGregorian(baktun, katun, tun, uinal, kin);
}

sc.close();
}
}

194
VARIABLE DESCRIPTION TABLE:

Variable Name Data Description Scope


Type
year int Year to check Parameter in isLeapYear,
for leap year or daysInMonth, and
calculate days convertMayanToGregorian
functions
month int Month to Parameter in daysInMonth
calculate the function
number of days
baktun int Mayan calendar Parameter in
unit convertMayanToGregorian
representing function
144,000 days
katun int Mayan calendar Parameter in
unit convertMayanToGregorian
representing function
7,200 days
tun int Mayan calendar Parameter in
unit convertMayanToGregorian
representing function
360 days
uinal int Mayan calendar Parameter in
unit convertMayanToGregorian
representing 20 function
days
kin int Mayan calendar Parameter in
unit convertMayanToGregorian
representing 1 function
day
daysFromStart int Total number of Local variable in
days since a convertMayanToGregorian
195
specific Mayan function
date
day int Day of the Local variable in
month convertMayanToGregorian
function
daysThisMonth int Number of days Local variable in
in the current convertMayanToGregorian
month function
!

OUTPUT:

196
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.

197
ALGORITHM:
CalVol Constructor (double r, double h):
Step 1: Input radius `r` and height `h`.
Step 2: Call the constructor of the `Base` class with radius `r`.
Step 3: Initialize height `ht` with `h`.

volume():
Step 1: Calculate the volume using the formula `pi * rad * rad * ht`.
Step 2: Return the calculated volume.

show():
Step 1: Call the `show()` method of the `Base` class to display the radius.
Step 2: Display the height `ht`.
Step 3: Call the `volume()` method to calculate the volume and display it.

Base Constructor (double r):


Step 1: Input radius `r`.
Step 2: Initialize the data member `rad` with `r`.

Base show():
Step 1: Display the radius `rad`.

Data Interface:
Step 1: Define a constant `double pi = 3.142`.
Step 2: Define an abstract method `double volume()`.

198
SOURCE CODE:
// Define the interface Data
interface Data {
double pi = 3.142; // Initialize pi
double volume(); // Method to calculate volume
}

// Define the super class Base


class Base {
protected double rad; // Radius of the geometrical shape

// Parameterized constructor to initialize radius


Base(double r) {
rad = r;
}

// Method to display the radius


void show() {
System.out.println("Radius: " + rad);
}
}

// Define the subclass CalVol that implements Data and extends Base
class CalVol extends Base implements Data {
private double ht; // Height of the cylinder

199
// Parameterized constructor to initialize radius and height
CalVol(double r, double h) {
super(r); // Initialize radius using Base class constructor
ht = h;
}

// Method to calculate the volume of the cylinder


@Override
public double volume() {
return pi * rad * rad * ht; // Volume formula: pi * radius^2 * height
}

// Method to display the radius, height, and volume


@Override
void show() {
super.show(); // Display the radius
System.out.println("Height: " + ht); // Display the height
System.out.println("Volume: " + volume()); // Display the volume
}
}

200
VARIABLE DESCRIPTION TABLE:

Variable Data Description Scope


Name Type
pi double Constant value of π Interface variable in Data
(pi)
rad double Radius of the Instance variable in Base
geometrical shape class
ht double Height of the cylinder Instance variable in CalVol
class
r double Radius passed to the Parameter in Base and
constructor CalVol constructors
h double Height passed to the Parameter in CalVol
constructor constructor

201
OUTPUT:

202
Output from running void show():

203

You might also like