Prog Assign 2024
Prog Assign 2024
Reg. No.
-----------------------------------------------------
----------------
During the year 2024 – 2025
1|Page
Internal Examiner External Examiner Principal
INDEX
1. GOLDBACH NUMBER
2. MATRIX ROTATION AND HIGHEST ELEMENT FINDER
3. PANGRAM CHECKER AND WORD LENGTH ANALYZER
4. DAY TO DATE CONVERTER AND FUTURE DATE CALCULATOR
5. SYMMETRY CHECKER AND DIAGONAL SUM CALCULATOR
6. CELL PHONE KEYPAD KEYSTROKE COUNTER
7. UNIQUE DIGIT INTEGER FINDER IN A SPECIFIED RANGE
8. MATRIX OPERATIONS
9. ANAGRAM CHECKER
10. PRIME – ADAM INTEGER
11. OCTAL MATRIX COVERTER
12. SENTENCE ORGANIZER
13. MATRIX ROW SORTER
14. VERTICAL TEAM BANNER DISPLAY
15. COMPOSITE MAGIC NUMBER
16. SENTENCE PROCESSOR
17. SMITH NUMBER
18. SENTENCE ANALYZER : VOWEL AND WORD COUNTER
19. MATRIX : LARGEST ELEMENT AND SORT ROWS
20. HAMMING NUMBER
2|Page
21. DOUBLY MARKOV MATRIX CHECKER
22. SNOWBALL STRING CHECKER
23. EVIL NUMBER
24. PRIME PALLINDROME INTEGER
25. SENTENCE ANALYSIS AND REARRANGEMENT TOOL
26. ISBN VERIFICATION AND VALIDATING ISBN CODES
27. GENERATE A MIRROR IMAGE OF A SQUARE MATRIX
28. PALINDROME WORD CHECKER IN A SENTENCE
29. PACKING CARTON CALCULATOR
30. QUIZ COMPETITION SCORING SYSTEM
31. CAESAR CIPHER – ENCRYPTION TECHNIQUE
32. CODE VALIDATION FOR ALTERNATE UPPERCASE LETTERS
33. MESSAGE DECODING PROGRAM
34. SINGLE DIMENSIONAL ARRAY - SQUARE MATRIX PROGRAM
35. PALINDROME CONVERSION PROGRAM
36. LUCKY NUMBER
37. UNIQUE ELEMENTS IN SQUARE MATRIX
38. SENTENCE REARRANGEMENT AND VALIDATION
39. DENOMINATION BREAKDOWN AND AMOUNT IN WORDS
40. INTEGER ARRAY REARRANGEMENT
3|Page
Question 1:
A number is said to be a Goldbach number, if the number can be expressed as the
addition of two odd prime number pairs. If we follow the above condition, then we can
find that every even number larger than 4 is a Goldbach number because it must have
any pair of odd prime number pairs.
Example:
6 = 3,3 ( ONE PAIR OF ODD PRIME )
10 = 3,7 and 5 , 5 ( TWO PAIRS OF ODD PRIME )
Write a program to enter any positive EVEN natural number ‘N’ where (1<=N<=50) and
generate odd prime twin of ‘N’
Test your program for the following data and some random data.
Example 1
INPUT: N = 14
OUTPUT: ODD PRIME PAIRS ARE: 3, 11
7, 7
Example 2
INPUT: N = 20
OUTPUT: ODD PRIME PAIRS ARE: 17, 3
13, 7
Example 3
INPUT: N = 44
OUTPUT: ODD PRIME PAIRS ARE: 41, 3
37, 7
31, 13
Example 4
INPUT: N = 25
OUTPUT: INVALID INPUT
Algorithm:
1. Input: Read an integer NNN from the user.
2. Check Validity:
o If N is not even or N<2 or N>, print "INVALID INPUT" and exit.
3. Initialize: Create an empty list to store prime numbers.
4. Generate Odd Primes:
4|Page
o Loop from 3 to N (inclusive) with a step of 2:
For each number i, check if it is prime:
A number is prime if it is greater than 1 and not divisible by
any number from 2 to the square root of i.
If i is prime, add it to the list of primes.
5. Find Goldbach Pairs:
o Loop through the list of odd primes:
For each prime p, calculate q=N−p.
If q is also in the list of primes:
Print the pair (p,q)
Source Code:
import java.util.*;
class Goldbach
{
public static boolean isprime(int n)
{
if(n<=0)
return false;
else
for(int i=2;i<=n/2;i++)
if(n%i==0)
return false;
return true;
}
5|Page
int diff = n-i;
if(isprime(diff))
System.out.println("("+i+","+diff+")");
}
else
System.out.println("INVALID INPUT");
}
6|Page
Question 2:
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 than10. Allow the user to input integers into this matrix. Display appropriate error
message for an invalid input.
Perform the following tasks on the matrix.
(a) Display the input matrix
(b) Shift each row one step upwards so the first row will become the last row 2nd row
will be the
1st row and so on
(c) Display the rotated matrix along with the highest element and its location in the
matrix
Test your program for the following data and some random data:
Example 1
INPUT: M =3
N=4
Enter elements in the matrix:
100 90 87 76
200 500 167 998
77 567 89 254
OUTPUT: FORMED MATRIX AFTER ROTATING:
200 500 167 998
77 567 89 254
100 90 87 76
Highest element: 998 ( Row: 0 and Column: 3 )
Example 2
INPUT: M =4
N=3
Enter elements in the matrix:
54 120 187
78 55 289
134 67 89
63 341 122
OUTPUT: FORMED MATRIX AFTER ROTATING:
7|Page
78 55 289
134 67 89
63 341 122
54 120 187
Highest element: 341 ( Row: 2 and Column: 1 )
Example 3
INPUT: M = 2
N=3
OUTPUT: SIZE IS OUT OF RANGE. INVALID ENTRY
Algorithm:
1. Input the Size of the Matrix:
o Prompt the user for values of M (number of rows) and N (number of
columns).
o Check if M and N are both greater than 2 and less than 10.
o If invalid, display an error message and exit.
2. Initialize the Matrix:
o Create a 2D array A of size M x N.
3. Input Elements of the Matrix:
o Prompt the user to enter integers for each element of the matrix.
o Store the integers in the matrix A.
4. Display the Input Matrix:
o Print the elements of the matrix in a structured format.
5. Rotate the Matrix:
o Create a new 2D array B of the same size.
o Shift each row of A upwards:
For each row i, set B[i] to A[(i + 1) % M] to implement the rotation.
6. Display the Rotated Matrix:
o Print the elements of the rotated matrix B.
7. Find the Highest Element:
o Initialize variables to track the highest element and its position.
o Iterate through the rotated matrix to find the highest element and its
coordinates.
8|Page
Source Code:
import java.util.*;
class Rotate
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.print("M= ");
int m = sc.nextInt();
System.out.print("N= ");
int n=sc.nextInt();
int x[][] = new int[m][n];
int y[][] = new int[m][n];
int big = -999999999;
int b1=0,b2=0;
if(m<2 ||n<2 ||m>10 || n>10){
System.out.println("SIZE IS OUT OF RANGE. INVALID ENTRY");
System.exit(0);
System.out.println("Enter elements in the matrix:");
for(int i = 0 ;i<m;i++)
for(int j = 0 ;j<n;j++)
x[i][j] = sc.nextInt();
System.out.println();
for(int i = 0 ;i<m;i++)
for(int j = 0 ;j<n;j++)
System.out.print(x[i][j]+" ");
System.out.println();
}
for(int i = 0 ;i<m;i++)
{
for(int j = 0 ;j<n;j++)
{
if(i!=0 && i<m-1)
y[i][j]=x[i+1][j];
else if(i==0)
y[i][j]=x[1][j];
9|Page
else
y[i][j]=x[0][j];
}
System.out.println();
}
System.out.println("FORMED MATRIX AFTER ROTATING:");
for(int i = 0 ;i<m;i++)
{
for(int j = 0 ;j<n;j++)
{
System.out.print(y[i][j]+" ");
}
System.out.println();
}
for(int i = 0 ;i<m;i++)
{
for(int j = 0 ;j<n;j++)
{
if(y[i][j]>big)
{
big = y[i][j];
b1= i;
b2 = j;
}
}
System.out.println();
}
System.out.println("Highest element: "+big+" (ROW: "+b1+" and Column:
"+b2+")");
}
}
10 | P a g e
Question 3:
Write a program to accept a sentence which may be terminated by either ‘.’ ,‘?’or ‘!’
only.
The words may be separated by a single blank space and should be case-insensitive.
Perform the following tasks:
(a) Determine if the accepted sentence is a Pangram or not.
[A Pangram is a sentence that contains every letter of the alphabet at least once.]
Example: "The quick brown fox jumps over the lazy dog"
(b) Display the first occurring longest and shortest word in the accepted sentence.
Test your program for the following data and some random data:
Example 1
INPUT: Pack my box with five dozen liquor jugs.
OUTPUT: IT IS A PANGRAM
LONGEST WORD: dozen
SHORTEST WORD: my
Example 2
INPUT: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
OUTPUT: IT IS A PANGRAM
LONGEST WORD: QUICK
SHORTEST WORD: THE
Example 3
INPUT: Hello my World.
OUTPUT: IT IS NOT A PANGRAM
LONGEST WORD: Hello
SHORTEST WORD: my
Example 4
INPUT: Alas ! it failed #
OUTPUT: INVALID INPUT
11 | P a g e
Algorithm:
1. Input the Sentence:
Accept a sentence from the user. Ensure it ends with one of the following
characters: ., ?, or !.
If it does not end with any of these characters, output "INVALID INPUT".
2. Check for Pangram:
Initialize a boolean array of size 26 (for each letter of the alphabet).
Convert the sentence to lowercase (to ensure case-insensitivity).
Iterate through each character of the sentence:
o If the character is an alphabetic letter (a-z), mark its corresponding index in
the boolean array.
After processing all characters, check if all entries in the boolean array are true
(indicating all letters were found).
If all letters are found, print "IT IS A PANGRAM", otherwise print "IT IS NOT A
PANGRAM".
3. Find Longest and Shortest Words:
Split the sentence into words (removing the terminating character).
Initialize variables to keep track of the longest and shortest words.
Iterate through the list of words:
o Update the longest word if the current word's length exceeds the length of
the longest word found so far.
o Update the shortest word if the current word's length is less than the
length of the shortest word found so far.
Print the longest and shortest words.
Source Code:
import java.util.*;
class Panagram
{
private String x;
public void main()
{
Scanner sc = new Scanner(System.in);
x=sc.nextLine();
String sh;
12 | P a g e
String lg;
int c=0;
if(x.endsWith(".")|| x.endsWith("?")||x.endsWith("!"))
{
if(check_Pana())
System.out.println("IT IS A PANGRAM ");
else if(check_Pana()==false)
System.out.println("IT IS NOT A PANGRAM");
checker();
}
else{
System.out.println("INVALID INPUT");
}
}
public void checker()
{
int big=0;
int small=0;
big=small=0;
String h[] = x.split("[\\s]");
String p=h[h.length-1];
String z = p.substring(0,p.length()-2);
h[h.length-1]=z;
for(int i = 0 ;i<h.length;i++)
{
if(h[i].length()>h[big].length())
big=i;
if(h[i].length()<h[small].length())
small=i;
}
System.out.println("LONGEST WORD: "+h[big]);
System.out.println("SHORTEST WORD:"+h[small]);
}
13 | P a g e
{
String alp = "abcdefghijklmnopqrstuvwxyz";
int arr[] = new int[alp.length()];
int c = 0;
String g =x.substring(0,x.length()-1).toLowerCase();
if(x.length()<26)
return false;
for(int i = 0 ;i<alp.length();i++)
{
for(int j = 0 ;j<g.length();j++)
if(g.charAt(j)==alp.charAt(i) && alp.charAt(i)!=' ')
c++;
arr[i] = c;
c=0;
}
for(int i = 0 ;i<arr.length;i++)
if(arr[i]==0)
return false;
return true;
}
}
14 | P a g e
Question 4:
Write a program in JAVA to accept day number (between 1 and 366) and year (yyyy)
from the user and display the corresponding date. Also accept ‘N’ from the user where
(1<=N<=100) to compute and display the future date ‘N’ days after the given date.
Display error message if the value of the day number or ‘N’ are not within the limit. Day
number is calculated taking 1st January of the given year as 1.
Test your program with given set of data and some random data
Example 1
INPUT: DAY NUMBER: 50
YEAR: 2024
N: 25
OUTPUT: ENTERED DATE: FEBRUARY 19, 2024
25 DAYS LATER: MARCH 15, 2024
Example 2
INPUT: DAY NUMBER: 321
YEAR: 2024
N: 77
OUTPUT: ENTERED DATE: NOVEMBER 16, 2024
77 DAYS LATER: FEBRUARY 1, 2025
Example 3
INPUT: DAY NUMBER: 400
YEAR: 2024
N: 125
OUTPUT: INCORRECT DAY NUMBER
INCORRECT VALUE OF ‘N’
Algorithm:
1. Input:
o Accept dayNumber (an integer between 1 and 366).
o Accept year (a four-digit integer).
o Accept N (an integer between 1 and 100).
2. Validation:
o Check if dayNumber is between 1 and 366.
If not, output "INCORRECT DAY NUMBER" and terminate.
o Check if N is between 1 and 100.
15 | P a g e
If not, output "INCORRECT VALUE OF ‘N’" and terminate.
3. Determine if the Year is a Leap Year:
o A year is a leap year if:
It is divisible by 4.
If it is divisible by 100, it must also be divisible by 400.
o Store the number of days in each month based on whether the year is a
leap year:
January: 31, February: 28 or 29, March: 31, April: 30, May: 31, June:
30, July: 31, August: 31, September: 30, October: 31, November: 30,
December: 31.
4. Calculate the Date:
o Loop through the months and subtract the number of days in each month
from dayNumber until dayNumber is less than or equal to the days in the
current month.
o Once found, record the month and the day.
5. Output the Entered Date:
o Format and print the date as "MONTH DAY, YEAR".
6. Calculate Future Date:
o Add N to dayNumber to get futureDayNumber.
o If futureDayNumber exceeds 366, increment the year and adjust the
futureDayNumber accordingly.
o Repeat the same process as above to determine the future date.
7. Output the Future Date:
o Format and print the future date as "N DAYS LATER: MONTH DAY, YEAR".
Source code:
import java.util.*;
class FutureDate {
int dayNumber;
int year;
int N;
FutureDate() {
dayNumber = 0;
year = 0;
N = 0;
16 | P a g e
}
public void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("DAY NUMBER (1-366): ");
dayNumber = sc.nextInt();
System.out.print("YEAR: ");
year = sc.nextInt();
System.out.print("N (1-100): ");
N = sc.nextInt();
boolean f=true;
if (dayNumber < 1 || dayNumber > (isLeapYear(year) ? 366 : 365)) {
System.out.println("INCORRECT DAY NUMBER");
f=false;
}
if (N < 1 || N > 100) {
System.out.println("INCORRECT VALUE OF ‘N‘");
f=false;
}
if(f==true)
{
System.out.print("ENTERED DATE: ");
printDate(dayNumber, year);
System.out.print(N + " DAYS LATER: ");
printDate(dayNumber + N, year);
}
}
public void printDate(int day, int year) {
String[] months = {"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year))
daysInMonth[2] = 29;
while (day > 365 + (isLeapYear(year) ? 1 : 0)) {
day -= 365 + (isLeapYear(year) ? 1 : 0);
year++;
}
for (int i = 1; i < months.length; i++) {
17 | P a g e
if (day <= daysInMonth[i]) {
System.out.println(months[i] + " " + day + ", " + year);
return;
}
day -= daysInMonth[i];
}
}
public boolean isLeapYear(int year) {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
public static void main(String[] args) {
FutureDate fd = new FutureDate();
fd.accept();
}
}
18 | P a g e
Question 5:
Write a program to declare a square matrix A[ ][ ] of order M × M where `M' is the
number
of rows and the number of columns, such that M must be greater than 2 and less than
10.
Accept the value of M as user input. Display an appropriate message for an invalid
input.
Allow the user to input integers into this matrix. Perform the following tasks:
(a) Display the original matrix.
(b) Check if the given matrix is Symmetric or not.
(A square matrix is said to be Symmetric, if the element of the ith row and jth column
is equal to the element of the jth row and ith column.)
(c) Find the sum of the elements of left diagonal and the sum of the elements of right
diagonal of the matrix and display them.
Test your program for the following data and some random data:
Example 1
INPUT: M = 3
Enter elements of the matrix:
123
245
356
OUTPUT: ORIGINAL MATRIX
123
245
356
THE GIVEN MATRIX IS SYMMETRIC
The sum of the left diagonal = 11
The sum of the right diagonal = 10
Example 2
INPUT: M = 4
Enter elements of the matrix:
7892
4563
8531
7642
19 | P a g e
OUTPUT: ORIGINAL MATRIX
7892
4563
8531
7642
THE GIVEN MATRIX IS NOT SYMMETRIC
The sum of the left diagonal = 17
The sum of the right diagonal = 20
Example 3
INPUT: M = 12
OUTPUT: SIZE IS OUT OF RANGE
Algorithm:
1. Input:
o Prompt the user to enter the size of the matrix M.
2. Validation:
o Check if M is greater than 2 and less than 10.
If not, output "SIZE IS OUT OF RANGE" and terminate the program.
3. Matrix Declaration:
o Declare a square matrix A[M][M].
4. Input Matrix Elements:
o Prompt the user to input integers into the matrix, filling A[i][j] for i from 0
to M-1 and j from 0 to M-1.
5. Display the Original Matrix:
o Print the matrix in a formatted manner.
6. Check Symmetry:
o Initialize a boolean variable isSymmetric to true.
o Loop through the matrix:
For each element A[i][j], check if it is equal to A[j][i].
If any pair is not equal, set isSymmetric to false and break out of the
loop.
o Output whether the matrix is symmetric or not based on the value of
isSymmetric.
7. Calculate Diagonal Sums:
o Initialize two variables leftDiagonalSum and rightDiagonalSum to 0.
o Loop through the matrix to calculate:
leftDiagonalSum as the sum of elements where i == j.
20 | P a g e
rightDiagonalSum as the sum of elements where i + j == M - 1.
8. Output Diagonal Sums:
o Print the sums of the left and right diagonals.
Source Code:
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the order of the matrix (M): ");
int M = sc.nextInt();
if (M <= 2 || M >= 10) {
System.out.println("SIZE IS OUT OF RANGE");
return;
}
int[][] matrix = new int[M][M];
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = sc.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
boolean isSymmetric = true;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
if (matrix[i][j] != matrix[j][i]) {
isSymmetric = false;
break;
}
}
if (!isSymmetric) break;
21 | P a g e
}
if (isSymmetric) {
System.out.println("THE GIVEN MATRIX IS SYMMETRIC");
} else {
System.out.println("THE GIVEN MATRIX IS NOT SYMMETRIC");
}
int leftDiagonalSum = 0;
int rightDiagonalSum = 0;
for (int i = 0; i < M; i++) {
leftDiagonalSum += matrix[i][i]; // Left diagonal (i, i)
rightDiagonalSum += matrix[i][M - 1 - i]; // Right diagonal (i, M-1-i)
}
System.out.println("The sum of the left diagonal = " + leftDiagonalSum);
System.out.println("The sum of the right diagonal = " + rightDiagonalSum);
}
}
22 | P a g e
Question 6:
23 | P a g e
Algorithm
24 | P a g e
1. Input Handling:
o Prompt the user to enter a word consisting of uppercase letters (no
punctuation or spaces).
o Read the input and convert it to uppercase to ensure uniformity.
2. Input Validation:
o Check if the input string contains only uppercase alphabetic characters (A-
Z).
o If the input is invalid (contains non-alphabetic characters), print "INVALID
ENTRY" and terminate the program.
3. Initialize Keystrokes Counter:
o Create a variable totalKeystrokes and initialize it to 0.
4. Keystroke Calculation:
o For each character in the input word:
Determine the number of keystrokes needed to type the character
based on its mapping to a mobile keypad:
'A', 'B', 'C' → 1, 2, 3 keystrokes respectively.
'D', 'E', 'F' → 1, 2, 3 keystrokes respectively.
'G', 'H', 'I' → 1, 2, 3 keystrokes respectively.
'J', 'K', 'L' → 1, 2, 3 keystrokes respectively.
'M', 'N', 'O' → 1, 2, 3 keystrokes respectively.
'P', 'Q', 'R', 'S' → 1, 2, 3, 4 keystrokes respectively.
'T', 'U', 'V' → 1, 2, 3 keystrokes respectively.
'W', 'X', 'Y', 'Z' → 1, 2, 3, 4 keystrokes respectively.
Add the number of keystrokes for the character to totalKeystrokes.
5. Output Result:
o Print the total number of keystrokes calculated for the input word.
Source code:
import java.util.Scanner;
public class KeypadKeystrokes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word (no punctuation or spaces): ");
String input = scanner.nextLine().toUpperCase(); // Convert input to uppercase for
consistency
if (!input.matches("[A-Z]+")) {
System.out.println("INVALID ENTRY");
25 | P a g e
return;
}
int totalKeystrokes = calculateKeystrokes(input);
System.out.println("Number of keystrokes = " + totalKeystrokes);
}
private static int calculateKeystrokes(String word) {
int keystrokes = 0;
26 | P a g e
case 'W':
case 'X':
case 'Y':
case 'Z': return (ch - 'W') + 1; // W=1, X=2, Y=3, Z=4
default: return 0; // Not applicable, should not happen due to validation
}
}
}
Question 7:
A unique-digit integer is a positive integer (without leading zeros) with no duplicate
digits. For example, 7, 135, 214 are all unique-digit integers whereas 33, 3121, 300 are
not. Given two positive integers m and n, where m < n, write a program to determine
27 | P a g e
how many unique-digit integers are there in the range between m and n (both
inclusive) and output them. The input contains two positive integers m and n. Assume
m < 30000 and n < 30000. You are to output the number of unique-digit integers in the
specified range along with their values in the format specified below:
Test your program for the following data and some random data.
Example 1:
INPUT: m = 100
n = 120
OUTPUT:
THE UNIQUE-DIGIT INTEGERS ARE: 102, 103, 104, 105, 106, 107, 108, 109, 120
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 9
Example 2:
INPUT: m = 2505
n = 2525
OUTPUT:
THE UNIQUE-DIGIT INTEGERS ARE: 2506, 2507, 2508, 2509, 2510, 2513, 2514,
2516, 2517, 2518, 2519
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 11
Example 3:
INPUT: m = 2520
n = 2529
OUTPUT: THE UNIQUE-DIGIT INTEGERS ARE: NIL
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 0.
Algorithm:
Validation:
Check if m is less than 30,000 and n is less than 30,000.
Ensure that m is less than n.
If any condition fails, print "INVALID INPUT" and terminate.
Initialization:
Create a variable l to count the unique-digit integers found.
Print a header message "THE UNIQUE-DIGIT INTEGERS ARE: ".
Iterate through the Range:
For each integer i from m to n (inclusive):
1. Convert the integer i to a string d.
2. Call the function check(d) to determine if d contains all unique digits.
Check for Unique Digits:
28 | P a g e
In the check function:
o For each character in the string k:
Initialize a counter m to zero.
Compare the current character with all characters in the string:
If a match is found, increment the counter m.
If m exceeds 1 for any character, return false (indicating not all digits
are unique).
o If all characters are unique, return true.
Output Unique-Digit Integers:
If check(d) returns true:
o If it's the first unique-digit integer found, print d on a new line.
o Otherwise, print d prefixed with a comma.
Source Code:
import java.util.Scanner;
class unique_digit
{
private int m;
private int n;
29 | P a g e
return true;
}
public void calculate()
{
System.out.print("THE UNIQUE-DIGIT INTEGERS ARE: ");
int l = 0;
for(int i = m;i<=n;i++)
{
String d = String.valueOf(i);
if(check(d))
{
if(l==0)
{
System.out.println();
System.out.print(d);
l++;
}
else
{
System.out.print(", " + d);
l++;
}
}
}
if(l==0)
{
System.out.print("NIL");
}
System.out.println();
System.out.println("FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: " + l + ".");
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter m:");
int m =sc.nextInt();
System.out.println("Enter n:");
30 | P a g e
int n =sc.nextInt();
if(m<30000 && n<30000 && m<n)
{
unique_digit a = new unique_digit(m,n);
a.calculate();
}
else
System.out.println("INVALID INPUT");
}
}
Question 8:
Write a program to declare a matrix A [ ] [ ] of order (M x N) where ‘M’ is the number of rows and
‘N’ is the number of columns such that 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:
Perform the following tasks on the matrix.
31 | P a g e
(a) Display the input matrix.
(b) Find the maximum and minimum value in the matrix and display them along with their
position.
(c) Sort the elements of the matrix in descending order using any standard sorting technique and
rearrange them in the matrix.
(d) Output the rearranged matrix.
Test your program for the following data and some random data:
Example 1
INPUT: M = 3 N = 4
Enter elements of the matrix
8 7 9 3
-2 0 4 5
1 3 6 -4
OUTPUT: ORIGINAL MATRIX
8 7 9 3
-2 0 4 5
1 3 6 -4
LARGEST NUMBER: 9
ROW = 0
COLUMN = 2
SMALLEST NUMBER: -4
ROW = 2
COLUMN = 3
REARRANGED MATRIX
-4 -2 0 1
3 3 4 5
6 7 8 9
Example 2
INPUT: M = 3
N=3
Enter elements of the matrix:
7 9 3
-2 4 5
1 16 4
OUTPUT: ORIGINAL MATRIX
7 9 3
-2 4 5
1 16 4
LARGEST NUMBER: 16
ROW = 2
COLUMN = 1
SMALLEST NUMBER: -2
32 | P a g e
ROW = 1
COLUMN = 0
REARRANGED MATRIX
-2 1 3
4 4 5
7 9 16
Example 3
INPUT: M = 3
N = 22
OUTPUT: SIZE OUT OF RANGE
Algorithm:
Validation:
Check if both m and n are greater than 2 and less than 20.
If any condition fails, print "SIZE OUT OF RANGE" and terminate.
Find Minimum and Maximum Method (minimum_and_maximum):
Initialize big to the first element mat[0][0] and set its indices (big_row, big_col) to
(0, 0).
Initialize small to the first element mat[0][0] and set its indices (small_row,
small_col) to (0, 0).
For each element in the matrix:
o If the current element is greater than big, update big, big_row, and big_col.
o If the current element is smaller than small, update small, small_row, and
small_col.
Print the largest number, its row, and column.
Print the smallest number, its row, and column.
Rearrange Method (rearrange):
For each element mat[i][j] in the matrix:
o Compare it with every other element mat[x][y] in the matrix.
o If mat[i][j] is less than mat[x][y], swap the two elements.
This effectively sorts the matrix in ascending order.
Main Method:
Execute the input, display the original matrix, find and display the minimum and
maximum values, rearrange the matrix, and display the rearranged matrix
Source Code:
import java.util.Scanner;
class matrix
{
33 | P a g e
public int mat[][];
public int m;
public int n;
public matrix(int m,int n)
{
this.m = m;
this.n = n;
mat = new int [m][n];
}
public void input()
{
Scanner sc = new Scanner(System.in);
for(int i = 0;i<m;i++)
for(int j = 0;j<n;j++)
{
System.out.println("Enter a value for : mat[" + i+"]["+j+"]");
mat[i][j] = sc.nextInt();
}
}
34 | P a g e
for(int i = 0;i<m;i++)
{
for(int j = 0;j<n;j++)
{
if(big<mat[i][j])
{
big = mat[i][j];
big_row = i;
big_cols = j;
}
if(small>mat[i][j])
{
small = mat[i][j];
small_row = i;
small_cols = j;
}
}
}
35 | P a g e
for(int y = 0;y<n;y++)
{
if(mat[i][j]<mat[x][y])
{
int t = mat[i][j];
mat[i][j] = mat[x][y];
mat[x][y] = t;
}
}
}
}
}
}
Question 9:
Write a program to check if a given string is an Anagram of another string. Two strings
are anagrams if they can be rearranged to form the same string. For example, "listen"
and "silent" are anagrams. Accept two strings from the user and check if they are
anagrams of each other. Ensure that the comparison is case-insensitive and ignores
37 | P a g e
spaces. Display an appropriate message based on whether they are anagrams or not. If
any of the strings contain invalid characters (e.g., numbers or special characters),
generate an error message.
Test your program with the following data and some random data:
Example 1
INPUT: Enter first string: Listen
Enter second string: Silent
OUTPUT: STRINGS ARE ANAGRAMS
Example 2
INPUT: Enter first string: Dormitory
Enter second string: Dirty room
OUTPUT: STRINGS ARE ANAGRAMS
Example 3
INPUT: Enter first string: Hello
Enter second string: World
OUTPUT: STRINGS ARE NOT ANAGRAMS
Example 4
INPUT: Enter first string: Test123
Enter second string: 321tset
OUTPUT: INVALID CHARACTERS IN STRING. INVALID INPUT
Algorithm:
Remove Whitespace:
Split the first string fs by whitespace and concatenate the resulting words into a
single string.
Split the second string ss by whitespace and concatenate the resulting words into
a single string.
Character Validation:
For each character in the concatenated string fs:
Check if it is an alphabetic character.
If any character is not alphabetic, print "INVALID CHARACTERS IN STRING.
INVALID INPUT" and terminate.
Repeat the same validation for the concatenated string ss.
Length Check:
If the lengths of fs and ss are not equal, print "STRINGS ARE NOT ANAGRAMS"
and terminate.
Anagram Check:
38 | P a g e
Initialize a flag variable f to 0.
For each character a in fs:
Loop through each character in ss:
If a matches a character in ss:
Remove the matched character from ss by creating a new substring (excluding
the matched character).
Set f to 1 (indicating a match was found).
Final Check:
If ss is empty after all characters in fs have been checked:
Print "STRINGS ARE ANAGRAMS".
Source Code:
import java.util.Scanner;
class anagrams
{
public String fs,ss;
String t[],m[];
public anagrams(String fs, String ss)
{
this.fs = fs;
this.ss = ss;
}
public void check()
{
t = fs.split("[\\s]+");
m = ss.split("[\\s]+");
fs = ss = "";
for(int i = 0;i<t.length;i++)
fs+=t[i];
for(int i = 0;i<m.length;i++)
ss+=m[i];
for(int i = 0;i<fs.length();i++)
if(Character.isAlphabetic(fs.charAt(i))==false)
System.out.println("INVALID CHARACTERS IN STRING. INVALID INPUT");
return;
for(int i = 0;i<ss.length();i++)
if(Character.isAlphabetic(ss.charAt(i))==false)
39 | P a g e
{
System.out.println("INVALID CHARACTERS IN STRING. INVALID INPUT");
return;
}
if(fs.length()!=ss.length())
{
System.out.println("STRINGS ARE NOT ANAGRAMS");
return ;
}
int f = 0;
for(int i = 0;i<fs.length();i++)
{
char a = fs.charAt(i);
for(int j = 0;j<ss.length();j++)
{
if(a==ss.charAt(j))
{
String m = ss.substring(0,j);
m+=ss.substring(j+1);
ss = m;
f = 1;
break;
}
}
if(f==1)
f = 0;
else
{
System.out.println("STRINGS ARE NOT ANAGRAMS");
return;
}
}
if(ss.length()==0)
System.out.println("STRINGS ARE ANAGRAMS");
}
public static void main()
{
40 | P a g e
Scanner sc = new Scanner(System.in);
System.out.println("Enter a first word");
String t = sc.nextLine();
System.out.println("Enter a second word");
String g = sc.nextLine();
anagrams a = new anagrams(t,g);
a.check();
}
}
Question 10:
41 | P a g e
Example: 2, 3, 5, 7 ... etc.
Adam number: The square of a number and the square of its reverse are reverse to
each other.
Example: If n = 13 and reverse of 'n' = 31, then,
(13)2 = 169
(31)2 = 961 which is reverse of 169
thus 13, is an Adam number.
Accept two positive integers m and n, where m is less than n as user input. Display all
Prime-Adam integers that are in the range between m and n (both inclusive) and
output them along with the frequency, in the format given below:
Test your program with the following data and some random data:
Example 1
INPUT:
m=5
n = 100
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
11 13 31
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 2
INPUT:
m = 100
n = 200
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
101 103 113
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 3
INPUT:
m = 50
n = 70
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
NIL
FREQUENCY OF PRIME-ADAM INTEGERS IS: 0
Example 4
INPUT:
42 | P a g e
m = 700
n = 450
OUTPUT:
INVALID INPUT.
Algorithm:
1. Input the Range:
Accept two positive integers m and n from the user.
If m is greater than n, output "INVALID INPUT." and terminate.
2. Define Helper Functions:
isPrime(n): Check if n is a prime number:
o Return false if n is less than or equal to 1.
o Loop from 2 to the square root of n, checking if n is divisible by any number in this
range. If it is, return false. Otherwise, return true.
reverse(n): Reverse the digits of n:
o Initialize a variable reversed to 0.
o While n is greater than 0, extract the last digit and append it to reversed. Divide n
by 10 to remove the last digit.
o Return reversed.
isAdam(n): Check if n is an Adam number:
o Get the reverse of n.
o Calculate the square of n and the square of its reverse.
o Check if the square of the reverse equals the reverse of the square of n. If true,
return true; otherwise, return false.
3. Find Prime-Adam Integers:
Initialize a counter count to 0.
Loop from m to n (inclusive):
o For each number, check if it is both prime and an Adam number using the helper
functions.
o If both conditions are satisfied, print the number and increment the counter.
4. Output Results:
If no Prime-Adam integers were found, print "NIL".
Print the frequency of Prime-Adam integers.
Source Code:
import java.util.*;
class Prime_Adam
{
private boolean isprime(int n)
43 | P a g e
{
if(n<=1)
return false;
int i=2;
while(i<=n/2)
{
if(n%i==0)
return false;
i++;
}
return true;
}
private int reverse(int n)
{
int s=0;
while(n!=0)
{
int r=n%10;
s=s*10+(r);
n=n/10;
}
return s;
}
private boolean isadam(int n)
{
int t=n;
int r=reverse(t);
int sqt=(t*t);
int sqr=(r*r);
if(sqt==reverse(sqr))
return true;
else
return false;
}
public void display()
{
Scanner sc=new Scanner(System.in);
44 | P a g e
System.out.print("m =");
int m=sc.nextInt();
System.out.print("n =");
int n=sc.nextInt();
int c=0;
if(m>n)
System.out.println("INVALID INPUT.");
else
{
System.out.println("THE PRIME-ADAM INTEGERS ARE:");
for(int i=m;i<=n;i++)
{
if(isadam(i)==true && isprime(i)==true)
{
c++;
System.out.print(i+" ");
}
}
if(c==0)
System.out.print("NIL");
System.out.println();
System.out.println("FREQUENCY OF PRIME-ADAM INTEGERS IS:"+c);
}
}
Question 11:
Write a program to declare a matrix A[][] of order (M x N) where 'M' is the number of rows and 'N'
is the number of columns such that the value of 'M' must be greater than 0 and less than 10 and
the value of 'N' must be greater than 2 and less than 6. Allow the user to input digits (0 - 7) only at
each location, such that each row represents an octal number.
45 | P a g e
Example:
2 3 1 (decimal equivalent of 1st row = 153 i.e. 2x82 + 3x81 + 1x80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4x82 + 0x81 + 5x80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1x82 + 5x81 + 6x80)
Perform the following tasks on the matrix:
OUTPUT:
FILLED MATRIX DECIMAL EQUIVALENT
1 4 4 100
Example 2:
INPUT:
M=3
N=4
ENTER ELEMENTS FOR ROW 1: 1 1 3 7
ENTER ELEMENTS FOR ROW 2: 2 1 0 6
ENTER ELEMENTS FOR ROW 3: 0 2 4 5
OUTPUT:
FILLED MATRIX DECIMAL EQUIVALENT
1 1 3 7 607
2 1 0 6 1094
0 2 4 5 165
Example 3:
INPUT:
M=3
N=3
ENTER ELEMENTS FOR ROW 1: 2 4 8
OUTPUT:
INVALID INPUT
Example 4:
INPUT:
M=4
N=6
46 | P a g e
OUTPUT:
OUT OF RANGE
Algorithm:
Input Matrix Dimensions:
Accept two integers, M (number of rows) and N (number of columns), from the user.
Check if M is in the range (0, 10) and N is in the range (2, 6):
o If M is not in range, print "OUT OF RANGE" and terminate.
o If N is not in range, print "OUT OF RANGE" and terminate.
Initialize the Matrix:
Create a 2D array arr of size M x N.
Input Elements for the Matrix:
Loop through each row i from 0 to M-1:
o Prompt the user to enter N integers for that row.
o Validate that each integer is between 0 and 7 (inclusive):
If any integer is outside this range, print "INVALID INPUT" and terminate.
Display the Matrix and Calculate Decimal Equivalents:
Print the header "FILLED MATRIX" and "DECIMAL EQUIVALENT".
For each row i, do the following:
o Print the elements of the row.
o Calculate the decimal equivalent.
o Print the calculated decimal equivalent.
Source Code:
import java.util.*;
class DeciEquivalent
{
private int arr[][];
private int M;
private int N;
private boolean readarray()
{
int f=0;
Scanner sc=new Scanner(System.in);
for(int i=0;i<M;i++)
{
System.out.print("ENTER ELEMENTS FOR ROW "+(i+1)+":");
for(int j=0;j<N;j++)
47 | P a g e
{
arr[i][j]=sc.nextInt();
if(arr[i][j]>=8)
return false;
}
}
return true;
}
private void calculate(int i)
{
int dec=0;
for(int j=0;j<N;j++)
dec+=(arr[i][j]*(int)Math.pow(8,(N-1-j)));
System.out.println(dec);
}
public void main()
{
int i,j;
Scanner sc=new Scanner(System.in);
System.out.print("M =");
M=sc.nextInt();
System.out.print("N =");
N=sc.nextInt();
arr=new int[M][N];
if(M==0 || M>=10|| N<=2 || N>=6)
System.out.println("OUT OF RANGE");
else if(readarray()==false)
System.out.println("INVALID INPUT");
else
{
System.out.println("FILLED MATRIX" +"\t"+" " +"DECIMAL EQUIVALENT");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
System.out.print(" "+arr[i][j]+" ");
System.out.print("\t"+"\t");
calculate(i);
48 | P a g e
}
}
}
}
Question 12:
Write a program to accept a sentence which may be terminated by either '.', '?' or '!'
only. The words are to be separated by a single blank space and are in UPPER CASE.
Perform the following tasks:
1.Check for the validity of the accepted sentence only for the terminating character.
49 | P a g e
2.Arrange the words in ascending order of their length. If two or more words have the
same length, then sort them alphabetically.
Test your program for the following data and some random data:
Example 1:
INPUT:
AS YOU SOW SO SHALL YOU REAP.
OUTPUT:
AS YOU SOW SO SHALL YOU REAP.
AS SO SOW YOU YOU REAP SHALL
Example 2:
INPUT:
SELF HELP IS THE BEST HELP.
OUTPUT:
SELF HELP IS THE BEST HELP.
IS THE BEST HELP HELP SELF
Example 3:
INPUT:
BE KIND TO OTHERS.
OUTPUT:
BE KIND TO OTHERS.
BE TO KIND OTHERS
Example 4:
INPUT:
50 | P a g e
NOTHING IS IMPOSSIBLE#
OUTPUT:
INVALID INPUT
Algorithm:
Input the Sentence:
Read a sentence from the user in uppercase letters.
2. Check Validity:
Verify that the last character of the sentence is either ., ?, or !.
If invalid, output "INVALID INPUT" and terminate.
3.Process the Sentence:
Remove the terminating character from the sentence.
Split the sentence into words using a space as a delimiter.
4.Sort the Words:
Sort the words by their lengths (ascending).
For words of the same length, sort them alphabetically.
Source Code:
import java.util.*;
class Ascending
{
private String sent;
51 | P a g e
public Ascending()
{
sent="";
}
52 | P a g e
a[j]=a[j+1];
a[j+1]=te;
}
}
}
for(int i=0;i<t.length;i++)
{
t[i]=a[i].length();
}
for(int i=0;i<t.length-1;i++)
{
for(int j=0;j<t.length-1-i;j++)
{
if(t[j]>t[j+1])
{
int temp=t[j];
String s=a[j];
a[j]=a[j+1];
a[j+1]=s;
t[j]=t[j+1];
t[j+1]=temp;
}
}
}
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
else
System.out.println("INVALID INPUT");
}}
Question 13:
Write a program to declare a matrix A[ ] [ ] of order (MXN) where ‘M’ is the number of
rows and ‘N’ is the number of columns such that the values of both ‘M’ and ‘N’ must be
greater than 2 and less than 10. Allow the user to input integers into this matrix.
Perform the following tasks on the matrix:
(a) Display the original matrix.
53 | P a g e
(b) Sort each row of the matrix in ascending order using any standard sorting
technique.
(c) Display the changed matrix after sorting each row.
Test your program for the following data and some random data:
Example 1:
INPUT: M = 4
N=3
ENTER ELEMENTS OF MATRIX
11 -2 3
5 16 7
9 0 4
3 1 8
OUTPUT:
ORIGINAL MATRIX
11 -2 3
5 16 7
9 0 4
3 1 8
MATRIX AFTER SORTING ROWS
-2 3 11
5 7 16
0 4 9
1 3 8
Example 2:
INPUT: M = 3
N=3
ENTER ELEMENTS OF MATRIX
22 5 19
7 36 12
9 13 6
OUTPUT:
ORIGINAL MATRIX
22 5 19
7 36 12
9 13 6
54 | P a g e
MATRIX SIZE OUT OF RANGE
Algorithm
Input:
o Prompt the user to enter the size of the matrix M.
Validation:
o Check if M is greater than 2 and less than 10.
If not, output "SIZE IS OUT OF RANGE" and terminate the program.
Matrix Declaration:
o Declare a square matrix A[M][M].
Input Matrix Elements:
o Prompt the user to input integers into the matrix, filling A[i][j] for i from 0 to M-1
and j from 0 to M-1.
Display the Original Matrix:
o Print the matrix in a formatted manner.
Check Symmetry:
o Initialize a boolean variable isSymmetric to true.
o Loop through the matrix:
For each element A[i][j], check if it is equal to A[j][i].
If any pair is not equal, set isSymmetric to false and break out of the loop.
o Output whether the matrix is symmetric or not based on the value of isSymmetric.
Calculate Diagonal Sums:
o Initialize two variables leftDiagonalSum and rightDiagonalSum to 0.
o Loop through the matrix to calculate:
leftDiagonalSum as the sum of elements where i == j.
rightDiagonalSum as the sum of elements where i + j == M - 1.
Source Code:
import java.util.*;
class Sort
{
private int a[][];
private int m;
private int n;
public Pro2(int mm,int nn)
{
m=mm;
n=nn;
a=new int[m][n];
}
55 | P a g e
public void read()
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER ELEMENTS OF MATRIX");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
}
public void sort()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n-1;j++)
{
for(int k=0;k<n-1-j;k++)
{
if(a[i][k]>a[i][k+1])
{
int t=a[i][k];
a[i][k]=a[i][k+1];
a[i][k+1]=t;
}
}
}} }
public void display()
{
System.out.println("ORIGINAL MATRIX");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
56 | P a g e
System.out.println();
}
System.out.println("MATRIX AFTER SORTING ROWS");
sort();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}}
Question 14:
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:
57 | P a g e
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
58 | P a g e
INPUT:
N = 10
OUTPUT:
INVALID INPUT
Algorithm
Input:
o Prompt the user to enter the number of teams N.
Validation:
o Check if N is within the range (2 < N < 9).
If not, output "INVALID INPUT" and terminate the program.
Team Name Storage:
o Create an array or list to store the names of the teams.
o For each team from 1 to N, prompt the user to enter the team name and
store it in the array.
Determine Maximum Length:
o Find the length of the longest team name to know how many rows are
needed for the display.
Display Teams Vertically:
o Use a loop that iterates up to the maximum length of the longest team
name.
For each index, loop through each team name:
Print the character at the current index if it exists; otherwise,
print a space.
After printing all teams for that index, add a horizontal tab (8
spaces) for separation.
Move to the next line after processing all teams for the current
index.
Source Code:
import java.util.*;
class Vertical_print
{
private String a[];
59 | P a g e
private int n;
public Pro3(int nn)
{
n=nn;
a=new String[n];
}
public void read()
{
Scanner sc = new Scanner(System.in);
for(int j=0;j<n;j++)
{
System.out.println("Team "+(j+1)+":");
a[j]=sc.nextLine();
}
}
public int big()
{
int k=a[0].length();
for(int i=0;i<n-1;i++)
{
if(a[i].length()<a[i+1].length())
k=a[i+1].length();
}
return k;
}
public void print()
{
int k=big();
for(int i=0;i<n;i++)
{
char c[]=new char[k];
for(int j=0;j<k;j++)
{
if(j<a[i].length())
c[j]=a[i].charAt(j);
else
c[j]=' ';
60 | P a g e
}
a[i]=String.valueOf(c);
}
for(int i=0;i<k;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[j].charAt(i)+" ");
System.out.println();
}
}
}
Question 15:
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
61 | P a g e
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:
INPUT:
m = 1200
n = 1300
OUTPUT:
Example 3:
INPUT:
m = 120
n = 99
62 | P a g e
OUTPUT:
INVALID INPUT
Algorithm
Define the Method:
o Create a method named findCompositeMagicNumbers(int m, int n).
Input Validation:
o Check if m is less than n and both are positive integers. If not, print "INVALID INPUT"
and terminate.
Initialize Variables:
o Create a list to store Composite Magic Numbers.
o Set a variable to count the frequency of Composite Magic Numbers.
Loop through Range:
o For each integer i from m to n (inclusive):
o Check if i is composite:
o If i is less than or equal to 1, it's not composite.
o For each integer j from 2 to the square root of i, check if i is divisible by j. If yes, it is
composite.
o Check if i is a magic number:
o Use a helper function to repeatedly sum the digits of i until a single digit is obtained.
If the result is 1, it is a magic number.
o If both conditions are met, add i to the list of Composite Magic Numbers and
increment the frequency count.
Output Results:
o Print the list of Composite Magic Numbers, separated by commas.
o Print the frequency of Composite Magic Numbers.
Source Code:
import java.util.*;
class Q1
{
public static int sumofdigits(int n)
63 | P a g e
{
int s=0;
while(n!=0)
{
s=s+n%10;
n=n/10;
}
return s;
}
public static int countofdigits(int n)
{
int c=0;
while(n!=0)
{
c++;
n=n/10;
}
return c;
}
public static void input()
{
int m,n;
Scanner sc = new Scanner(System.in);
System.out.println("M:");
m=sc.nextInt();
System.out.println("N:");
n=sc.nextInt();
if(m<100 || m>10000 || n>m)
System.out.println("Invalid input");
else
{
for(int i=m+1;;i++)
{
if(sumofdigits(i)==n)
{
System.out.println(i);
System.out.println("Total number of digits="+(countofdigits(i)));
64 | P a g e
break;
}
}
}
}
}
Question 16:
Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or ‘!’ only. Any
other character may be ignored. The words may be separated by more than one blank space and
are in UPPER CASE.
Perform the following tasks:
(a) Accept the sentence and reduce all the extra blank space between two words to
65 | P a g e
a single blank space.
(b) Accept a word from the user which is part of the sentence along with its
position number and delete the word and display the sentence.
Test your program with the sample data and some random data:
Example 1
INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
Example 3
INPUT: STUDY WELL ##.
OUTPUT: INVALID INPUT.
Algorithm:
Input Acceptance:
o Prompt the user to enter a sentence.
o Read the input sentence.
Input Validation:
o Check if the last character of the sentence is either ., ?, or !.
o If yes, proceed; if no, print "INVALID INPUT" and terminate.
2. Reduce Extra Spaces:
o Use a regular expression to split the sentence by one or more whitespace characters.
o Join the words back together with a single space.
3. Display Processed Sentence:
o Print the sentence after reducing extra spaces.
4. Count Vowels and Consonants:
o For each word in the processed sentence:
o Initialize counters for vowels (v) and consonants (c) to zero.
o For each character in the word:
o Check if it is a vowel (by comparing against a predefined list of vowels).
o Increment the respective counters.
o Print each word along with its vowel and consonant counts.
5. Word Deletion:
o Prompt the user for a word to delete and its position in the sentence.
66 | P a g e
o Convert the position to zero-based index.
o Check if the position is valid (within bounds of the words array).
o If valid, remove the word from the array.
o Join the remaining words and print the modified sentence.
o If invalid, print an error message
Source Code:
import java.util.*;
class Q3
{
private String sent;
public Q3()
{
Scanner sc = new Scanner(System.in);
System.out.println("Input:");
sent=sc.nextLine();
}
public void execute()
{
if(sent.charAt(sent.length()-1)=='.' || sent.charAt(sent.length()-1)=='?')
{
String a[]=sent.split("[\\s]+");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
System.out.println("Word Vowels Consonant ");
for(int i=0;i<a.length;i++)
{
int v=0,c=0;
for(int j=0;j<a[i].length();j++)
{
String h="aeiouAEIOU";
int f=0;
for(int p=0;p<h.length();p++)
{
if(a[i].charAt(j)==h.charAt(p))
{
f=1;
67 | P a g e
v++;
break;
}
}
if(f==0)
c++;
}
int y=a[i].length();
if(i==a.length-1)
{
c--;
y--;
}
System.out.print(Character.toUpperCase(a[i].charAt(0))
+""+a[i].substring(1,y));
for(int h=y;h<=9;h++)
System.out.print(" ");
System.out.print(" "+v);
System.out.println(" "+c);
}
}
else
{
System.out.println("Invalid Input");
}
}
}
Question 17
A Smith number is a composite number, the sum of whose digits is the sum of the digits of its
prime factors obtained as a result of prime factorization (excluding 1). The first few such numbers
are 4, 22, 27, 58, 85, 94, 121 ………………..
Example 1
1. 666
68 | P a g e
Prime factors are 2, 3, 3, and 37
Sum of the digits are (6+6+6) = 18
Sum of the digits of the factors (2+3+3+(3+7)) = 18
2. 4937775
Prime factors are 3, 5, 5, 65837
Write a program to input a number and display whether the number is a Smith number or not.
Sample data:
Input 94 Output SMITH Number
Input 102 Output NOT SMITH Number
Input 666 Output SMITH Number
Input 999 Output NOT SMITH Number
Algorithm :
Function to Check if a Number is Composite:
o If the number is less than 2, return false.
o Loop from 2 to the square root of the number:
If the number is divisible by any of these, return true (composite).
o If no divisors found, return false (not composite).
2. Function to Calculate Sum of Digits:
o Convert the number to a string.
o Sum the integer values of each character.
3. Function to Perform Prime Factorization:
o Initialize an empty list to store prime factors.
o Divide the number by each integer starting from 2 until the number is
reduced to 1:
If it divides evenly, add the factor to the list and continue dividing.
o Return the list of prime factors.
4. Main Function to Determine Smith Number:
o Input the number.
o Check if the number is composite using the composite check function.
o Calculate the sum of digits of the number.
o Get the prime factors using the prime factorization function.
69 | P a g e
o Calculate the sum of the digits of all the prime factors.
o Compare the two sums and print whether it is a Smith number or not.
Source Code:
import java.util.*;
public class Q11
{
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int n = in.nextInt();
if (n <= 0)
{
System.out.println(n + " is not a Smith Number.");
return;
}
boolean isComposite = false;
for (int i = 2; i < n; i++)
{
if (n % i == 0) {
isComposite = true;
break;
}
}
if (isComposite && n != 1)
{
int sumDigits = 0;
int t = n;
while (t != 0)
{
int d = t % 10;
sumDigits += d;
t /= 10;
}
int sumPrimeDigits = 0;
t = n;
70 | P a g e
for(int i = 2; i < t; i++)
{
while(t % i == 0)
{
t /= i;
int temp = i;
while (temp != 0)
{
int d = temp % 10;
sumPrimeDigits += d;
temp /= 10;
}
}
}
if(t > 2)
{
while (t != 0)
{
int d = t % 10;
sumPrimeDigits += d;
t /= 10;
}
}
if (sumPrimeDigits == sumDigits)
System.out.println(n + " is a Smith Number.");
else
System.out.println(n + " is not a Smith Number.");
}
else
{
System.out.println(n + " is not a Smith Number.");
}}}
Question 18
A sentence is terminated by either “.”, or “?” followed by a space. Input a piece of text consisting
of sentences. Assume that there will be a maximum of 10 sentences in block letters.
71 | P a g e
Write a program to:
(i) Obtain the length of the sentence (measured in words) and the frequency of vowels in each
sentence
(ii) Generate the output as shown below using the given data
Sample Data:
INPUT
OUTPUT
——————————————————
1 VVVVVV
WWW
2 VVVVVVVVVVVVVVV
WWWWWWWWW
3 VVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWW
4 VVVVVVVVVVV
WWWWWWWWWWW
72 | P a g e
Algorithm
Input the Text:
Read a block of text containing sentences.
Split Sentences:
Identify sentences by splitting the text on ". " or "? " (ensuring to handle
cases where sentences might end at the end of the string).
Initialize Data Structures:
Create lists to store the number of vowels and the number of words for
each sentence.
Process Each Sentence:
o For each sentence:
Count the number of words by splitting the sentence on whitespace.
Count the number of vowels (A, E, I, O, U) in the sentence.
Format the Output:
Create the required output format showing the sentence number, number
of vowels, number of words, and a visual representation of the counts.
Print the Results:
Display the output in the specified format.
Source Code:
class Q12
{
private static int countsentences(String ss)
{
int p=0;
for(int i=0;i<ss.length();i++)
{
if(ss.charAt(i)=='.' || ss.charAt(i)=='?' || ss.charAt(i)=='!')
{
p++;
}
}
return p;
}
private static int countwords(String s)
{
73 | P a g e
StringTokenizer st = new StringTokenizer(s," ");
int p = st.countTokens();
return p;
}
private static int countvowels(String s)
{
int i,v=0;
for(i=0;i<s.length();i++)
{
if(s.charAt(i)=='a' || s.charAt(i)=='A' || s.charAt(i)=='e' || s.charAt(i)=='E' ||
s.charAt(i)=='i' || s.charAt(i)=='I' || s.charAt(i)=='o' || s.charAt(i)=='O' || s.charAt(i)=='u'
|| s.charAt(i)=='U')
{
v++;
}
}
return v;
}
private static void display(int n,char c)
{
for(int i = 1;i<=(n*3);i++)
{
System.out.print(c);
}
}
public static void main(String args[])
{
String str;
int c=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter a Sentence : ");
str = s.nextLine();
String n="";
int count = countsentences(str);
String word[] = new String[count];
word[0] = "";
for(int i=0;i<str.length();i++)
74 | P a g e
{
if(str.charAt(i)=='.' || str.charAt(i)=='?' || str.charAt(i)=='!')
{
word[c++] = n.trim();
n = "";
}
else
{
n=n+str.charAt(i);
}
}
System.out.println("Sentence\tNo. of Vowels\tNo. of words");
for(int i=0;i<c;i++)
{
System.out.println((i+1) + "\t\t"+countvowels(word[i])+"\t\
t"+countwords(word[i]));
}
System.out.println("\nSentence No. of words/vowels");
System.out.println("-------------------------------");
for(int i=0;i<c;i++)
{
System.out.print((i+1)+"\t\t\t");
display(countvowels(word[i]),'V');
System.out.print("\n\t\t\t");
display(countwords(word[i]),'W');
System.out.println();
}
System.out.println("-------------------------------");
}
}
Question 19
Given a square matrix list [ ] [ ] of order ‘n’. The maximum value possible for ‘n’ is 20. Input the
value for ‘n’ and the positive integers in the matrix and perform the following tasks:
75 | P a g e
Display the original matrix
1.Print the row and column position of the largest element of the matrix
2.Print the row and column position of the second largest element of the matrix
3.Sort the elements of the rows in the ascending order and display the new matrix
Sample Data:
INPUT:
N=3
LIST [ ] [ ]
5 1 3
7 4 6
9 8 2
OUTPUT
5 1 3
7 4 6
9 8 2
Sorted list
1 3 5
4 6 7
2 8 9
Algorithm
Input the Size of the Matrix:
o Read the integer nnn (the order of the matrix).
76 | P a g e
o Ensure nnn is between 1 and 20.
Input the Matrix Elements:
o Create a square matrix of size n×nn \times nn×n.
o Read positive integers to fill the matrix.
Display the Original Matrix:
o Print the matrix in a formatted manner.
Find the Largest and Second Largest Elements:
o Initialize two variables to store the largest and second largest values along
with their positions.
o Iterate through each element in the matrix:
If an element is greater than the largest, update both the largest and
second largest values and their positions.
If an element is between the largest and second largest, update the
second largest value and its position.
Sort Each Row in Ascending Order:
o Iterate through each row of the matrix and sort it.
Display the Sorted Matrix:
o Print the newly sorted matrix.
Source Code:
import java.util.*;
class Q13
{
private int a[][];
private int n;
public void main()
{
read();
int b=0,sb=0,r1=0,c1=0,r2=0,c2=0;
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
if(b<a[i][j])
{
b=a[i][j];
r1=i;c1=j;
77 | P a g e
}
else if(sb<a[i][j])
{
sb=a[i][j];
r2=i;c2=j;
}
}
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println("The largest element "+b+" is in row "+(r1+1)+" and column "+
(c1+1));
System.out.println("The second largest element "+sb+" is in row "+(r2+1)+" and
column "+(c2+1));
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1;j++)
{
for(int k=0;k<n-1-j;k++)
{
if(a[i][k]>a[i][k+1])
{
int l=a[i][k+1];
a[i][k+1]=a[i][k];
a[i][k]=l;
}
}
}
}
System.out.println("Sorted List");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
78 | P a g e
System.out.print(a[i][j]+" ");
System.out.println();
}
}
Question 20:
Hamming numbers are positive integer numbers whose prime factors include 2,3 and 5 only
Example:
n=6 is an hamming number as 6=2x3 .So its prime factors are limited to 2 ,3
79 | P a g e
n=8 is an hamming number as 8=2x2x2 and it has only 2 as its prime factors
n=90 is an hamming number as 90=2x3x3x5 which has only 2,3,5 as prime factors
n=14 is not a hamming number as 14=2x7 .It has 7 as one of its prime factor
n=44 is not a hamming number as 44=2x2x11. It has 11 as one of its prime factors
Design a program to accept any positive integer number and check if it is a Hamming number or
not. Display the result with an appropriate message in the format specified below. The program
should also generate error message if a negative number is entered.
Test your program for the following data and some random data.
Example 1
INPUT: Enter any number: 3600
OUTPUT: 3600= 2 x 2 x 2 x 2 x 3 x 3 x 5 x 5
3600 IS A HAMMING NUMBER
Example 2
INPUT: Enter any number: 5832
OUTPUT: 5832= 2 x 2 x 2 x 3 x 3 x 3 x 3 x 3 x 3
5832 IS A HAMMING NUMBER
Example 3
INPUT: Enter any number: 7854
OUTPUT: 7854= 2 x 3 x 7 x 11 x 17
7854 IS NOT A HAMMING NUMBER
Example 4
INPUT: Enter a number: -120
OUTPUT: NEGATIVE NUMBER ENTERED. INVALID INPUT
Algorithm
Input:
Prompt the user to enter a positive integer.
Read the input and try to convert it to an integer.
If the input is not a valid integer, display an error message: "INVALID INPUT.
PLEASE ENTER A POSITIVE INTEGER."
If the number is negative, display: "NEGATIVE NUMBER ENTERED. INVALID
INPUT."
Prime Factorization:
Initialize an empty list factors to store the prime factors of the number.
Store the original value of the number in a variable original_n.
Check for factors of 2:
While n is divisible by 2, append 2 to the factors list and divide n by 2.
Check for factors of 3:
While n is divisible by 3, append 3 to the factors list and divide n by 3.
Check for factors of 5:
While n is divisible by 5, append 5 to the factors list and divide n by 5.
80 | P a g e
Check for Hamming Number:
Source Code:
import java.util.*;
class Program1
{
public static boolean isprime(int n)
{
if(n<=1)
{
return false;
}
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
else
{
String g="";
int f=1;
int t = n;
for(int i = 2;i<=n;i++)
{
if(isprime(i)==true && n%i==0)
{
g = g+i+" x ";
if(i==2 || i==3 || i==5)
{
f = f * i;
}
n = n /i;
i=1;
}
}
if(t==f)
{
System.out.println(t + " = " + g.substring(0,g.length()-2));
System.out.println(t + " IS A HAMMING NUMBER");
}
else
{
System.out.println(t + " = " + g.substring(0,g.length()-2));
System.out.println(t + " IS NOT A HAMMING NUMBER");
}}}}
Question 21:
Write a program to declare a square matrix M[][] of order ‘N’. Check if the matrix is a Doubly
Markov matrix or not. A matrix which satisfies the following conditions are Doubly Markov matrix
(i) All elements are greater than or equal to 0
(ii) Sum of each row is equal to 1.
(iii) Sum of each column is equal to 1.
82 | P a g e
Accept ‘N’ from the user where 3 <= N <= 9. Display an appropriate error message if ‘N’ is not in
the given range or the entered numbers are negative. Allow the user to create a matrix and check
whether the created matrix is a Doubly Markov matrix or not
Test your program for the following data and some random data:
Example 1
INPUT: N=3
Enter elements in the matrix: 0.5, 0.25, 0.25, 0.25, 0.75, 0.0, 0.25, 0.0, 0.75
OUTPUT: FORMED MATRIX
0.5 0.25 0.25
0.25 0.75 0.0
0.25 0.0 0.75
IT IS A DOUBLY MARKOV MATRIX
Example 2
INPUT: N=3
Enter elements in the matrix: 1.5, 3, 0.15, 0.25, 4, 1.0, 0.25, 1.0, 3
OUTPUT: FORMED MATRIX
1.5 3 0.15
0.25 4 1.0
0.25 1.0 3
Algorithm:
Input Handling:
83 | P a g e
Traverse the matrix M to check if any element is negative.
If any negative element is found, display "NEGATIVE NUMBERS ENTERED. INVALID ENTRY"
and terminate the program.
Check Rows and Columns:
Source Code:
import java.util.*;
class Program2
{
public static void main()
{
Scanner s = new Scanner(System.in);
System.out.print("N = ");
int n = s.nextInt();
if(n>=3 && n<=9)
{
int f = 0;
double arr[][] = new double[n][n];
System.out.println("Enter elements in the matrix : ");
for(int i = 0;i<n;i++)
84 | P a g e
{
for(int j=0;j<n;j++)
{
arr[i][j] = s.nextDouble();
if(arr[i][j]<0)
{
f=1;
}
}
}
if(f==1)
{
System.out.println("NEGATIVE NUMBERS ENTERED. INVALID ENTRY");
}
else
{
double row=0.0,col=0.0,k=0;
for(int i = 0;i<n;i++)
{
for(int j=0;j<n;j++)
{
row = row+arr[i][j];
col = col+arr[j][i];
}
if(row == 1.0 && col==1.0)
{
row = 0.0;
col = 0.0;
}
else
{
k=1;
break;
}
}
for(int i = 0;i<n;i++)
{
85 | P a g e
for(int j=0;j<n;j++)
{
System.out.printf("%.2f ",arr[i][j]);
}
System.out.println();
}
if(k==0)
{
System.out.println("IT IS A DOUBLE MARKOV MATRIX");
}
else
{
System.out.println("IT IS NOT A DOUBLE MARKOV MATRIX");
}
}
}
else
{
System.out.println("SIZE OUT OF RANGE. INVALID ENTRY");
}}}
Question 22:
A snowball string is a sentence where each word is arranged in ascending order of their length and is
also consecutive.
For example “I am the Lord” is a snowball string as
Length of word ‘I’ is 1
Length of word ‘am’ is 2
Length of word ‘the’ is 3
86 | P a g e
Length of word ‘Lord’ is 4
The length of each word is one more than the previous word. Hence they are consecutive and in
ascending order.
Write a program to enter any sentence and check if it is a snowball string or not. The words in the
sentence may be separated by a one or more spaces and terminated by ‘.’ or ‘?’ only. The program
will generate appropriate error message for any other terminating character.
Test your program for the following data and some random data:
Example 1
INPUT: He may give bonus.
OUTPUT: IT IS A SNOWBALL STRING
Example 2
INPUT: Is the cold water frozen?
OUTPUT: IT IS A SNOWBALL STRING
Example 3
INPUT: Look before you leap.
OUTPUT: IT IS NOT A SNOWBALL STRING
Example 4
INPUT: The child is father of the man!
OUTPUT: INCORRECT TERMINATING CHARACTER. INVALID INPUT
Algorithm
Input:
Prompt the user to enter a sentence.
Check the last character of the sentence:
If the last character is not . or ?, display "INCORRECT TERMINATING CHARACTER. INVALID
INPUT" and terminate the program.
Remove the Terminator:
Remove the terminating character (either . or ?) from the end of the sentence.
87 | P a g e
Source Code:
import java.util.Scanner;
class Program3
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence terminated by '.' or '?': ");
String sentence = scanner.nextLine();
// Check if the sentence ends with '.' or '?'
char lastChar = sentence.charAt(sentence.length() - 1);
if (lastChar != '.' && lastChar != '?')
{
System.out.println("INCORRECT TERMINATING CHARACTER. INVALID INPUT");
}
else if (isSnowballString(sentence))
{
System.out.println("IT IS A SNOWBALL STRING");
}
else
{
System.out.println("IT IS NOT A SNOWBALL STRING");
}
}
88 | P a g e
if (currentLength < prevLength || currentLength != prevLength + 1)
{
return false;
}
prevLength = currentLength;
}
return true;
}
}
Question 23:
An Evil number is a positive whole number which has even number of 1’s in its binary
equivalent.
Example: Binary equivalent of 9 is 1001, which contains even number of 1’s.
A few evil numbers are 3, 5, 6, 9....
Design a program to accept a positive whole number and find the binary equivalent of
the number and
89 | P a g e
count the number of 1’s in it and display whether it is a Evil number or not with an
appropriate
message. Output the result in format given below:
Example 1
INPUT : 15
BINARY EQUIVALENT : 1111
NO. OF 1’s : 4
OUTPUT : EVIL NUMBER
Example 2
INPUT : 26
BINARY EQUIVALENT : 11010
NO. OF 1’s : 3
OUTPUT : NOT AN EVIL NUMBER
Algorithm
Input:
Prompt the user to enter a positive whole number.
Read the input and check if it is a valid positive integer.
If the input is invalid (e.g., negative or not an integer), display an appropriate error
message and terminate the program.
Convert the number to its binary equivalent using a suitable method (e.g., using built-in
functions).
Count the Number of 1's:
Source Code:
90 | P a g e
import java.util.*;
class Evilnumber
{
private int num;
private int count=0;
Evilnumber()
{
num=0;
}
void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("INPUT: ");
num=sc.nextInt();
}
int bin_convert(int n)
{
if(n==0)
return 0;
else{
int t = n%2;
return bin_convert(n/2)*10+t;
}
}
boolean check()
{
int no = bin_convert(num);
int c = 0;
while(no!=0)
{
int rem = no%10;
if(rem==1)
c++;
no = no/10;
91 | P a g e
}
count = c;
if(c%2==0)
return true;
return false;
}
void display()
{
boolean f = check();
System.out.println("BINARY EQUIVALENT: "+bin_convert(num));
System.out.println("NO. OF 1’s: "+count);
if(f==true)
System.out.println("OUTPUT: EVIL NUMBER");
else
System.out.println("OUTPUT: NOT AN EVIL NUMBER");
}
}
Question 24:
A prime palindrome integer is a positive integer (without leading zeros) 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:
92 | P a g e
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, 797, 919, 929
FREQUENCY OF PRIME PALINDROME INTEGERS : 15
Example 2
INPUT: m = 100
n = 5000
OUTPUT: OUT OF RANGE
Algorithm
Input:
Prompt the user to enter two positive integers m and n.
Check if m < n, and if both m and n are less than 3000.
If not, display "OUT OF RANGE" and terminate the program.
Prime Check Function:
Define a function is_prime(num) that returns True if num is a prime number:
If num is less than 2, return False.
For each integer i from 2 to the square root of num, check if num is divisible by i.
If divisible, return False. Otherwise, return True.
Palindrome Check Function:
Source Code:
class PrimePalin
93 | P a g e
{
private int m,n;
public void input(int mm,int nn)
{
if(mm>=3000 && nn>=3000)
{
System.out.print("OUT OF RANGE");
return;
}
m=mm;
n=nn;
}
public boolean isPrime(int n)
{
if(n<0)
return false;
for(int i=2;i<=n/2;i++)
if(n%i==0)
return false;
return true;
}
public boolean isPalin(int n)
{
int t=n,p=0;
while(t!=0)
{
p=(p*10)+(t%10);
t/=10;
}
return (p==n)?true:false;
}
public void print()
{
for(int i=m;i<=n;i++)
if(isPrime(i)==true && isPalin(i)==true)
System.out.print(i +" ");
}
94 | P a g e
}
Question 25:
Write a program to accept a sentence as input. The words in the string are to be
separated by a blank. Each word must be in upper case. The sentence is terminated by
either “.”,”!” or “?”. Perform the following tasks:
(i) Obtain the length of the sentence (measured in words).
(ii) Arrange the sentence in alphabetical order of the words.
Test your program with the sample data and some random data:
Example 1
95 | P a g e
INPUT:
NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT:
LENGTH : 6
REARRANGED SENTENCE
INVENTION IS MOTHER NECESSITY OF THE
Example 2
INPUT:
BE GOOD TO OTHERS.
OUTPUT:
LENGTH : 4
REARRANGED SENTENCE
BE GOOD OTHERS TO
Algorithm
Input the Sentence:
o Read the sentence from the user. Ensure the sentence is in uppercase and
ends with one of the specified punctuation marks (".", "!", "?").
Remove the Punctuation:
o Trim the terminating punctuation from the sentence for further
processing.
Split the Sentence into Words:
o Split the sentence into words based on spaces.
Calculate the Length:
o Count the number of words in the list.
Sort the Words:
o Sort the list of words in alphabetical order.
Format and Display the Output:
o Print the length of the sentence and the rearranged sentence.
Source Code:
import java.util.*;
class Arrange
{
private String s;
public Arrange()
{
s="";
96 | P a g e
}
public void input()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the sentence: ");
s=sc.nextLine();
}
public int obtainLength()
{
return s.split("[\\s]+").length;
}
public void sort()
{
String d[]=s.split("[\\s]+");
for(int i=0;i<d.length;i++)
if(d[i].endsWith(".") || d[i].endsWith("!") || d[i].endsWith("?"))
d[i]=d[i].substring(0,d[i].length()-1);
for(int i=0;i<d.length-1;i++)
for(int j=0;j<d.length-1-i;j++)
if(d[j].compareTo(d[j+1])>0)
{
String t=d[j];
d[j]=d[j+1];
d[j+1]=t;
}
for(int i=0;i<d.length;i++)
System.out.print(d[i] +" ");
}
public void display()
{
System.out.println("LENGTH: " +obtainLength());
System.out.println("REARRANGED SENTENCE");
sort();
}
}
97 | P a g e
Question 26:
An ISBN (International Standard Book Number) is a ten digit code which uniquely
identifies a book.
The first nine digits represent the Group, Publisher and Title of the book and the last
digit is used to check whether ISBN is correct or not.
Each of the first nine digits of the code can take a value between 0 and 9. Sometimes it
is necessary to make the last digit equal to ten; this is done by writing the last digit of
the code as X.
98 | P a g e
To verify an ISBN, calculate 10 times the first digit, plus 9 times the second digit, plus 8
times the third and so on until we add 1 time the last digit. If the final number leaves no
remainder when divided by 11, the code is a valid ISBN.
For Example:
1. 0201103311 = 10*0 + 9*2 + 8*0 + 7*1 + 6*1 + 5*0 + 4*3 + 3*3 + 2*1 + 1*1 = 55
Since 55 leaves no remainder when divided by 11, hence it is a valid ISBN.
2. 007462542X = 10*0 + 9*0 + 8*7 + 7*4 + 6*6 + 5*2 + 4*5 + 3*4 + 2*2 + 1*10 = 176
Since 176 leaves no remainder when divided by 11, hence it is a valid ISBN.
3. 0112112425 = 10*0 + 9*1 + 8*1 + 7*2 + 6*1 + 5*1 + 4*1 + 3*4 + 2*2 + 1*5 = 71
Since 71 leaves no remainder when divided by 11, hence it is not a valid ISBN.
Design a program to accept a ten digit code from the user. For an invalid input, display
an appropriate message. Verify the code for its validity in the format specified below:
Test your program with the sample data and some random data:
Example 1
INPUT CODE: 0201530821
OUTPUT : SUM = 99
LEAVES NO REMAINDER – VALID ISBN CODE
Example 2
INPUT CODE: 035680324
OUTPUT : INVALID INPUT
Example 3
INPUT CODE: 0231428031
OUTPUT : SUM = 122
LEAVES REMAINDER – INVALID ISBN CODE
Algorithm
Input the ISBN Code:
o Read the input from the user.
Validate the Input:
o Check if the input is exactly 10 characters long.
o Ensure the first nine characters are digits (0-9).
o Check if the last character is either a digit (0-9) or 'X'.
Calculate the Weighted Sum:
o Initialize a variable for the total sum.
o Iterate over the first 9 digits, multiplying each digit by its weight (10 for the first, 9
for the second, etc.).
o If the last character is 'X', add 10 to the sum; otherwise, add the numeric value of
the last digit.
Check Validity:
99 | P a g e
o Determine if the calculated sum is divisible by 11.
o Print the appropriate message based on the validity check:
If divisible, print the sum and indicate it's a valid ISBN.
If not divisible, print the sum and indicate it's an invalid ISBN.
Source Code:
import java.util.*;
class ISBN
{
public static void main()
{
String s="";
Scanner sc=new Scanner(System.in);
System.out.print("Enter a 10 digit code: ");
s=sc.nextLine();
if(s.length()<10 || s.length()>10)
System.out.println("INVALID INPUT");
else
{
int sum=0;
String c;
int m=10;
int a;
for(int i=0;i<s.length();i++)
{
c=Character.toString(s.charAt(i));
if(c.equalsIgnoreCase("X"))
a=10;
else
a=Integer.parseInt(c);
sum=sum+a*m;
m--;
}
if(sum%11==0)
{
System.out.println("SUM ="+sum);
System.out.println("LEAVES NO REMAINDER-VALID ISBN CODE");
}
100 | P a g e
else
{
System.out.println("SUM ="+sum);
System.out.println("LEAVES REMAINDER-INVALID ISBN CODE");
}
}
}
}
Question 27:
Write a program to declare a square matrix A[ ] [ ] of order (M x M) where ‘M’ is the number of
rows and the number of columns such that M must be greater than 2 and less than 20. Allow the
user to input integers into this matrix. Display appropriate error message for an invalid input.
Perform the following tasks:
(a) Display the input matrix.
(b) Create a mirror image matrix.
(c) Display the mirror image matrix.
Test your program with the sample data and some random data:
Example 1
101 | P a g e
INPUT : M = 3
4 16 12
8 2 14
4 1 3
OUTPUT :
ORIGINAL MATRIX
4 16 12
8 2 14
4 1 3
MIRROR IMAGE MATRIX
12 16 4
14 2 8
3 1 4
Example 2
INPUT : M = 22
OUTPUT : SIZE OUT OF RANGE
Algorithm
Input the Size of the Matrix (M):
o Prompt the user to enter an integer for M.
o Validate that M is greater than 2 and less than 20.
o If invalid, print an error message and exit.
Input the Matrix Elements:
o Initialize a square matrix of size MxM.
o Prompt the user to enter integers for each element of the matrix.
o Store the input values in the matrix.
Display the Original Matrix:
o Print the matrix in a formatted way.
Create the Mirror Image Matrix:
o Initialize a new matrix for the mirror image.
o For each element in the original matrix, assign it to the corresponding
position in the mirror image matrix (mirroring horizontally).
Display the Mirror Image Matrix:
o Print the mirror image matrix in a formatted way.
Source Code:
import java.util.*;
class Mirror
{
102 | P a g e
public static void main()
{
int arr[][];
int M;
Scanner sc=new Scanner(System.in);
System.out.print("M =");
M=sc.nextInt();
arr=new int[M][M];
if(M<2 || M>20)
System.out.println("SIZE OUT OF RANGE");
else
{
System.out.println("ENTER ELEMENTS FOR A "+(M)+"X"+(M)+" MATRIX");
for(int i=0;i<M;i++)
{
for(int j=0;j<M;j++)
arr[i][j]=sc.nextInt();
}
int a[][]=new int[M][M];
for(int i=0;i<M;i++)
{
int c=0;
for(int j=M-1;j>=0;j--)
a[i][c++]=arr[i][j];
}
System.out.println("ORIGINAL MATRIX");
for(int i=0;i<M;i++)
{
for(int j=0;j<M;j++)
System.out.print(arr[i][j]+"\t");
System.out.println();
}
System.out.println("MIRROR IMAGE MATRIX");
for(int i=0;i<M;i++)
{
for(int j=0;j<M;j++)
System.out.print(a[i][j]+"\t");
103 | P a g e
System.out.println();
}
}
}
}
Question 28:
A Palindrome is a word that may be read the same way in either direction.
Accept a sentence in UPPER CASE which is terminated by either ” . “, ” ? ” or ” ! “.
Each word of the sentence is separated by a single blank space.
Perform the following tasks:
(a) Display the count of palindromic words in the sentence.
(b) Display the Palindromic words in the sentence.
Example of palindromic words: MADAM, ARORA, NOON
Test your program with the sample data and some random data:
104 | P a g e
Example 1
INPUT : MOM AND DAD ARE COMING AT NOON.
OUTPUT : MOM DAD NOON
NUMBER OF PALINDROMIC WORDS : 3
Example 2
INPUT : NITIN ARORA USES LIRIL SOAP.
OUTPUT : NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS : 3
Example 3
INPUT : HOW ARE YOU?
OUTPUT : NO PALINDROMIC WORDS
Algorithm
Input the Sentence:
o Read a sentence from the user, ensuring it is in uppercase and ends with
one of the specified punctuation marks (".", "?", "!").
Remove the Punctuation:
o Trim the terminating punctuation from the sentence for processing.
Split the Sentence into Words:
o Split the sentence into individual words based on spaces.
Check for Palindromic Words:
o Initialize a list to store palindromic words.
o For each word in the list:
Check if the word is the same when reversed.
If it is, add it to the list of palindromic words.
Display the Results:
o Print the palindromic words and the total count.
o If there are no palindromic words, print a specific message.
Source Code:
import java.util.*;
class Palindrome
{
private static boolean palindrome(String k)
{
105 | P a g e
for(int i=0;i<k.length()/2;i++)
{
if(k.charAt(i)!=k.charAt(k.length()-1-i))
return false;
}
return true;
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER A SENTENCE:");
String sent=sc.nextLine().toUpperCase();
int k;
int c=0;
int f=0;
for(k=0;k<sent.length();k++)
{
if(sent.charAt(k)=='.' ||sent.charAt(k)=='?'||sent.charAt(k)=='!' )
{
f=1;
break;
}
}
System.out.println("OUTPUT:");
if(f==1)
{
sent=sent.substring(0,k);
String a[]=sent.split("[\\s]+");
for(int i=0;i<a.length;i++)
{
if(palindrome(a[i])==true)
{
System.out.print(a[i]+" ");
c++;
}
}
if(c==0)
106 | P a g e
System.out.println("NO PALINDROMIC WORDS");
else
{
System.out.println();
System.out.println("NUMBER OF PALINDROMIC WORDS:"+c);
}
}
else
System.out.println("INVALID INPUT");
}
}
Question 29:
company manufactures packing cartons in four sizes, i.e. cartons to accommodate 6
boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to accept the number of
boxes to be packed (N) by the user (maximum up to 1000 boxes) and display the break-
up of the cartons used in descending order of capacity (i.e. preference should be given
to the highest capacity available, and if boxes left are less than 6, an extra carton of
capacity 6 should be used.) Test your program with the following data and some
random data:
107 | P a g e
Example 1:
INPUT: N = 726 48 * 15 = 720
OUTPUT: Remaining boxes 6x16 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 Remaining boxes 6 * 1 = 6 2 * 1 = 2 Total
number of boxes -140 Total number of cartons 6 Example 3 INPUT: N = 4296 OUTPUT:
INVALID INPUT
Algorithm:
Input:
Read an integer n from the user representing the number of boxes.
Validation:
If n is greater than 1000, print "INVALID INPUT" and terminate.
Initialize:
Store the initial value of n in a variable c (for total boxes).
Initialize a variable nfc to 0 (for total cartoons).
Calculation Loop:
While n is greater than 5:
o If n is between 6 and 11 (inclusive):
Calculate r as n / 6 (integer division).
Calculate k as 6 * r.
Call the display function with parameters 6, r, and k.
Add r to nfc and subtract k from n.
o If n is between 12 and 23 (inclusive):
Calculate r as n / 12.
Calculate k as 12 * r.
Call the display function with parameters 12, r, and k.
Add r to nfc and subtract k from n.
o If n is between 24 and 47 (inclusive):
Calculate r as n / 24.
Calculate k as 24 * r.
Call the display function with parameters 24, r, and k.
Add r to nfc and subtract k from n.
o If n is 48 or more:
Calculate r as n / 48.
108 | P a g e
Calculate k as 48 * r.
Call the display function with parameters 48, r, and k.
Add r to nfc and subtract k from n.
Display Remaining Boxes:
Call the suplementry_display function to show:
o Remaining boxes left (if any).
o Total number of boxes (c).
o Total number of cartoons (nfc).
End: The program finishes after displaying the results.
Source Code:
import java.util.Scanner;
class cartoons
{
private int n;
private int nfc;
private int c;
public cartoons(int n)
{
this.n = n;
c = n;
nfc = 0;
}
109 | P a g e
else if(n>=12 && n<24)
{
int r = n/12;
int k = 12*r;
display(12,r,k);
nfc+=r;
n-=k;
}
else if(n>=24 && n<48)
{
int r = n/24;
int k = 24*r;
display(24,r,k);
nfc+=r;
n-=k;
}
else if(n>=48)
{
int r = n/48;
int k = 48*r;
display(48,r,k);
// System.out.println(48 + " x " + r + " = " + k);
nfc+=r;
n-=k;
}
}
}
110 | P a g e
{
if(n==0)
{
System.out.print("Remaining boxes");
System.out.printf("%28s "," = "+n);
System.out.println();
System.out.print("Total number of boxes");
System.out.printf("%24s "," = " + c);
System.out.println();
System.out.print("Total number of cartoons");
System.out.printf("%20s "," = " + nfc);
System.out.println();
}
else
{
System.out.printf("Remaining boxes");
System.out.printf("%28s ",n + " x " + 1 + " = " + n);
System.out.println();
System.out.print("Total number of boxes");
System.out.printf("%24s "," = " + c);
System.out.println();
System.out.print("Total number of cartoons");
System.out.printf("%19s "," = " + (nfc+1));
System.out.println();
}
}
111 | P a g e
a.suplementry_display();
}
else
{
System.out.println("INVALID INPUT");
}
}
}
Question 30:
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 participant(s)
having the highest score.
Example: If the value of N 4, then the array would be:
112 | P a g e
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 DABCC
Participant 2 AADCB
Participant 3 BACDB
Participant 4 DADCB
Participant 5 B CADD
Key: BCDAA
OUTPUT:
Scores:
Participant 1=0
Participant 2 = 1
Participant 3 = 1
Participant 4 = 1
Participant 5 = 2
Highest score: Participant 5
Example 2:
INPUT:
N=4
Participant 1 ACCBD
Participant 2 BCAAC
Participant 3 BСВАА
Participant 4 CCDDB
Key: ACDBB
OUTPUT:
113 | P a g e
Scores:
Participant 1 = 3
Participant 2 = 1
Participant 3 = 1
Participant 4 = 3
Highest score: Participant 1
Participant 4
Algorithm:
Initialization:
Define a quiz class that contains:
o A 2D array q for storing participants' answers.
o A 1D array key for storing the correct answers.
o An array scores for tracking scores of participants.
o A variable k to hold the number of participants.
Constructor:
Accepts an integer n (number of participants) and initializes:
o q as a 2D array of size n x 5 (assuming 5 questions).
o key as a 1D array of size 5.
o scores as a 1D array of size n.
o A string array n for participant names (though this name might be confusing since it
also holds answers).
Input Method:
Use Scanner to read input from the console.
For each participant:
o Print a prompt.
o Read a line of input, split by whitespace, and store it in q[i] (the participant's
answers).
Read the correct answers and store them in key.
Calculate Scores Method:
Loop through each question index (0 to 4):
o For each question, compare each participant's answer with the correct answer in
key.
o If the answer matches, increment the corresponding participant's score in scores.
114 | P a g e
Create a Scanner for user input.
Prompt for the number of participants and instantiate the quiz object.
Call the input, calculate, and display methods in sequence.
Source Code:
import java.util.Scanner;
class quiz
{
public String q[][];
public String key[];
private String n[];
private int scores[];
int k;
public quiz(int n)
{
k = n;
q = new String[n][5];
key = new String[5];
scores = new int [n];
this.n = new String[n];
}
String k = sc.nextLine();
n = k.split("[\\s]+");
for(int j = 0;j<n.length;j++)
{
q[i][j] = n[j];
}
}
System.out.println("Key: ");
115 | P a g e
key = sc.nextLine().split("[\\s]+");
}
116 | P a g e
}
117 | P a g e
Question 31:
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.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:
RIOT13
118 | P a g e
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
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 gngn.
Example 3:
INPUT: You OUTPUT: INVALID LENGTH
Algorithm:
Class Definition:
Define a class Riot13 with two private string attributes a (input text) and b (encoded
text).
Constructor:
Accept a string a as input and initialize the class attribute a with this value.
Encoding Method:
Create a method encode that processes each character in the input string a:
o Loop through each character in a:
If the character is a letter:
If the character is in the range A-M (uppercase) or a-m
(lowercase), add 13 to its ASCII value and append the resulting
character to b.
If the character is in the range N-Z (uppercase) or n-z (lowercase),
subtract 13 from its ASCII value and append the resulting
character to b.
If the character is not a letter, append it directly to b without
modification.
Display Method:
Create a method display to print the encoded string b.
Main Method:
In the main method:
o Create a Scanner object to read input from the console.
o Read a string m from the input.
o Check if the length of m is between 4 and 99 (inclusive):
119 | P a g e
If valid, instantiate a Riot13 object with m, call the encode method, and
then call the display method.
If invalid, print "INVALID LENGTH".
Source Code:
import java.util.Scanner;
class Riot13
{
private String a = "";
private String b = "";
public Riot13(String a)
{
this.a = a;
}
120 | P a g e
}
Question 32:
A new advanced Operating System, incorporating the latest hi-tech features has been designed by
Opera Computer System.
The task of generating copy protection codes to prevent software piracy has been entrusted to the
Security Department.
The security department has decided to have codes containing a jumbled combination of
alternate uppercase letters of the alphabet starting from A upto K (namely among A,C,E,G,I,K). The
codes may or may not be in the consecutive series of alphabets.
121 | P a g e
Write a program to input a code and its length. At the first instance of an error display “Invalid!”
stating the appropriate reason.
In case of no error, display the message “Valid!” Test your program for the following data and
some random data.
SAMPLE DATA
INPUT
N=4
ABCE
OUTPUT Invalid! Only alternate letters permitted!
INPUT
N=4
AcIK
OUTPUT Invalid! Only upper case letters permitted!
INPUT
N=4
AAKE
OUTPUT Invalid! Repetition of characters not permitted!
INPUT
N=7
OUTPUT Error! Length of string should not exceed 6 characters!
INPUT
N=4
AEGIK
OUTPUT Invalid! String length not the same as specified!
INPUT
N=3
ACE
OUTPUT Valid!
INPUT
N=5
GEAIK
OUTPUT Valid!
Algorithm
1. Input Handling:
o Read the length NNN and the code string from the user.
2. Length Check:
o If the length of the code string exceeds 6 characters, display "Error! Length of
string should not exceed 6 characters!" and terminate.
3. Length Validation:
122 | P a g e
o Check if the length of the code string matches NNN. If not, display "Invalid!
String length not the same as specified!" and terminate.
4. Character Validation:
o Ensure that all characters in the string are uppercase letters. If any character is
not uppercase, display "Invalid! Only upper case letters permitted!" and
terminate.
5. Alternate Character Check:
o Check that the string contains only the valid alternate letters: A, C, E, G, I, K. If
any invalid character is found, display "Invalid! Only alternate letters permitted!"
and terminate.
6. Repetition Check:
o Check for duplicate characters in the string. If duplicates exist, display "Invalid!
Repetition of characters not permitted!" and terminate.
7. Final Validation:
o If all checks are passed, display "Valid!".
Source Code:
import java.util.Scanner;
class preventfrompiracy
{
private String leters;
private int n;
public preventfrompiracy(int n,String l)
{
this.n = n;
leters = l;
}
public void prevent()
{
//checking for ABCD and AAKE
for(int i = 0;i<leters.length()-1;i++)
{
int j = leters.charAt(i);
int m = leters.charAt(i+1);
if((j+1)==m)
{
123 | P a g e
System.out.println("Invalid! Only alternate letters permitted!");
return;
}
if(j==m)
{
System.out.println("Invalid! Repetition of characters not permitted!");
}
}
//checking for more than k and less a
for(int i = 0;i<leters.length();i++)
{
if(leters.charAt(i)<65 && leters.charAt(i)>75)
{
System.out.println("Invalid!");
}
}
//checking whether the word is in uppercase
if(leters.equals(leters.toUpperCase())==false)
{
System.out.println("Invalid! Only upper case letters permitted!");
return;
}
//check for 6 characters in n
if(n>6)
{
System.out.println("Error! Length of string should not exceed 6 characters!");
}
//check for strings
if(leters.length()!=n)
{
System.out.println("Invalid! String length not the same as specified!");
}
else
{
System.out.println("valid!");
}
}
124 | P a g e
public static void main()
{
Scanner sc = new Scanner(System.in);
Scanner j = new Scanner(System.in);
System.out.println("ENTER A LENGTH");
int n = sc.nextInt();
System.out.println("ENTER A STRING VALUE");
String t = j.nextLine();
preventfrompiracy a = new preventfrompiracy(n,t);
a.prevent();
}
}
}
Question 33:
125 | P a g e
For example, consider A_z (the underscore is just to highlight the space). The ASCII
values of A. , z are 65, 32, 122 respectively. Concatenate them to get 6532122, then
reverse this to get 2212356 as the code message.
Write a program which reads a coded message and decodes it. The coded message will
not exceed 200 characters. It will contain only alphabets (A …. Z, and a ….z) and spaces.
ASCII values of A …Z are 65 ...90 and those of a …z are 97 …122. Test your program for
the following data and some random data.
SAMPLE DATA:
INPUT
Encode message: 2 3 1 2 1 7 9 8 6 2 3 1 0 1 9 9 5 0 1 8 7 2 3 7 9 2 31 0 1 8 1 1 7 9 2 7
OUTPUT: THE DECODED MESSAGE: Have a Nice Day
INPUT
Encode message: 2 3 5 1 10 1 1 5 0 1 7 8 2 3 5 1 1 1 2 1 7 9 9 1 1 8 0 1 5 6 2 3 4 0 1 6 1 1
71141148
OUTPUT: THE DECODED MESSAGE: Truth Always Wins
Algorithm
1. Read the Input: Capture the encoded message as a string of space-separated
ASCII values.
2. Reverse the Input: Since the encoded message is created by reversing the
concatenated ASCII values, we first reverse the string.
3. Split into ASCII Values: Split the reversed string into groups of three characters,
as ASCII values for the given character set (A-Z, a-z, and space) range from 65 to
122, which means they will be represented by either two or three digits.
4. Convert ASCII to Characters:
o Convert each group of characters back to their corresponding integer
(ASCII value).
o Map each ASCII value to its corresponding character.
5. Construct the Decoded Message: Join the characters together to form the final
decoded message.
6. Output the Result: Print the decoded message.
Source Code:
import java.util.Scanner;
class Decoder
126 | P a g e
{
private String code;
public Decoder(String l)
{
code = l;
String arr[] = code.split("[\\s]+");
code = "";
for(int i = 0;i<arr.length;i++)
{
code+=arr[i];
}
}
127 | P a g e
else if(r>=65 && r<=90)
{
k+=(char)r;
i+=2;
}
else if(r>=97 && r<=99)
{
k+=(char)r;
i+=2;
}
else
{
t = p.substring(i,i+3);
r = Integer.parseInt(t);
if(r>=100 && r<=122)
{
k+=(char)r;
i+=3;
}
else
{
return "INVALID INPUT";
}
}
}
return k;
}
Question 34 :
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 }
129 | P a g e
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 : M=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 : M = 13
OUTPUT : MATRIX SIZE OUT OF RANGE
Example 3
INPUT : M=5
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 10 2 5 23 6
OUTPUT : SORTED ARRAY: 2 5 6 10 23
FILLED MATRIX
2 5 6 10 23
2 5 6 10 2
2 5 6 2 5
2 5 2 5 6
2 2 5 6 10
Algorithm:
Class Definition:
Define a class Matrixx with:
o A one-dimensional integer array a to store input elements.
o A two-dimensional integer array b to represent the square matrix.
o An integer m to store the size of the matrix.
Constructor:
The constructor Matrixx(int n) initializes:
130 | P a g e
o The size m with the value of n.
o The one-dimensional array a with size m.
o The two-dimensional array b with dimensions [m][m].
Main Method:
In the main method:
o Check if the input size m is between 3 and 9 (inclusive):
If valid, instantiate a Matrixx object a with size m, call accept(), sort(),
fill(), and display().
If invalid, print "MATRIX SIZE OUT OF RANGE."
Accept Method:
Create a method accept() to read user input for the array:
o Initialize a Scanner to read input.
o Prompt the user to enter elements for the one-dimensional array.
o Loop through each index i from 0 to m-1 and read an integer into a[i].
Sort Method:
Create a method sort() to sort the elements of array a using insertion sort:
o Loop through each index i from 1 to m-1:
Store the value of a[i] in a temporary variable t.
Initialize p to i - 1.
While p is greater than or equal to 0 and t is less than a[p], shift a[p] to
the right (to a[p + 1]).
Place t in the correct position (a[p + 1]).
Fill Method:
Create a method fill() to fill the two-dimensional array b:
o Loop through each row i from 0 to m-1:
For the first part of the row (from 0 to m-1-i), fill b[i][j] with a[j].
For the remaining columns of the row (from j to m-1), fill b[i][k] with a[k-
j] (wrapping around the values).
Display Method:
Create a method display() to print the sorted array and the filled matrix:
o Print "SORTED ARRAY" and loop through a to print each non-zero element.
o Print "FILLED MATRIX" and loop through b to print each element in the matrix.
Source Code:
import java.util.*;
class Matrixx
{
int a[];
int b[ ][ ];
int m;
131 | P a g e
Matrixx(int n)
{
m=n;
a=new int[m];
b=new int[m][m];
}
void sort() //sorts the elements of the one dimensional array using insertion sort
technique
{
for(int i=1;i<a.length;i++)
132 | P a g e
{
int t = a[i];
int p = i-1;
while(p>=0 && t<a[p])
{
a[p+1] = a[p];
p--;
}
a[p+1] = t;
}
}
133 | P a g e
}
System.out.println("FILLED MATRIX");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(" "+b[i][j]);
}
System.out.println();
}
}
}
Question 35 :
Write a program to accept a sentence which may be terminated by either only. The words are to be
separated by a single blank space and are in UPPER CASE.
Perform the following tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence into palindrome words by concatenating
the word by its reverse (excluding the last character).
134 | P a g e
Example: The reverse of the word HELP would be LEH (omitting the last alphabet) and by
concatenating both, the new palindrome word is HELPLEH. Thus the word HELP becomes HELPLEH.
Note: The words which end in repeated alphabets, foe example AB would become ABBA and not
ABBBA and XXAZZZ becomes XAZZZAX.
[Palindrome word: Spells same from either side. Example: DAD, MADAM etc.]
(c) Display the original sentence along with the converted sentence.
Example 1
INPUT : THE BIRD IS FLYING.
OUTPUT : THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNGYLF
Example 2
INPUT : IS THE WATER LEVEL RAISING?
OUTPUT : IS THE WATER LEVEL RAISING?
ISI THEHT WATERETAW LEVEL RAISINGNISIAR
Example 3
INPUT : THIS MOBILE APP LOOKS FINE.
OUTPUT : THIS MOBILE APP LOOKS FINE.
THISIHT MOBILELIBOM APPA LOOKSKOOL FINENIF
Example 3
INPUT : YOU MUST BE CRAZY#
OUTPUT : INVALID INPUT
Algorithm:
Class Definition:
Define a class named Palindrome with:
o A string attribute s to store user input.
o An integer attribute f initialized to 1, used for input validity checking.
Accept Method:
Create a method accept() to read input from the user and check its validity:
o Initialize a Scanner to read user input.
o Prompt the user to enter a sentence in uppercase.
o Read the entire line and store it in s.
o Check the last character of s:
If it is not one of the valid punctuation marks (., ?, !), print "INVALID INPUT"
and set f to 0.
If valid, remove the punctuation by creating a substring of s that excludes
the last character.
Palindrome Check Method:
Create a method palindrome(String w) to check if a given word is a palindrome:
o Loop through the first half of the string w:
Compare the character at the current index i with the character at the
mirrored index (length - 1 - i).
If any characters do not match, return false.
o If all characters match, return true.
135 | P a g e
Convert Method:
Create a method convert(String w) to convert a word into a palindrome by concatenating it
with its reverse:
o Initialize an empty string r to store the reverse of the word (excluding the last
character).
o Loop backwards from the second-to-last character of w and append each character
to r.
Display Method:
Create a method display() to show the original and converted sentences:
o If f is still 1 (indicating valid input):
Print the original sentence s.
Split s into an array of words using whitespace as the delimiter.
Loop through each word in the array:
If the word is a palindrome (using the palindrome method), print the
word.
Otherwise, convert the word using the convert method and print the
result.
Main Method:
In the main method, create an instance of Palindromee and call the accept and display
methods to execute the program.
Source Code:
import java.util.*;
class Palindromee
{
String s;
int f=1;
void accept() //accepts input from the user and checks its validity
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter a sentence(in upper case):");
s=sc.nextLine();
int n=s.length();
char c=s.charAt(n-1);
s=s.substring(0,n-1);
if(c!='.' && c!='?' && c!='!')
{
System.out.println("INVALID INPUT.");
f=0;
}
136 | P a g e
}
boolean palindrome(String w) //checks if a given word is plaindrome
{
for(int i=0;i<w.length()/2;i++)
{
if(w.charAt(i)!=w.charAt(w.length()-1-i))
{
return false;
}
}
return true;
}
String convert(String w) //converts words into palindrome words by concatenating
with its reverse .
{
String r=""; //stores everse of a word(excluding the last character)
for(int i=w.length()-2;i>=0;i--)
{
r+= w.charAt(i);
}
if(r.charAt(0)==r.charAt(1))
{
r=r.substring(1);
}
return w+r;
}
void display() //displays the original sentence along with the converted sentence.
{
if(f==1)
{
System.out.println(s);
String a[]= s.split("[\\s]+");
for(int i=0;i<a.length;i++)
{
if(palindrome(a[i])==true)
{
137 | P a g e
System.out.println(a[i]);
}
else
{
System.out.println(convert(a[i]));
}
}
}
}
public static void main()
{
Palindromee a=new Palindromee();
a.accept();
a.display();
}
}
Question 36:
138 | P a g e
Example 1:
INPUT N = 1623
OUTPUT The number 1623 is a lucky number.
Example 2:
INPUT N = 15
OUTPUT The number 15 is not a lucky number.
Algorithm:
Input:
Read an integer n from the user.
Initialize:
Convert the integer n to a string p to process each digit.
Initialize a variable sum to 0.
Iterate through the Digits:
For each character in the string p (from index 0 to the length of p - 1):
o Check if the index i is odd (i.e., i % 2 != 0).
If true:
Convert the character at index i to an integer m.
Square the integer m (i.e., calculate m * m).
Add the squared value to sum.
Check Lucky Condition:
After processing all digits, check if sum % 9 == 0.
o If true, print "The number n is a lucky number".
o If false, print "The number n is not a lucky number".
End:
The program finishes after displaying the result.
Source Code:
import java.util.Scanner;
class lucky
{
private int n;
139 | P a g e
public lucky(int n)
{
this.n = n;
}
140 | P a g e
Question 37:
Write a program to declare a square matrix A[][] of order N.
Write a program to input N and check whether the value of N is greater than 1 and less than 20, if
not display “Size Out of Range”
Allow the user to input positive integers into this matrix. Perform the following tasks on the
matrix.
1. Output the Original Matrix.
141 | P a g e
2. Print the unique elements in each row. If there are no unique elements print “No Unique
Elements”
Try the program with the sample input and output.
Example1
INPUT
N=4
2 4 6 4
3 1 7 5
9 8 8 5
2 0 4 2
OUTPUT
2 4 6 4 Unique Elements in Row 1 = 2 6
3 1 7 5 Unique Elements in Row 2 = No Unique Elements
9 8 8 5 Unique Elements in Row 3 = 9 5
2 0 4 2 Unique Elements in Row 4 = 0 4
Example 2
INPUT
7 8
2 2
OUTPUT
7 8 Unique Elements in Row 1 = 7 8
2 2 Unique Elements in Row 2 = No Unique Elements
Example 3
INPUT N = 21
OUTPUT Size Out of Range
Algorithm:
Class Definition:
Define a class named unique.
Declare a private 2D array arr.
Constructor:
Define a constructor unique(int n) to initialize the 2D array with dimensions n x n.
Input Method:
142 | P a g e
Create a method input() to fill the 2D array with user-provided values:
o Create a Scanner object for input.
o Use nested loops to iterate through the array:
Prompt the user to enter a value for each element at position [i][j].
Store the input value in arr[i][j].
Get Unique Elements Method:
Create a method getunique(int k) to find and print unique elements in the k-th row of
the array:
o Initialize a temporary array ar to store unique elements and a counter p to track
the number of unique elements.
o Loop through each element m in the k-th row:
Initialize a count variable to zero.
Loop through the same row to count occurrences of m.
If the count of m is 1, store it in ar and increment p.
o Check if p is equal to the length of ar:
If true, print "No Unique Elements".
Otherwise, print the unique elements stored in ar.
Display Method:
Create a method display(int k) to print all elements of the k-th row:
o Loop through the elements of arr[k] and print each element.
Check Method:
Create a method check() to iterate through each row of the array:
o For each row, call display(i) to show the elements.
o Call getunique(i) to find and print unique elements in that row.
Source Code:
import java.util.Scanner;
class unique
{
private int arr[][];
143 | P a g e
public unique(int n)
{
arr = new int[n][n];
}
144 | P a g e
}
if(p==ar.length)
{
System.out.printf("%35s ","Unique Elements in Row " + (k+1) + "=");
System.out.print("No Unique Elements");
}
else
{
System.out.printf("%35s ","Unique Elements in Row " + (k+1) + "=");
for(int i = 0;i<p;i++)
{
System.out.print(ar[i] + " ");
}
}
System.out.println();
}
Question 38:
Write a program to accept a sentence which may be terminated by either ‘.’ , ‘?’ or ‘!’
only. The words are to be separated by a single space and are in UPPERCASE.
Perform the following tasks:
(a) Check for the validity of the accepted sentence only for the terminating character.
(b) Arrange each word in alphabetical order.
145 | P a g e
(c) Display the original sentence along with the changed sentence. Test your program
for the following data and some random data:
Example 1:
INPUT: ACTION SPEAK LOUDER THAN WORDS.
OUTPUT: ACINOT AEKPS DELORU AHNT DORSW
Example 2:
INPUT: WE WON!
OUTPUT: EW NOW
Example 3:
INPUT: YOU SCARED THE LIFE OUT OF ME,
OUTPUT: INVALID INPUT
Algorithm:
Class Definition:
Define a class named alpha.
Declare a string attribute j to store the input sentence.
Constructor:
Create a constructor alpha(String n) to initialize the string j with the provided input.
Calculate Method:
Create a method calculate() to process the input sentence:
o Split the string j into an array of words using whitespace as the delimiter.
o Loop through each word in the array:
If the current word is the last one in the array (indicated by its index),
remove the last character (punctuation) and print the sorted version
using the makealpha method.
For all other words, print the sorted version followed by a space.
Makealpha Method:
Create a method makealpha(String l) to sort the characters of a word:
o Convert the string l into a character array a.
o Use a nested loop to perform a bubble sort on the character array:
Loop through the array, comparing adjacent characters and swapping
them if they are out of order.
o Convert the sorted character array back to a string and return it.
Main Method:
In the main method, create a Scanner to read user input:
o Read a line of input into the string m.
o Check if the string m ends with one of the valid punctuation marks (., ?, !):
146 | P a g e
If valid, create an instance of alpha and call the calculate() method.
If not valid, print "INVALID INPUT".
Source Code:
import java.util.Scanner;
class alpha
{
String j = "";
public alpha(String n)
{
j = n;
}
return String.valueOf(a);
}
Question 39:
A bank intends to design a program to display the denomination of an input amount, up to 5
digits. The available denomination with the bank are of rupees 2000, 500, 200, 100, 50, 20, 10 and
1.
Design a program to accept the amount from the user and display the break-up in descending
order of denominations. (i.e., preference should be given to the highest denomination available)
along with the total number of notes.
[Note: Only the denomination used should be displayed].
148 | P a g e
Also print the amount in words according to the digits.
Example 1:
Input:
14836
Output:
One Four Eight Three Six
Denomination:
2000 * 7 = 14000
500 * 1 = 500
200 * 1 = 200
100 * 1 = 100
20 * 1 = 20
10 * 1 = 10
1*6=6
Example 2:
Input:
235001
Output:
Invalid Amount
Algorithm
1. Input Handling:
o Read the amount from the user.
o Check if the amount is a valid 5-digit or less integer.
o If invalid, display "Invalid Amount" and terminate.
2. Display Amount in Words:
o Create a function to convert each digit of the amount into its
corresponding word representation (e.g., 1 -> "One").
3. Denomination Breakdown:
o Define the available denominations in descending order: [2000, 500, 200,
100, 50, 20, 10, 1].
o Initialize a dictionary or list to store the count of each denomination used.
o Loop through each denomination:
Calculate the number of notes for the current denomination.
If any notes are used, add them to the output.
4. Output the Results:
o Print the amount in words.
o Print the denominations used along with their counts.
149 | P a g e
Source code:
import java.util.*;
class Denomination
{
public static void main()
{
System.out.println("hi");
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int a[]={1000,500,100,50,20,10,5,2,1};
String
b[]={"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
int cn=n,i=0,s=0,cc=0,j=-1;
while(cn!=0)
{
j++;
cn=cn/10;
}
if(j<5)
{
cn=n;
while(j!=-1)
{
int c=cn/((int)Math.pow(10,j));
System.out.print(b[c]+" ");
cn=cn%((int)Math.pow(10,j--));
}
System.out.println();
cn=n;
while(cn!=0)
{
int c=cn/a[i];
if(c>0)
{
System.out.println(a[i]+"\t"+"X"+"\t"+c+"\t"+"="+"\t"+(c*a[i]));
s=s+(c*a[i]);
150 | P a g e
cc=cc+c;
}
cn=cn%a[i];
i++;
}
System.out.println("Total\t\t\t=\t"+(s));
System.out.println("Total Number of Notes\t=\t"+(cc));
}
else
{
System.out.println("INVALID AMOUNT");
}}}
Question 40:
Write the program to do the following:
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
151 | P a g e
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
1. Input Handling:
o Read an integer nnn (the number of integers).
o If nnn is greater than 50, handle the error accordingly.
o Create an empty list called data.
o Read nnn integers from the user and store them in the data list.
152 | P a g e
2. Sorting the Data:
o Sort the data list in ascending order to easily access the largest values.
3. Rearranging the Data:
o Create a new list called rearranged with the same size as data.
o Place the largest value at index n//2n // 2n//2 (center).
o Use two pointers: one for the right position and one for the left position,
alternating between placing values to the right and left of the center.
4. Output the Results:
o Print the original array.
o Print the rearranged array.
Source Code:
import java.util.Arrays;
import java.util.Scanner;
if (n > 50) {
System.out.println("Invalid input. The number of integers should not exceed
50.");
return;
}
153 | P a g e
System.out.println("Original array");
System.out.println(Arrays.toString(data));
int centerIndex = n / 2;
rearranged[centerIndex] = data[n - 1]; // Place the maximum in the center
scanner.close();
}}
154 | P a g e