Ar Comp
Ar Comp
A Prime-Adam integer is a positive integer (without leading zeroes) which is a prime as well as
an Adam number.
Prime number: A number which has only two factors, i.e. 1 and the number itself. Example: 2, 3,
5, 7, etc.
Adam number: The square of a number and the square of its reverse are reverse to each other.
Example: If n = 13 and reverse of ‘n’ is 31, then, 132 = 169, and 312 = 961 which is reverse of
169. Thus, 13 is an Adam number.
Accept two positive integers m and n, where m is less than n as user input. Display all Prime-
Adam integers that are in the range between m and n (both inclusive) and output them along with
the frequency, in the format given below:
Test your program with the following data and some random data:
Example 1:
INPUT:
m=5
n = 100
OUTPUT:
The Prime-Adam integers are:
11, 13, 31
Frequency of Prime-Adam integers is: 3
Example 2:
INPUT:
m = 100
n = 200
OUTPUT:
The Prime-Adam integers are:
101, 103, 113
Frequency of Prime-Adam integers is: 3
Example 3:
INPUT:
m = 50
n = 70
OUTPUT:
The Prime-Adam integers are:
NIL
Frequency of Prime-Adam integers is: 0
Example 4:
INPUT:
m = 700
n = 450
OUTPUT:
Invalid Input
ALGORITHM:
isPrime():
Step 1: Start of algorithm.
Step 2: If num <= 1, return false.
Step 3: Set i = 2.
Step 4: While i <= √num, do the following:
Step 4.1: If num % i == 0, return false.
Step 4.2: Increment i by 1.
Step 5: Return true.
Step 6: End of algorithm.
reverse():
Step 1: Start of algorithm.
Step 2: Set rev = 0.
Step 3: While num != 0, do the following:
Step 3.1: Set rev = rev * 10 + num % 10.
Step 3.2: Set num = num / 10.
Step 4: Return rev.
Step 5: End of algorithm.
isAdam():
Step 1: Start of algorithm.
Step 2: Set revNum = reverse(num).
Step 3: Set sqNum = num * num.
Step 4: Set sqRevNum = revNum * revNum.
Step 5: If sqNum == reverse(sqRevNum), return true.
Step 6: Otherwise, return false.
Step 7: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Initialize Scanner sc.
Step 3: Prompt the user to enter m, store it in m.
Step 4: Prompt the user to enter n, store it in n.
Step 5: If m > n, print "Invalid Input." and exit.
Step 6: Initialize an array primeAdamNumbers to store results.
Step 7: Set count = 0.
Step 8: For i = m to n, do the following:
Step 8.1: If isPrime(i) == true and isAdam(i) == true, do the following:
Step 8.1.1: Store i in primeAdamNumbers[count].
Step 8.1.2: Increment count by 1.
Step 9: Print "The Prime-Adam integers are:".
Step 10: If count == 0, print "NIL".
Step 11: Else, for j = 0 to count - 1, do the following:
Step 11.1: Print primeAdamNumbers[j].
Step 12: Print "Frequency of Prime-Adam integers is: " + count.
Step 13: Close Scanner sc.
Step 14: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
A MOBIUS function M(N) returns the value -1 or 0 or 1 for a natural number (N) by the
following conditions are defined:
When,
M(N) = 1 if N = 1
M(N) = 0 if any prime factor of N is contained in N more than once.
M(N) = (-1)P if N is the product of ‘P’ distinct prime factors.
Write a program to accept a positive natural number (N) and display the MOBIUS result with
proper message.
Design your program which will enable the output in the format given below:
Sample 1:
INPUT: 78
OUTPUT:
78 = 2 × 3 × 13
NUMBER OF DISTINCT PRIME FACTORS = 3
M(78) = -1
Sample 2:
INPUT: 34
OUTPUT:
34 = 2 × 17
NUMBER OF DISTINCT PRIME FACTORS = 2
M(34) = 1
Sample 3:
INPUT: 12
OUTPUT:
12 = 2 × 2 × 3
DUPLICATE PRIME FACTORS
M(12) = 0
Sample 4:
INPUT: 1
OUTPUT:
1=1
NO PRIME FACTORS
M(1) = 1
ALGORITHM:
mobius(int num):
Step 1: Start of algorithm.
Step 2: If `num == 1`, return `1`.
Step 3: Initialize `pCount = 0` to count distinct prime factors.
Step 4: Store the original value of `num` in `originalNum`.
Step 5: Initialize `factorization` as an empty string to store the prime factorization.
Step 6: For `i = 2` to `√num`, do the following:
Step 7: If `num % i == 0`, do the following:
Step 8: Initialize `factorCount = 0` to count occurrences of the prime factor `i`.
Step 9: While `num % i == 0`, do the following:
Step 10: Divide `num` by `i`.
Step 11: Increment `factorCount` by `1`.
Step 12: If `factorization` is empty, set `factorization = i + " x "`.
Step 13: Else, append `i + " x "` to `factorization`.
Step 14: If `factorCount > 1`, remove the last " x " from `factorization`.
Step 15: Print `originalNum + " = " + factorization`.
Step 16: Print "DUPLICATE PRIME FACTORS".
Step 17: Return `0`.
Step 18: Increment `pCount` by `1`.
Step 19: If `num > 1`, do the following:
Step 20: If `factorization` is empty, set `factorization = num`.
Step 21: Else, append `num` to `factorization`.
Step 22: Increment `pCount` by `1`.
Step 23: Else, remove the last " x " from `factorization`.
Step 24: Calculate `mobiusValue = (pCount % 2 == 0) ? 1 : -1`.
Step 25: Print `originalNum + " = " + factorization`.
Step 26: Print "NUMBER OF DISTINCT PRIME FACTORS = " + pCount`.
Step 27: Return `mobiusValue`.
Step 28: End of algorithm.
main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize `Scanner sc`.
Step 3: Prompt the user to input `N`, store it in `N`.
Step 4: Print "OUTPUT:".
Step 5: If `N == 1`, do the following:
Step 6: Print "1 = 1".
Step 7: Print "NO PRIME FACTORS".
Step 8: Print "M(1) = 1".
Step 9: Else, call `mobius(N)` and store the result in `result`.
Step 10: Print "M(" + N + ") = " + result`.
Step 11: Close `Scanner sc`.
Step 12: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
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++;
}
}
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 3:
A Fascinating number is one which when multiplied by 2 and 3 and then, after the results are
concatenated with the original number, the new number contains all the digits from 1 to 9 exactly
once. There can be any number of zeroes and are to be ignored.
Example: 273
273 × 1 = 273
273 × 2 = 546
273 × 3 = 819
Concatenating the results we get, 273546819 which contains all digits from 1 to 9 exactly once.
Thus, 273 is a Fascinating number.
Accept two positive integers m and n, where m must be less than n and the values of both ‘m’
and ‘n’ must be greater than 99 and less than 10000 as user input. Display all Fascinating
numbers that are in the range between m and n (both inclusive) and output them along with the
frequency, in the format given below:
Test your program with the following data and some random data:
Example 1:
INPUT:
m = 100
n = 500
OUTPUT:
THE FASCINATING NUMBERS ARE:
192 219 273 327
FREQUENCY OF FASCINATING NUMBERS IS: 4
Example 2:
INPUT:
m = 900
n = 5000
OUTPUT:
THE FASCINATING NUMBERS ARE:
1902 1920 2019 2190 2703 2730 3027 3270
FREQUENCY OF FASCINATING NUMBERS IS: 8
Example 3:
INPUT:
m = 400
n = 900
OUTPUT:
THE FASCINATING NUMBERS ARE:
NIL
FREQUENCY OF FASCINATING NUMBERS IS: 0
Example 4:
INPUT:
m = 70
n = 450
OUTPUT:
INVALID INPUT
ALGORITHM:
isFasc():
STEP 1: Start of algorithm.
STEP 2: Initialize `n1` to `num`.
STEP 3: Initialize `n2` to `num * 2`.
STEP 4: Initialize `n3` to `num * 3`.
STEP 5: Concatenate `n1`, `n2`, and `n3` as strings and assign to `concat`.
STEP 6: Initialize a boolean array `digPres` of size 10 to `false`.
STEP 7: For each character `ch` in `concat`:
STEP 8: If `ch` is '0', continue to next character.
STEP 9: Convert `ch` to integer `dig`.
STEP 10: If `digPres[dig]` is `true`, return `false` (duplicate digit found).
STEP 11: Set `digPres[dig]` to `true`.
STEP 12: For integer `i` from 1 to 9:
STEP 13: If `digPres[i]` is `false`, return `false` (missing digit found).
STEP 14: Return `true` (all digits 1 to 9 present exactly once).
STEP 15: End of algorithm.
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nm = ".
STEP 4: Read integer input `m` from user.
STEP 5: Print "n = ".
STEP 6: Read integer input `n` from user.
STEP 7: If `m >= n` or `m < 100` or `n >= 10000`:
STEP 8: Print "INVALID INPUT".
STEP 9: Else:
STEP 10: Print "OUTPUT:".
STEP 11: Print "FASCINATING NUMBERS:".
STEP 12: Initialize `cnt` to 0.
STEP 13: For integer `i` from `m` to `n`:
STEP 14: If `isFasc(i)` returns `true`:
STEP 15: Print `i` followed by a space.
STEP 16: Increment `cnt` by 1.
STEP 17: If `cnt` is 0:
STEP 18: Print "NIL".
STEP 19: Else:
STEP 20: Print a newline.
STEP 21: Print "FREQUENCY OF FASCINATING NUMBERS IS: " followed by `cnt`.
STEP 22: Close the `Scanner` object `sc`.
STEP 23: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
// Check if the concatenated string contains all digits from 1 to 9 exactly once
boolean[] digPres = new boolean[10]; // Index 0 to 9
return true;
}
if (cnt == 0) {
System.out.println("NIL");
} else {
System.out.println();
}
sc.close();
}
}
OUTPUT:
Question 4:
Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows and
‘N’ is the number of columns such that the value of ‘M’ must be greater than 0 and less than 10
and the value of ‘N’ must be greater than 2 and less than 6. Allow the user to input digits (0 – 7)
only at each location, such that each row represents an octal number.
Example:
2 3 1 (decimal equivalent of 1st row = 153 i.e. 2 × 82 + 3 × 81 + 1 × 80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4 × 82 + 0 × 81 + 5 × 80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1 × 82 + 5 × 81 + 6 × 80)
Perform the following tasks on the matrix:
a) Display the original matrix.
b) Calculate the decimal equivalent for each row and display as per the format given below.
Test your program for the following data and some random data:
Example 1:
INPUT:
M=1
N=3
Enter elements for row 1: 1 4 4
OUTPUT:
Filled Matrix:
144
Decimal Equivalent:
100
Example 2:
INPUT:
M=3
N=4
Enter elements for row 1: 1 1 3 7
Enter elements for row 2: 2 1 0 6
Enter elements for row 3: 0 2 4 5
OUTPUT:
Filled Matrix:
1137
2106
0245
Decimal Equivalent:
607
1094
165
Example 3:
INPUT:
M=3
N=3
Enter elements for row 1: 2 4 8
OUTPUT:
Invalid Input.
Example 4:
INPUT:
M=4
N=6
OUTPUT:
Out of range.
ALGORITHM:
isValMSize():
STEP 1: Start of algorithm.
STEP 2: Return `true` if `m` is greater than 0 and less than 10, and `n` is greater than 2 and less
than 6.
STEP 3: Else return `false`.
STEP 4: End of algorithm.
isValOcDig():
STEP 1: Start of algorithm.
STEP 2: Return `true` if `digit` is greater than or equal to 0 and less than or equal to 7.
STEP 3: Else return `false`.
STEP 4: End of algorithm.
calcDeci():
STEP 1: Start of algorithm.
STEP 2: Initialize `deciVal` to 0.
STEP 3: Initialize `power` to the length of `octR` minus 1.
STEP 4: For each `digit` in `octR`:
STEP 5: Add `digit * Math.pow(8, power)` to `deciVal`.
STEP 6: Decrement `power` by 1.
STEP 7: Return `deciVal`.
STEP 8: End of algorithm.
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nM = ".
STEP 4: Read integer input `m` from user.
STEP 5: Print "N = ".
STEP 6: Read integer input `n` from user.
STEP 7: If `!isValMSize(m, n)`:
STEP 8: Print "Out of range.".
STEP 9: Close `Scanner` object `sc`.
STEP 10: Return from function.
STEP 11: Initialize a 2D array `matrix` of size `m` by `n`.
STEP 12: For integer `i` from 0 to `m - 1`:
STEP 13: Print "Enter elements for row " followed by `i + 1` and ": ".
STEP 14: For integer `j` from 0 to `n - 1`:
STEP 15: Read integer input `ele` from user.
STEP 16: If `!isValOcDig(ele)`:
STEP 17: Print "Invalid Input.".
STEP 18: Close `Scanner` object `sc`.
STEP 19: Return from function.
STEP 20: Set `matrix[i][j]` to `ele`.
STEP 21: Print "OUTPUT:\nFilled Matrix:".
STEP 22: For integer `i` from 0 to `m - 1`:
STEP 23: For integer `j` from 0 to `n - 1`:
STEP 24: Print `matrix[i][j]` followed by a space.
STEP 25: Print a newline.
STEP 26: Print "Decimal Equivalent:".
STEP 27: For integer `i` from 0 to `m - 1`:
STEP 28: Extract row `matrix[i]` into `row`.
STEP 29: Call `calcDeci(row)` and assign result to `deciEq`.
STEP 30: Print `deciEq`.
STEP 31: Close `Scanner` object `sc`.
STEP 32: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
return deciVal;
}
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 5:
Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user to
generate and display the corresponding date. Also, accept N (1 <= N <= 100) from the user to
compute and display the future date corresponding to ‘N’ days after the generated date. Display
an error message if the value of the day number, year and N are not within the limit or not
according to the condition specified.
Test your program with the following data and some random data:
Example 1:
INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2:
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019
Example 3:
INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33
OUTPUT:
DAY NUMBER OUT OF RANGE
Example 4:
INPUT:
DAY NUMBER: 150
YEAR: 2018
DATE AFTER (N DAYS): 330
OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE
ALGORITHM:
isLeap():
STEP 1: Start of algorithm.
STEP 2: Return `true` if `yr % 4 == 0` and `yr % 100 != 0`, or `yr % 400 == 0`.
STEP 3: Else return `false`.
STEP 4: End of algorithm.
genDate():
STEP 1: Start of algorithm.
STEP 2: If `day` is less than 1 or greater than `(isLeap(yr) ? 366 : 365)`, return `null` (invalid day
number).
STEP 3: Initialize `dArr` to `leapDays` if `isLeap(yr)` is `true`, otherwise `days`.
STEP 4: Initialize `mon` to 0.
STEP 5: While `day` is greater than `dArr[mon]`:
STEP 6: Subtract `dArr[mon]` from `day`.
STEP 7: Increment `mon` by 1.
STEP 8: Return `day + " " + getMon(mon) + ", " + yr`.
STEP 9: End of algorithm.
getMon():
STEP 1: Start of algorithm.
STEP 2: Initialize `mons` array with month names.
STEP 3: Return `mons[mon]`.
STEP 4: End of algorithm.
getSuf():
STEP 1: Start of algorithm.
STEP 2: If `n` is between 11 and 13 inclusive, return "TH".
STEP 3: Switch on `n % 10`:
STEP 4: If `n % 10` is 1, return "ST".
STEP 5: If `n % 10` is 2, return "ND".
STEP 6: If `n % 10` is 3, return "RD".
STEP 7: Else return "TH".
STEP 8: End of algorithm.
addDays():
STEP 1: Start of algorithm.
STEP 2: Initialize `dArr` to `leapDays` if `isLeap(yr)` is `true`, otherwise `days`.
STEP 3: Add `n` to `day`.
STEP 4: While `day` is greater than `(isLeap(yr) ? 366 : 365)`:
STEP 5: Subtract `(isLeap(yr) ? 366 : 365)` from `day`.
STEP 6: Increment `yr` by 1.
STEP 7: Initialize `mon` to 0.
STEP 8: While `day` is greater than `dArr[mon]`:
STEP 9: Subtract `dArr[mon]` from `day`.
STEP 10: Increment `mon` by 1.
STEP 11: Return `day + " " + getMon(mon) + ", " + yr`.
STEP 12: End of algorithm.
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "DAY NUMBER: ".
STEP 4: Read integer input `day` from user.
STEP 5: Print "YEAR: ".
STEP 6: Read integer input `yr` from user.
STEP 7: Print "DAYS AFTER (N DAYS): ".
STEP 8: Read integer input `n` from user.
STEP 9: If `n` is less than 1 or greater than 100:
STEP 10: Print "DATE NUMBER AFTER (N DAYS) OUT OF RANGE".
STEP 11: Close `Scanner` object `sc`.
STEP 12: Return from function.
STEP 13: Call `genDate(day, yr)` and assign result to `date`.
STEP 14: If `date` is `null`:
STEP 15: Print "DAY NUMBER OUT OF RANGE".
STEP 16: Close `Scanner` object `sc`.
STEP 17: Return from function.
STEP 18: Call `addDays(day, n, yr)` and assign result to `futDate`.
STEP 19: Split `futDate` by space into `prts`.
STEP 20: Parse the third part of `prts` into `futYr`.
STEP 21: Initialize `maxYr` to `yr + 100`.
STEP 22: If `futYr` is equal to `maxYr` and `day` is greater than `n`:
STEP 23: Print "DATE AFTER " + n + " OUT OF RANGE".
STEP 24: Close `Scanner` object `sc`.
STEP 25: Return from function.
STEP 26: Print "OUTPUT:".
STEP 27: Parse the day number from `date` and store in `dayNum`.
STEP 28: Print "DATE: " + `dayNum` + `getSuf(dayNum)` + " " + `date.substring(03)`.
STEP 29: Parse the future day number from `futDate` and store in `futDayNum`.
STEP 30: Print "DATE AFTER " + n + " DAYS: " + `futDayNum` + `getSuf(futDayNum)` + " "
+ `futDate.substring(02)`.
STEP 31: Close `Scanner` object `sc`.
STEP 32: End of algorithm
.
SOURCE CODE:
import java.util.Scanner;
int mon = 0;
while (day > dArr[mon]) {
day -= dArr[mon];
mon++;
}
return day+ " " + getMon(mon) + ", " + yr;
}
System.out.print("YEAR: ");
int yr = sc.nextInt();
System.out.println("OUTPUT:");
int dayNum = Integer.parseInt(date.split(" ")[0]);
System.out.println("DATE: " + dayNum + getSuf(dayNum) + " " + date.substring(03));
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
days int[] Array of days in each month for non-leap years. Class level
leapDays int[] Array of days in each month for leap years. Class level
futDate String The future date string after adding n days. addDays,
main
methods
prts String[] Array of date parts split from futDate. main method
maxYr int Maximum year considered for range validation. main method
dayNum int Day number extracted from date for output. main method
futDayNum int Day number extracted from futDate for output. main method
OUTPUT:
Question 6:
Write a program to declare a single-dimensional array a[] and a square matrix b[][] of size N,
where N > 2 and N < 10. Allow the user to input positive integers into the single dimensional
array.
Perform the following tasks on the matrix:
a) Sort the elements of the single-dimensional array in ascending order using any standard
sorting technique and display the sorted elements.
b) Fill the square matrix b[][] in the following format.
If the array a[] = {5, 2, 8, 1} then, after sorting a[] = {1, 2, 5, 8}
Then, the matrix b[][] would fill as below:
1 2 5 8
1 2 5 1
1 2 1 2
1 1 2 5
c) Display the filled matrix in the above format.
Test your program for the following data and some random data:
Example 1:
INPUT:
N=3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT:
SORTED ARRAY: 1 3 7
FILLED MATRIX
1 3 7
1 3 1
1 1 3
Example 2:
INPUT:
N = 13
OUTPUT:
MATRIX SIZE OUT OF RANGE
ALGORITHM:
sortArray(int[] array)
STEP 1: Start of algorithm.
STEP 2: Use the Arrays.sort() method to sort the array in ascending order.
STEP 3: End of algorithm.
displayMatrix(int[][] matrix)
STEP 1: Start of algorithm.
STEP 2: For each row in the matrix:
STEP 2.1: For each element in the row:
STEP 2.1.1: Print the element followed by a space.
STEP 2.2: Print a newline character after printing all elements of the row.
STEP 3: End of algorithm.
SOURCE CODE:
import java.util.Arrays;
import java.util.Scanner;
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
array int[] Single-dimensional array of integers to be sorted. Parameter in
sortArray
method
matrix int[][] 2D square matrix to be filled. Parameter in
fillMatrix
method and
displayMatri
x method
sortedArray int[] Sorted single-dimensional array used to fill the matrix. Parameter in
fillMatrix
method
N int Size of the square matrix (number of rows and columns). Local variable
in fillMatrix
method
i int Row index used for iterating through the matrix. Local variable
in fillMatrix
method
j int Column index used for iterating through the matrix. Local variable
in fillMatrix
method
day int Day number for generating dates and calculating future dates. Parameter in
genDate and
addDays
methods, and
in main
method
yr int Year for generating dates and calculating future dates. Parameter in
genDate,
addDays
methods, and
in main
method
sortedArray int[] Sorted array used to fill the matrix in a specific format. Parameter in
fillMatrix
method
date String Formatted date string generated from the day number and Local variable
year. in main
method
futDate String Formatted future date string after adding days. Local variable
in main
method
prts String[] Array of strings obtained by splitting futDate. Local variable
in main
method
futYr int Year component of the future date. Local variable
in main
method
maxYr int Maximum year limit for date calculation. Local variable
in main
method
dayNum int Day number extracted from the date string. Local variable
in main
method
futDayNum int Future day number extracted from the futDate string. Local variable
in main
method
OUTPUT:
Question 7:
A Goldbach number is a positive even integer that can be expressed as the sum of two odd
primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example:
6=3+3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs, i.e. 3, 7 and 5, 5.
Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all the odd prime
pairs whose sum is equal to the number ‘N’.
Test your program with the following data and some random data:
Example 1:
INPUT:
N = 14
OUTPUT:
Prime pairs are:
3, 11
7, 7
Example 2:
INPUT:
N = 30
OUTPUT:
Prime numbers are:
7, 23
11, 19
13, 17
Example 3:
INPUT:
N = 17
OUTPUT:
Invalid input. Number is odd.
Example 4:
INPUT:
N = 126
OUTPUT:
Invalid input. Number is out of range
.
ALGORITHM:
isPrime():
STEP 1: Start of algorithm.
STEP 2: If `num` is less than or equal to 1, return `false`.
STEP 3: For integer `i` from 2 to `sqrt(num)`:
STEP 4: If `num % i` is 0, return `false` (not a prime).
STEP 5: Return `true` (is a prime).
STEP 6: End of algorithm.
findPrimePairs():
STEP 1: Start of algorithm.
STEP 2: Print "Prime pairs are:".
STEP 3: For integer `i` from 3 to `N / 2`, increment by 2:
STEP 4: If `isPrime(i)` and `isPrime(N - i)`:
STEP 5: Print `i` and `N - i` as a pair.
STEP 6: End of algorithm.
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: If `N` is odd or `N` is less than 10 or greater than 50:
STEP 6: Print "OUTPUT:\nInvalid input. Number is " followed by "out of range." if `N` is even,
or "odd." if `N` is odd.
STEP 7: Else call `findPrimePairs(N)`.
STEP 8: Close `Scanner` object `sc`.
STEP 9: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
num int The integer value to check if it's prime. Parameter in
isPrime
method
i int Loop variable used for checking divisors of num. Local variable
in isPrime
method
N int The integer input number to find prime pairs for. Parameter in
findPrimePai
rs method
and local
variable in
main method
OUTPUT:
Question 8:
The names of the teams participating in a competition should be displayed on a banner vertically,
to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display them in vertical
order, side by side with a horizontal tab (i.e. eight spaces).
Test your program for the following data and some random data:
Example 1:
INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote
OUTPUT:
E R C
m o o
u a y
s d o
t
R e
o
l
s
Example 2:
INPUT:
N=4
Team 1: Royal
Team 2: Mars
Team 3: De Rose
Team 4: Kings
OUTPUT:
R M D K
o a e i
y r n
a s R g
l o s
s
e
Example 3:
INPUT:
N = 10
OUTPUT:
Invalid input.
ALGORITHM:
displayTeams():
STEP 1: Start of algorithm.
STEP 2: Initialize `maxLength` to 0.
STEP 3: For integer `i` from 0 to `numTeams - 1`:
STEP 4: If `teams[i].length()` is greater than `maxLength`:
STEP 5: Set `maxLength` to `teams[i].length()`.
STEP 6: For integer `i` from 0 to `maxLength - 1`:
STEP 7: For integer `j` from 0 to `numTeams - 1`:
STEP 8: If `i` is less than `teams[j].length()`:
STEP 9: Print `teams[j].charAt(i)` followed by two tabs.
STEP 10: Else print two tabs.
STEP 11: Print a newline.
STEP 12: End of algorithm.
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: Consume newline character.
STEP 6: If `N` is less than or equal to 2 or greater than or equal to 9:
STEP 7: Print "OUTPUT:\nInvalid input."
STEP 8: Close `Scanner` object `sc`.
STEP 9: Return from function.
STEP 10: Initialize a `String` array `teams` of size `N`.
STEP 11: For integer `i` from 0 to `N - 1`:
STEP 12: Print "Team " followed by `i + 1` and ": ".
STEP 13: Read a `String` input from user and store in `teams[i]`.
STEP 14: Print "OUTPUT:".
STEP 15: Call `displayTeams(teams, N)`.
STEP 16: Close `Scanner` object `sc`.
STEP 17: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.nextLine(); // Consume newline
if (N <= 2 || N >= 9) {
System.out.println("OUTPUT:\nInvalid input.");
} else {
String[] teams = new String[N];
for (int i = 0; i < N; i++) {
System.out.print("Team " + (i + 1) + ": ");
teams[i] = sc.nextLine();
}
System.out.println("OUTPUT:");
displayTeams(teams, N);
}
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
Variable Data Description Scope
Name Type
teams String[] Array of team names. Parameter in displayTeams
method and local variable in
main method
numTeams int Number of teams (length of the Parameter in displayTeams
teams array). method and local variable in
main method
maxLength int Maximum length of team Local variable in displayTeams
names in the teams array. method
i int Loop variable used to iterate Local variable in displayTeams
over the rows of characters to method
display.
j int Loop variable used to iterate Local variable in displayTeams
over the team names. method
N int Number of teams entered by Local variable in main method
the user.
sc Scanner Scanner object used to read Local variable in main method
user input.
teams[i] String Team name at index i in the Local variable in main method
teams array.
OUTPUT:
Question 9:
A company manufactures packing cartons in four sizes, i.e. cartons to accomodate 6 boxes, 12
boxes, 24 boxes and 48 boxes. Design a program to accept the number of boxes to be packed (N)
by the user (maximum up to 1000 boxes) and display the break-up of the cartons used in
descending order of capacity (i.e. preference should be given to the highest capacity available,
and if boxes left are less than 6, an extra carton of capacity 6 should be used.)
Test your program with the following data and some random data:
Example 1:
INPUT:
N = 726
OUTPUT:
48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Example 2:
INPUT:
N = 140
OUTPUT:
48 * 2 = 96
24 * 1 = 24
12 * 1 = 12
6*1=6
Remaining boxes = 2 * 1 = 2
Total number of boxes = 140
Total number of cartons = 6
Example 3:
INPUT:
N = 4296
OUTPUT:
INVALID INPUT
ALGORITHM:
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: Consume newline character.
STEP 6: If `N` is less than 0 or greater than 1000:
STEP 7: Print "OUTPUT:\nINVALID INPUT".
STEP 8: Close `Scanner` object `sc`.
STEP 9: Return from function.
STEP 10: Calculate `cartons48` as `N / 48`.
STEP 11: Calculate `cartons24` as `(N % 48) / 24`.
STEP 12: Calculate `cartons12` as `((N % 48) % 24) / 12`.
STEP 13: Calculate `cartons6` as `(((N % 48) % 24) % 12) / 6`.
STEP 14: Calculate `remainingBoxes` as `(((N % 48) % 24) % 12) % 6`.
STEP 15: Calculate `totalCartons` as `cartons48 + cartons24 + cartons12 + cartons6`.
STEP 16: If `remainingBoxes` is greater than 0:
STEP 17: Increment `cartons6` by 1.
STEP 18: Increment `totalCartons` by 1.
STEP 19: Print "OUTPUT:".
STEP 20: Print "48 * " + `cartons48` + " = " + `(cartons48 * 48)` if `cartons48` is not 0.
STEP 21: Print "24 * " + `cartons24` + " = " + `(cartons24 * 24)` if `cartons24` is not 0.
STEP 22: Print "12 * " + `cartons12` + " = " + `(cartons12 * 12)` if `cartons12` is not 0.
STEP 23: Print "6 * " + `cartons6` + " = " + `(cartons6 * 6)` if `cartons6` is not 0.
STEP 24: If `remainingBoxes` is greater than 0:
STEP 25: Print "Remaining boxes = " + `remainingBoxes` + " * 1 = " + `remainingBoxes`.
STEP 26: Else if `remainingBoxes` is 0:
STEP 27: Print "Remaining boxes = 0".
STEP 28: Else print "Remaining boxes do not exist!".
STEP 29: Print "Total number of boxes = " + `N`.
STEP 30: Print "Total number of cartons = " + `totalCartons`.
STEP 31: Close `Scanner` object `sc`.
STEP 32: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.nextLine(); // Consume newline
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();
}
}
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:\nN = ".
STEP 4: Read integer input `N` from user.
STEP 5: Consume newline character.
STEP 6: If `N` is less than or equal to 3 or greater than or equal to 11:
STEP 7: Print "OUTPUT:\nINPUT SIZE OUT OF RANGE."
STEP 8: Close `Scanner` object `sc`.
STEP 9: Return from function.
STEP 10: Initialize a `String` 2D array `answers` with dimensions `N` x 5.
STEP 11: Print "Enter participant's answers:".
STEP 12: For integer `i` from 0 to `N - 1`:
STEP 13: Print "Participant " followed by `i + 1` and " ".
STEP 14: Read a `String` input from user, trim it, and split it into parts, then store in
`answers[i]`.
STEP 15: Print "Key: ".
STEP 16: Read a `String` input from user, trim it, and split it into parts, then store in `key`.
STEP 17: Call `calculateScores(answers, key)` and store the result in `scores`.
STEP 18: Call `displayScores(scores)`.
STEP 19: Close `Scanner` object `sc`.
STEP 20: End of algorithm.
calculateScores():
STEP 1: Start of algorithm.
STEP 2: Initialize an `int` array `scores` with size equal to the number of participants.
STEP 3: For integer `i` from 0 to `answers.length - 1`:
STEP 4: For integer `j` from 0 to `answers[i].length - 1`:
STEP 5: If `answers[i][j]` equals `key[j]`:
STEP 6: Increment `scores[i]` by 1.
STEP 7: Return `scores`.
STEP 8: End of algorithm.
displayScores():
STEP 1: Start of algorithm.
STEP 2: Print "OUTPUT:\nScores:".
STEP 3: For integer `i` from 0 to `scores.length - 1`:
STEP 4: Print "Participant " followed by `i + 1` and " = " followed by `scores[i]`.
STEP 5: Initialize `maxScore` to 0.
STEP 6: For each `score` in `scores`:
STEP 7: If `score` is greater than `maxScore`:
STEP 8: Set `maxScore` to `score`.
STEP 9: Print "Highest score:".
STEP 10: For integer `i` from 0 to `scores.length - 1`:
STEP 11: If `scores[i]` equals `maxScore`:
STEP 12: Print "Participant " followed by `i + 1`.
STEP 13: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
public class QuizCompetition {
System.out.print("INPUT:\nN = ");
int N = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Key: ");
String[] key = sc.nextLine().trim().split("\\s+");
sc.close();
}
int maxScore = 0;
for (int score : scores) {
if (score > maxScore) {
maxScore = score;
}
}
System.out.println("Highest score:");
for (int i = 0; i < scores.length; i++) {
if (scores[i] == maxScore) {
System.out.println("Participant " + (i + 1));
}
}
}
}
VARIABLE DESCRIPTION TABLE:
Variable Name Data Description Scope
Type
N int Number of participants in the quiz competition. Local variable in
main method
answers String[] 2D array holding the answers of each participant. Local variable in
[] main method
key String[] Array holding the correct answers for the quiz. Local variable in
main method
scores int[] Array holding the score of each participant based on correct Local variable in
answers. calculateScor
es method
i int Loop variable used to iterate over participants and answers. Local variable in
main,
calculateScor
es, and
displayScores
methods
j int Loop variable used to iterate over answers for each Local variable in
participant. calculateScor
es method
maxScore int The highest score among all participants. Local variable in
displayScores
method
OUTPUT:
Question 11:
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `scanner`.
STEP 3: Print "INPUT:".
STEP 4: Print "Enter the plain text: ".
STEP 5: Read `plainText` input from user.
STEP 6: If the length of `plainText` is less than or equal to 3 or greater than or equal to 100:
STEP 7: Print "OUTPUT:\nINVALID LENGTH".
STEP 8: Close `Scanner` object `scanner`.
STEP 9: Return from function.
STEP 10: Call `encrypt(plainText)` and store the result in `cipherText`.
STEP 11: Print "OUTPUT:\nThe cipher text is:\n" followed by `cipherText`.
STEP 12: Close `Scanner` object `scanner`.
STEP 13: End of algorithm.
encrypt():
STEP 1: Start of algorithm.
STEP 2: Initialize a `StringBuilder` object `cipherText`.
STEP 3: For integer `i` from 0 to `plainText.length() - 1`:
STEP 4: Get character `ch` from `plainText` at index `i`.
STEP 5: If `ch` is a letter:
STEP 6: Determine `base` as 'A' if `ch` is uppercase, else 'a'.
STEP 7: Update `ch` as `(((ch - base + 13) % 26) + base)`.
STEP 8: Append `ch` to `cipherText`.
STEP 9: Return `cipherText.toString()`.
STEP 10: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.println("INPUT:");
System.out.print("Enter the plain text: ");
String plainText = scanner.nextLine();
scanner.close();
}
if (Character.isLetter(ch)) {
char base = Character.isUpperCase(ch) ? 'A' : 'a';
ch = (char) (((ch - base + 13) % 26) + base);
}
cipherText.append(ch);
}
return cipherText.toString();
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 12:
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than
100. Find the smallest integer that is greater than M and whose digits add up to N. For example,
if M = 100 and N = 11, then the smallest integer greater than 100 whose digits add up to 11 is
119.
Write a program to accept the numbers M and N from the user and print the smallest required
number whose sum of all its digits is equal to N. Also, print the total number of digits present in
the required number. The program should check for the validity of the inputs and display an
appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1:
INPUT:
M = 100
N = 11
OUTPUT:
The required number = 119
Total number of digits = 3
Example 2:
INPUT:
M = 1500
N = 25
OUTPUT:
The required number = 1699
Total number of digits = 4
Example 3:
INPUT:
M = 99
N = 11
OUTPUT:
INVALID INPUT
Example 4:
INPUT:
M = 112
N = 130
OUTPUT:
INVALID INPUT
ALGORITHM:
main():
STEP 1: Start of algorithm.
STEP 2: Create a `Scanner` object `sc`.
STEP 3: Print "INPUT:".
STEP 4: Print "M = ".
STEP 5: Read integer `M` from user input.
STEP 6: Print "N = ".
STEP 7: Read integer `N` from user input.
STEP 8: If `M` is less than 100 or greater than 10000, or `N` is greater than or equal to 100:
STEP 9: Print "OUTPUT:\nINVALID INPUT".
STEP 10: Close `Scanner` object `sc`.
STEP 11: Return from function.
STEP 12: Call **findSmallestNumber(M, N)** and store the result in `smallestNumber`.
STEP 13: Call **countDigits(smallestNumber)** and store the result in `totalDigits`.
STEP 14: Print "OUTPUT:".
STEP 15: Print "The required number = " followed by `smallestNumber`.
STEP 16: Print "Total number of digits = " followed by `totalDigits`.
STEP 17: Close `Scanner` object `sc`.
STEP 18: End of algorithm.
sumOfDigits(int number):
STEP 1: Start of algorithm.
STEP 2: Initialize `sum` to 0.
STEP 3: While `number` is greater than 0:
STEP 4: Add `number % 10` to `sum`.
STEP 5: Update `number` to `number / 10`.
STEP 6: Return `sum`.
STEP 7: End of algorithm.
countDigits(int number):
STEP 1: Start of algorithm.
STEP 2: Initialize `count` to 0.
STEP 3: While `number` is greater than 0:
STEP 4: Increment `count` by 1.
STEP 5: Update `number` to `number / 10`.
STEP 6: Return `count`.
STEP 7: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.println("INPUT:");
System.out.print("M = ");
int M = sc.nextInt();
System.out.print("N = ");
int N = sc.nextInt();
System.out.println("OUTPUT:");
System.out.println("The required number = " + smallestNumber);
System.out.println("Total number of digits = " + totalDigits);
}
sc.close();
}
M int The lower bound for finding the smallest integer. Local variable in
main method
N int The target sum of digits for the smallest integer. Local variable in
main method
smallestNum int The smallest integer greater than M whose sum of digits Local variable in
ber equals N. main method,
return value of
findSmallestNum
ber method
i int Loop variable used to find the smallest number whose Local variable in
sum of digits equals N. findSmallestNum
ber method
number int The current number being processed to find the sum of Local variable in
digits. sumOfDigits and
countDigits
methods
sum int The sum of the digits of number. Local variable in
sumOfDigits
method
count int The count of digits in number. Local variable in
countDigits
method
OUTPUT:
Question 13:
A composite magic number is a positive integer which is composite as well as a magic number.
Composite number: A composite number is a number that has more than two factors.
For example: 10
Factors are: 1, 2, 5, 10.
Magic number: A magic number is a number in which the eventual sum of the digits is equal to
1.
For example: 28
2 + 8 = 10.
1 + 0 = 1.
Accept two positive integers ‘m’ and ‘n’, where m is less than n as user input. Display the
number of composite magic integers that are in the range between ‘m’ and ‘n’ (both inclusive)
and output them along with the frequency, in the format specified below.
Test your program with the sample data and some random data:
Example 1:
INPUT:
m = 10
n = 100
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2:
INPUT:
m = 1200
n = 1300
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
1207, 1216, 1225, 1234, 1243, 1252, 1261, 1270, 1288
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9
Example 3:
INPUT:
m = 120
n = 99
OUTPUT:
INVALID INPUT
ALGORITHM:
main():
STEP 1: Start of algorithm.
STEP 2: Create a Scanner object sc.
STEP 3: Print "INPUT:".
STEP 4: Print "m = ".
STEP 5: Read integer m from user input.
STEP 6: Print "n = ".
STEP 7: Read integer n from user input.
STEP 8: If m is greater than or equal to n:
STEP 9: Print "OUTPUT:\nINVALID INPUT".
STEP 10: Close Scanner object sc.
STEP 11: Return from function.
STEP 12: Print "OUTPUT:".
STEP 13: Print "THE COMPOSITE MAGIC INTEGERS ARE:".
STEP 14: Call printCompositeMagicNumbers(m, n) and store the result in count.
STEP 15: Print "FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: " followed by count.
STEP 16: End of algorithm.
isComposite(int number):
STEP 1: Start of algorithm.
STEP 2: If number is less than or equal to 1:
STEP 3: Return false.
STEP 4: For integer i from 2 to the square root of number:
STEP 5: If number is divisible by i:
STEP 6: Return true.
STEP 7: Return false.
STEP 8: End of algorithm.
isMagicNumber(int number):
STEP 1: Start of algorithm.
STEP 2: While number is greater than 9:
STEP 3: Initialize sum to 0.
STEP 4: While number is greater than 0:
STEP 5: Add number % 10 to sum.
STEP 6: Update number to number / 10.
STEP 7: Update number to sum.
STEP 8: Return number equals 1.
STEP 9: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
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();
}
m int The lower bound of the range to check for Local variable in main
composite magic numbers. method
n int The upper bound of the range to check for Local variable in main
composite magic numbers. method
count int The count of composite magic numbers found in Local variable in
the range. printCompositeMagicNum
bers method
i int Loop variable used to iterate through numbers in Local variable in
the range [m, n]. printCompositeMagicNum
bers method
OUTPUT:
Question 14:
A prime palindrome integer is a positive integer (without leading zeroes) which is prime as well
as a palindrome. Given two positive integers m and n, where m < n, write a program to
determine how many prime palindrome integers are there in the range between m and n (both
inclusive) and output them.
The input contains two positive integers m and n where m < 3000 and n < 3000. Display the
number of prime palindrome integers in the specified range along with their values in the format
specified below:
Test your program with the sample data and some random data:
Example 1:
INPUT:
m = 100
n = 1000
OUTPUT:
THE PRIME PALINDROME INTEGERS ARE:
101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 919, 929
FREQUENCY OF PRIME PALINDROME INTEGERS: 15
Example 2:
INPUT:
m = 100
n = 5000
OUTPUT:
OUT OF RANGE.
ALGORITHM:
main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize Scanner sc.
Step 3: Print "INPUT:".
Step 4: Prompt the user to input m, store it in m.
Step 5: Prompt the user to input n, store it in n.
Step 6: If m >= 3000 or n >= 3000, do the following:
Step 7: Print "OUTPUT:\nOUT OF RANGE.".
Step 8: Else, do the following:
Step 9: Print "OUTPUT:".
Step 10: Print "THE PRIME PALINDROME INTEGERS ARE:".
Step 11: Initialize freq = 0 and first = true.
Step 12: For i = m to n, do the following:
Step 13: If isPrime(i) and isPalin(i), do the following:
Step 14: If first is false, print ", ".
Step 15: Print i.
Step 16: Increment freq by 1.
Step 17: Set first to false.
Step 18: If freq == 0, print "NIL".
Step 19: Else, print a newline.
Step 20: Print "FREQUENCY OF PRIME PALINDROME INTEGERS: " + freq.
Step 21: Close Scanner sc.
Step 22: End of algorithm.
isPrime(int num):
Step 1: Start of algorithm.
Step 2: If num <= 1, return false.
Step 3: For i = 2 to √num, do the following:
Step 4: If num % i == 0, return false.
Step 5: Return true.
Step 6: End of algorithm.
isPalin(int num):
Step 1: Start of algorithm.
Step 2: Initialize rev = 0 and orig = num.
Step 3: While orig != 0, do the following:
Step 4: Set dig = orig % 10.
Step 5: Update rev = rev * 10 + dig.
Step 6: Update orig /= 10.
Step 7: Return num == rev.
Step 8: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.println("INPUT:");
System.out.print("m = ");
int m = sc.nextInt();
System.out.print("n = ");
int n = sc.nextInt();
int freq = 0;
boolean first = true;
if (freq == 0) {
System.out.println("NIL");
} else {
System.out.println();
}
sc.close();
}
private static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
while (orig != 0) {
int dig = orig % 10;
rev = rev * 10 + dig;
orig /= 10;
}
OUTPUT:
Question 15:
Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows and
‘N’ is the number of columns such that both M and N must be greater than 2 and less than 20.
Allow the user to input integers into this matrix. Perform the following tasks on the matrix:
Display the input matrix.
Find the maximum and minimum value in the matrix and display them along with their position.
Sort the elements of the matrix in ascending order using any standard sorting technique and
rearrange them in the matrix.
Output the rearranged matrix.
Test your program with the sample data and some random data.
Example 1:
INPUT:
M=3
N=4
8 7 9 3
-2 0 4 5
1 3 6 -1
OUTPUT:
ORIGINAL MATRIX:
8 7 9 3
-2 0 4 5
1 3 6 -1
LARGEST NUMBER: 9
ROW = 0
COLUMN = 3
REARRANGED MATRIX:
-4 -2 0 1
3 3 4 5
6 7 8 9
Example 2:
INPUT:
M=3
N = 22
OUTPUT:
SIZE OUT OF RANGE
ALGORITHM:
main()
STEP 1: Start of algorithm.
STEP 2: Create a Scanner object sc.
STEP 3: Print "INPUT:\nM = ".
STEP 4: Read integer input M from user.
STEP 5: Print "N = ".
STEP 6: Read integer input N from user.
STEP 7: If M is less than or equal to 2, or M is greater than or equal to 20, or N is less than or
equal to 2, or N is greater than or equal to 20:
STEP 8: Print "OUTPUT:\nSIZE OUT OF RANGE".
STEP 9: Close Scanner object sc.
STEP 10: Return from function.
STEP 11: Create a 2D matrix matrix of size M by N.
STEP 12: Print "Enter the elements of the matrix:".
STEP 13: For each element in matrix, read the integer input from user.
STEP 14: Print "OUTPUT:".
STEP 15: Print "ORIGINAL MATRIX:".
STEP 16: Call printMatrix(matrix).
STEP 17: Create a 1D array flattenedMatrix to store matrix elements.
STEP 18: Flatten matrix into flattenedMatrix.
STEP 19: Find maximum value in flattenedMatrix and store in max.
STEP 20: Find minimum value in flattenedMatrix and store in min.
STEP 21: Find position of max in flattenedMatrix and store in maxPos.
STEP 22: Find position of min in flattenedMatrix and store in minPos.
STEP 23: Print "LARGEST NUMBER: " followed by max.
STEP 24: Print "ROW = " followed by row index of max in matrix.
STEP 25: Print "COLUMN = " followed by column index of max in matrix.
STEP 26: Print "SMALLEST NUMBER: " followed by min.
STEP 27: Print "ROW = " followed by row index of min in matrix.
STEP 28: Print "COLUMN = " followed by column index of min in matrix.
STEP 29: Sort flattenedMatrix.
STEP 30: Create a 2D matrix sortedMatrix to store sorted elements.
STEP 31: Rearrange sorted elements from flattenedMatrix into sortedMatrix.
STEP 32: Print "REARRANGED MATRIX:".
STEP 33: Call printMatrix(sortedMatrix).
STEP 34: Close Scanner object sc.
STEP 35: End of algorithm.
printMatrix(int[][] matrix)
STEP 1: Start of algorithm.
STEP 2: For each row in matrix:
STEP 3: For each value in the row:
STEP 4: Print the value followed by a space.
STEP 5: Print a new line.
STEP 6: End of algorithm.
SOURCE CODE:
import java.util.Arrays;
import java.util.Scanner;
System.out.print("INPUT:\nM = ");
int M = sc.nextInt();
System.out.print("N = ");
int N = sc.nextInt();
System.out.println("OUTPUT:");
System.out.println("ORIGINAL MATRIX:");
printMatrix(matrix);
// 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();
}
OUTPUT:
Question 16:
Write a program to input a natural number less than 1000 and display it in words.
Test your program for the given sample data and some random data.
INPUT: 29
OUTPUT: TWENTY NINE
INPUT: 17001
OUTPUT: OUT OF RANGE
INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN
INPUT: 500
OUTPUT: FIVE HUNDRED
ALGORITHM:
main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize `Scanner sc`.
Step 3: Print "INPUT: ".
Step 4: Prompt the user to input `n`, store it in `n`.
Step 5: If `isValid(n)` returns `true`, do the following:
Step 6: Print "OUTPUT: ".
Step 7: Print the result of `convertToWords(n)`.
Step 8: Else, print "OUTPUT: OUT OF RANGE".
Step 9: Close `Scanner sc`.
Step 10: End of algorithm.
isValid(int n):
Step 1: Start of algorithm.
Step 2: Return `true` if `n > 0` and `n < 1000`.
Step 3: Else, return `false`.
Step 4: End of algorithm.
convertToWords(int n):
Step 1: Start of algorithm.
Step 2: Initialize arrays `u` and `t` for unit and ten values respectively.
Step 3: If `n == 0`, return "ZERO".
Step 4: If `n < 20`, return the corresponding value from `u[n]`.
Step 5: If `n < 100`, return the combination of `t[n / 10]` and `u[n % 10]`.
Step 6: Return the combination of `u[n / 100]`, "HUNDRED", and the result of
`convertToWords(n % 100)` if `n % 100 != 0`.
Step 7: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
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();
}
if (n == 0) {
return "ZERO";
}
if (n < 20) {
return u[n];
}
if (n < 100) {
return t[n / 10] + " " + u[n % 10];
}
return u[n / 100] + " HUNDRED" + (n % 100 != 0 ? " AND " + convertToWords(n % 100) :
"");
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 17:
ALGORITHM:
main(String[] args):
Step 1: Start of algorithm.
Step 2: Initialize `Scanner sc`.
Step 3: Print "INPUT N: ".
Step 4: Prompt the user to input `n`, store it in `n`.
Step 5: If `n >= 50`, print "N MUST BE LESS THAN 50." and close `Scanner sc`.
Step 6: Return from the function.
Step 7: Initialize an array `arr` of size `n`.
Step 8: Fill `arr` with values from 1 to `n`.
Step 9: Initialize `step` to 2.
Step 10: Enter a `while` loop that continues indefinitely.
Step 11: Initialize `len` to 0.
Step 12: Iterate over `arr` and copy elements that are not removed to a new position in `arr`,
updating `len`.
Step 13: If `len` equals `n`, break the loop.
Step 14: Update `n` to `len`.
Step 15: Increment `step` by 1.
Step 16: Print the lucky numbers less than 10 if `arr[0] < 10`, otherwise print less than 25.
Step 17: Print the elements of `arr` from index 0 to `n-1`.
Step 18: Close `Scanner sc`.
Step 19: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
System.out.print("INPUT N: ");
int n = sc.nextInt();
while (true) {
int len = 0; // Length of the new array after removing numbers
sc.close();
}
}
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 18:
Read in an integer n (which can be at most 50). Then read in n integers one by one and store
them in an array data from index 0 to n-1. Now we want to rearrange the integers in data in the
following way :
Find the maximum value in data and put in the centre of the array (that is at (n/2);
find the next largest value and put it to its right; then the next largest and place it to its left and so
on alternating right and left until all integers in data are done. For example, if the array is
initially:
7, 3, 1, 6, 4, 2, 5 then after rearranging it becomes 1, 3, 5, 7, 6, 4, 2. However, since we have very
little memory, you are not allowed to use any other array from data.
Sample data:
Input:
Give the number of integers: 5
Give integer 1 : 7
Give integer 2 : 9
Give integer 3 : 2
Give integer 4 : 5
Give integer 5 : 6
Output:
Original array
79256
rearranged array
26975
Input:
Give the number of integers: 6
Give integer 1 : 5
Give integer 2 : 1
Give integer 3 : 9
Give integer 4 : 8
Give integer 5 : 2
Give integer 6 : 4
Output:
Original array
519824
rearranged array
259841
ALGORITHM:
main()
STEP 1: Start of algorithm.
STEP 2: Create a Scanner object sc to read user input.
STEP 3: Print "Give the number of integers: " and read integer input n from the user.
STEP 4: If n is greater than 50:
STEP 4.1: Print "Input exceeds limit of 50."
STEP 4.2: Close the Scanner object sc.
STEP 4.3: Return from function.
STEP 5: Initialize an integer array data of size n.
STEP 6: For each index i from 0 to n-1:
STEP 6.1: Print "Give integer " + (i + 1) + ": " and read integer input into data[i].
STEP 7: Print "Original array" and display the elements of the array data from index 0 to n-1.
STEP 8: Sort the array data in descending order.
STEP 9: Initialize an integer array result of size n.
STEP 10: Initialize left to 0 and right to n-1.
STEP 11: For each index i from 0 to n-1:
STEP 11.1: If i is even, place the i-th largest element of data at index left of result and increment
left by 1.
STEP 11.2: If i is odd, place the i-th largest element of data at index right of result and decrement
right by 1.
STEP 12: Print "Rearranged array" and display the elements of the array result from index 0 to n-
1.
STEP 13: Close the Scanner object sc.
STEP 14: End of algorithm.
SOURCE CODE:
import java.util.Arrays;
import java.util.Scanner;
// 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;
}
OUTPUT:
Question 19:
Write a program to declare a square matrix A [ ] [ ]of order N (N < 20). Allow the user to input
positive integers in to this matrix. Perform the following task on the matrix:
(i) Output the original matrix.
(ii) Fins the SADDLE POINT for the matrix such that is the minimum element for the row to
which it belongs and the maximum element for the column to which it belongs. Saddle point for
a given matrix is always unique. If the matrix has no saddle point, output the message “ NO
SADDLE POINT ”.
Test your program for the following data and some random data :
SAMPLE DATA :
INPUT : N = 4
MATRIX A [ ] [ ] =
2569
8 4 12 3
6731
12 24 2 11
OUTPUT :
2569
8 4 12 3
6731
12 24 2 11
NO SADDLE POINT
MATRIX AFTER SORTING THE PRINCIPAL DIAGONAL
2569
8 4 12 3
6731
12 24 2 11
INPUT : N = 3
MATRIX A [ ] [ ] =
4 16 12
2 6 14
138
OUTPUT :
4 16 12
2 6 14
138
SADDLE POINT = 4
MATRIX AFTER SORTING THE PRINCIPAL DIAGONAL
4 16 12
2 6 14
138
ALGORITHM:
main(String[] args):
Step 1: Initialize `Scanner sc`.
Step 2: Print "Enter the order of the matrix N (N < 20):".
Step 3: Prompt the user to input `n`, store it in `n`.
Step 4: Create a 2D array `mat` of size `n x n`.
Step 5: Print "Enter the elements of the matrix:".
Step 6: Iterate over `i` from 0 to `n-1`.
Step 7: Iterate over `j` from 0 to `n-1`.
Step 8: Input matrix element at `mat[i][j]`.
Step 9: Print "Original Matrix:".
Step 10: Iterate over `i` from 0 to `n-1`.
Step 11: Iterate over `j` from 0 to `n-1`.
Step 12: Print matrix element `mat[i][j]` followed by a space.
Step 13: Print a newline after each row.
Step 14: Initialize `hasSaddlePoint` to `false` and `saddlePoint` to 0.
Step 15: Iterate over `i` from 0 to `n-1`.
Step 16: Initialize `minRow` to `mat[i][0]` and `minColIndex` to 0.
Step 17: Iterate over `j` from 1 to `n-1`.
Step 18: Update `minRow` and `minColIndex` if `mat[i][j]` is less than `minRow`.
Step 19: Initialize `isSaddle` to `true`.
Step 20: Iterate over `k` from 0 to `n-1`.
Step 21: Set `isSaddle` to `false` if `mat[k][minColIndex]` is greater than `minRow`.
Step 22: Break the loop if `isSaddle` is `false`.
Step 23: If `isSaddle` is `true`, set `saddlePoint` to `minRow`, set `hasSaddlePoint` to `true`, and
break the loop.
Step 24: Print the saddle point if `hasSaddlePoint` is `true`, otherwise print "NO SADDLE
POINT".
Step 25: Iterate over `i` from 0 to `n-2`.
Step 26: Iterate over `j` from `i+1` to `n-1`.
Step 27: Swap `mat[i][i]` with `mat[j][j]` if `mat[i][i]` is greater than `mat[j][j]`.
Step 28: Print "Matrix after sorting the principal diagonal:".
Step 29: Iterate over `i` from 0 to `n-1`.
Step 30: Iterate over `j` from 0 to `n-1`.
Step 31: Print matrix element `mat[i][j]` followed by a space.
Step 32: Print a newline after each row.
Step 33: Close `Scanner sc`.
Step 34: End of algorithm.
SOURCE CODE:
import java.util.Scanner;
// 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");
}
sc.close();
}
}
A simple encryption system uses a shifting process to hide a message. The value of the shift can
be in the range 1 to 26. For example a shift of 7 means that A = U, B =V,C = W, etc.i e.
Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T
Fist an extra space is added to the end of the string. To make things little more difficult, spaces
within the original text are replaced with QQ before the text is encrypted. Double Q (QQ) was
selected because no English word ends in Q or contains QQ.
Additionally the coded message is printed in blocks of six characters separated by spaces. The
last block might not contain six characters. Write a program that takes the coded text (less than
100 characters), the shift value and prints the decoded original text. Your program must reject
any non-valid value for shift and display an error message “INVALID SHIFT VALUE)”.Assume
all characters are upper case. Test your program for the following data and some data that you
have coded, using the rules given above:
SAMLE DATA:
INPUT:
CODED TEXT : “UHINBY LKKQCH HYLKK”
SHIFT : 7
OUTPUT:
DECODED TEXT : ANOTHER VALUE
INPUT:
CODED TEXT : “RUIJGG EVGGBK SAGG”
SHIFT : 11
OUTPUT:
DECODED TEST : BEST OF LUCK
INPUT:
CODED TEXT : “DKSMMW NAMMUK QMM”
SHIFT : 29
OUTPUT:
INVALID SHIFT VALUE
ALGORITHM:
main()
1. Start the algorithm.
2. Create a Scanner object scanner to read user inputs.
3. Print "INPUT:" and read the codedText from the user.
4. Print "SHIFT:" and read the shift value from the user.
5. Check if shift is outside the valid range (1 to 26):
o If yes, print "INVALID SHIFT VALUE" and end the program.
6. Decode the codedText using the decodeMessage method with the given shift.
7. Print the decoded message.
8. Close the scanner object.
9. End the algorithm.
decodeMessage(codedText, shift)
1. Remove spaces from the codedText.
2. Calculate the reverse shift value: 26 - (shift % 26).
3. Initialize an empty StringBuilder for the decoded message.
4. Iterate over each character in the codedText:
o If the character is 'Q' followed by another 'Q':
Append a space to the decodedMessage.
Skip the next character.
o Else, decode the character using the reverse shift and append it to the
decodedMessage.
5. Return the decoded message.
SOURCE CODE:
import java.util.Scanner;
scanner.close();
}
return decodedMessage.toString();
}
}
OUTPUT:
Question 21:
The manager of a company wants to analyse the machine uses from the records to find the
utilization of the machine. He wants to know how long each user used the machine. When the
user wants to use the machine he must login to the machine and after finishing the work he must
log off the machine.
Each log record consists of:
User identification number.
Login time and date.
Logout time and date.
Time consists of:
Hours
Minutes
Date consists of:
Day
Month
You may assume all logins and logouts are in the same year and there are 100 users at the most.
The time format is 24 hours and minutes.
Design a program:
(a) To find the duration for which each user has logged. Output all records along with the
duration in hours (format hours: minutes).
(b) Output the record of the user who logged for the longest duration.You may assume that no
user will login for more than 40 minutes.
Test your program for the following data and some random data.
SAMPLE DATA;
INPUT:
Number of users : 3
USER LOGIN LOGOUT
IDENTIFICATION TIME & DATE TIME & DATE
149 20:10 20-12 2:50 21-12
173 12:30 20-12 12:30 21-12
142 16:20 20-12 16:30 20-12
OUTPUT:
USER LOGIN LOGOUT DURATION
IDENTIFICATION TIME & DATE TIME & DATE HOURS : MINS
149 20:10 20-12 2:50 21-12 6 : 40
173 12:30 20-12 12:30 21-12 24 : 00
142 16:20 20-12 16:30 20-12 00 : 10
THE USER WHO LOGGED IN FOR THE LONGEST DURATION:
173 12:30 20-12 12:30 21-12 24 : 00
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 22:
// Check if the sum of left and right parts equals the original number
return (leftNum + rightNum) == n;
}
int count = 0;
for (int i = p; i <= q; i++) {
if (isKaprekar(i)) {
System.out.print(i + " ");
count++;
}
}
Specify the class Personal giving details of the constructor and member functions void
display( ). Using the concept of inheritance, specify the class Retire giving details of
constructor, and the member functions void provident( ), void gratuity( ) and the void
display1( ). The main function need not be written.
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 26:
Chain is an entity which can hold at the most 50 integers. The chain enables the user to add and
remove integers from both the ends i.e. front and rear. Define a class Chain with the following
details:
Class name : Chain
Data Members:
ele[ ] : the array to hold the integer elements.
Cap : stores the maximum capacity of the array.
front : to point the index of the front.
rear : to point the index of the rear.
Member functions:
Chain(int max) : constructor to initialize the data cap = max, front = rear = 0 and to
create the integer array.
void pushfront(int v) : to add integers from the front index if possible else display the
message(“full from front”).
int popfront( ) : to remove the return elements from front. If array is empty then return-
999.
void pushrear(int v) : to add integers from the front index if possible else display the
message(“full from rear”).
int poprear( ) : to remove and return elements from rear. If the array is empty then
return-999.
(a) Specify the class Chain giving details of the constructor and member function void
pushfront(int), int popfront( ), void pushrear(int) and int poprear ( ).The main function need not
be written.
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 27:
Design a “AutoSort” class having the following data members and member functions:
Data Members
int arr[] : stores a list of n integers accepted from the user
int n : stores the size of the array arr
Member functions:
AutoSort()
void insert() : insert the elements within the array in such a way that the elements are
all arranged in the ascending order.
void display() : display the contents of the array
AutoSort merge(AutoSort m) : merges the contents of both the arrays in such way that after
merging the merged array has the elements in ascending order. Do not use any sorting algorithm
to sort the merged array.
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 28:
A Keith number is an n-digit integer N>9 such that if a Fibonacci-like sequence (in which each
term in the sequence is the sum of the n previous terms) is formed with the first n terms taken as
the decimal digits of the number N, then N itself occurs as a term in the sequence. For example,
197 is a Keith number since it generates the sequence 1, 9, 7, , ,
, , .
Design a class named “Keith” having the following data members and member functions :
Data Members:
int n : an integer variable storing the number to be checked.
Member Functions:
void storenum() accepts the number from the user.
boolean checkKeith() Returns true if the number is a Keith as defined above
otherwise returns false.
void findKeithNums(int x,int y) displays all the Keith numbers between x and y(both
inclusive).
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 29:
The Mayan civilisation used three different calendars. In their long count calendar there were 20
days (called kins) in a uinal, 18 uinals in a tun, 20 tuns in a katun and 20 katuns in a baktun. In
our calendar, we specify a date by giving the day, then month, and finally the year. The Maya
specified dates in reverse, giving the baktun (1-20), then katun (1-20), then tun (1-20), then uinal
(1-18) and finally the kin (1-20).
The Mayan date 13 20 7 16 3 corresponds to the date 1 January 2000 (which was a Saturday).
Write a program which, given a Mayan date (between 13 20 7 16 3 and 14 1 15 12 3 inclusive),
outputs the corresponding date in our calendar. You should output the month as a number.
You are reminded that, in our calendar, the number of days in each month is:
1 January 31
3 March 31
4 April 30
5 May 31
6 June 30
7 July 31
8 August 31
9 September 30
10 October 31
11 November 30
12 December 31
Within the range of dates for this question, every year divisible by 4 is a leap year.
Sample run
13 20 9 2 9
22 3 2001
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT:
Question 30:
An interface Data is defined with a data member and a method volume() which returns the
volume of the implementing shape. A super class Base has been defined to contain the radius of a
geometrical shape. Define a sub-class CalVol which uses the properties of the interface Data and
the class Base and calculates the volume of a cylinder.
The details of the members of the interface and both the classes are given below:
Interface name: Data
Data member:
double pi: initialize pi = 3.142.
Member function/method:
double volume()
Class name: Base
Data member/instance variable:
rad: to store the radius in decimal.
Member functions/methods:
Base(…): parameterized constructor to initialize the data members.
void show(): displays the radius with an appropriate message.
Class name: CalVol
Data member/instance variable:
ht: to store the height in decimal.
Member functions/methods:
CalVol(…): parameterized constructor to initialize the data members of both the classes.
double volume(): calculates the volume of a sphere by using the formula (pi × radius2 × height)
void show(): displays the data members of both the classes and the volume of the sphere with
appropriate message.
Assume that the interface Data and the super class Base has been defined. Using the concept of
inheritance, specify the class CalVol giving details of the constructor, double volume() and void
show().
The interface, super class, main() function and algorithm need not be written.
ALGORITHM:
SOURCE CODE:
VARIABLE DESCRIPTION TABLE:
OUTPUT: