Ilovepdf Merged Merged
Ilovepdf Merged Merged
CLASS : XII
SECTION : D
SERIAL NO. – 21
SUBJECT : COMPUTER APPLICATION,
PROJECT WORK
PROJECT TOPIC: JAVA PROGRAMS
YEAR : ISC 2024
NAME : NAMAN BOTHRA
CLASS: XII
SECTION : D
SERIAL NO. – 21
SUBJECT : COMPUTER APPLICATIONS,
PROJECT WORK
PROJECT TOPIC: JAVA PROGRAMS
YEAR : ISC 2024
Table of Contents:
• Introduction to Java Programming Language:………………………………….
• Introduction to BlueJ Software..………………………………………………...
Program 1: 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……………………………………………………………
Program 2: A MOBIUS function M(N) returns the value -1 or 0 or 1 for a natural number (N) by the
following conditions are defined: When, M(N) = 1 if N = 1 M(N) = 0 if any prime factor of N is
contained in N more than once. M(N) = (-1)P if N is the product of ‘P’ distinct prime factors. Write a
program to accept a positive natural number (N) and display the MOBIUS result with proper
message. Design your program which will enable the output.………………………………..
Program 3: Display all Fascinating numbers that are in the range between m and n (both inclusive)
and output them along with the frequency, in the format given below: Test your program with the
following data and some random data……………….………………………………………..
Program 4: Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of
rows and ‘N’ is the number of columns such that the value of ‘M’ must be greater than 0 and less than
10 and the value of ‘N’ must be greater than 2 and less than 6. Allow the user to input digits (0 – 7)
only at each location, such that each row represents an octal number…………………………..
Program 5: Design a program to accept a day number (between 1 and 366), year (in 4 digits) from
the user to generate and display the corresponding date. Also, accept N (1 <= N <= 100) from the
user to compute and display the future date corresponding to ‘N’ days after the generated date.
Display an error message if the value of the day number, year and N are not within the limit or not
according to the condition specified……………………………………………………………
Program 6: Question 6 Write a program to declare a single-dimensional array a[] and a square matrix
b[][] of size N, where N > 2 and N < 10. Allow the user to input positive integers into the single
dimensional array. Perform the following tasks on the matrix : a) Sort the elements of the single-
dimensional array in ascending order using any standard sorting technique and display the sorted
elements. b) Fill the square matrix b[][] in the following format. If the array a[] = {5, 2, 8, 1} then,
after sorting a[] = {1, 2, 5, 8} Then, the matrix b[][] would fill as below: 1 2 5 8 1 2 5 1 1 2 1 2 1 1 2 5
c) Display the filled matrix in the above format……………………………………………….
Program 7: A Goldbach number is a positive even integer that can be expressed as the sum of two
odd primes. Note: All even integer numbers greater than 4 are Goldbach numbers. Example: 6 = 3 + 3
10 = 3 + 7 10 = 5 + 5 Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs,
i.e. 3, 7 and 5, 5. Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all the
odd prime pairs whose sum is equal to the number ‘N’………………………………………….
Program 8: The names of the teams participating in a competition should be displayed on a banner
vertically, to accommodate as many teams as possible in a single banner. Design a program to accept
the names of N teams, where 2 < N < 9 and display them in vertical order, side by side with a
horizontal tab (i.e. eight spaces)……………………………………………………..………
Program 9: A company manufactures packing cartons in four sizes, i.e. cartons to accomodate 6
boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to accept the number of boxes to be
packed (N) by the user (maximum up to 1000 boxes) and display the break up of the cartons used in
descending order of capacity (i.e. preference should be given to the highest capacity available, and if
boxes left are less than 6, an extra carton of capacity 6 should be used.)……………………
Program 10: Design a program to accept the number of participants N such that N must be greater
than 3 and less than 11. Create a double- dimensional array of size (N * 5) to store the answers of
each participant row-wise. Calculate the marks for each participant by matching the correct answer
stored in a single-dimensional array of size 5.Display the scores for each participant and also the
participants(s) having the highest score………………………………………………………
Program 11: 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……………………………….
Program 12: Write a program to accept the numbers M and N from the user and print the smallest
required number whose sum of all its digits is equal to N. Also, print the total number of digits
present in the required number. The program should check for the validity of the inputs and display
an appropriate message for an invalid input……………………………………………………….
Program 13: 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…. ………………………
Program 14: , 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………………………………………………………..
Program 15: Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of
rows and ‘N’ is the number of columns such that both M and N must be greater than 2 and less than
20. Allow the user to input integers into this matrix. Perform the following tasks on the matrix: 1.
Display the input matrix. 2. Find the maximum and minimum value in the matrix and display them
along with their position. 3. Sort the elements of the matrix in ascending order using any standard
sorting technique and rearrange them in the matrix. 4. Output the rearranged matrix……………
Program 16: Write a program to input a natural number less than 1000 and display it in words.
Program 17: Write a program to generate and print lucky numbers less than a given number
N < 50…...………………………………………………………………………………………
Program 18: Read in an integer n (which can be at most 50). Then read in n integers one by one and
store them in an array data from index 0 to n-1. Now we want to rearrange the integers in data in the
following way : Find the maximum value in data and put in the centre of the array (that is at (n/2);
find the next largest value and put it to its right; then the next largest and place it to its left and so on
alternating right and left until all integers in data are done.…………………………………
Program 19: Write a program to declare a square matrix A [ ] [ ]of order N (N < 20). Allow the user to
input positive integers in to this matrix. Perform the following task on the matrix: (i) Output the
original matrix. (ii) Fins the SADDLE POINT for the matrix such that is the minimum element for
the row to which it belongs and the maximum element for the column to which it belongs. Saddle
point for a given matrix is always unique. If the matrix has no saddle point, output the message “ NO
SADDLE POINT ”.………………………………………………………………………
Program 20: Write a program that takes the coded text (less than 100 characters), the shift value and
prints the decoded original text. Your program must reject any non-valid value for shift and display an
error message “INVALID SHIFT VALUE)”.Assume all characters are upper case……………..
Introduction to Java Programming Language:
Java was created by James Gosling and his team at Sun Microsystems
(which was later acquired by Oracle Corporation). The development of
Java began in the early 1990s, and the first official version, Java 1.0, was
released in 1996. James Gosling is often referred to as the "father of Java"
due to his significant contributions to its design and development.
Java Virtual Machine (JVM):
Java Virtual Machine (JVM) is a critical component of the Java
programming language and platform. It plays a crucial role in enabling
Java's "write once, run anywhere" principle, where Java code can be
written on one platform and executed on any platform with a compatible
JVM. Here are three key aspects of JVM:
Execution Environment:
JVM serves as a runtime environment for executing Java applications. It takes
compiled Java bytecode as input and executes it by converting the bytecode into
native machine code or interpreted code.This enables Java applications to be
platform-independent, as the bytecode remains consistent across different
platforms while the JVM handles the platform-specific execution.
Platform Independence:
Java source code is compiled into bytecode, a platform-independent
representation of the code. Bytecode is not tied to a specific hardware or
operating system.When a Java application runs, the JVM on that platform
interprets or compiles the bytecode, adapting it to the host system's architecture.
ALGORITHM:
num int Loop variable used to iterate through the numbers in the range.
reversedNum int Stores the reversed form of the current number during the loop.
squaredNum int Stores the square of the current number during the loop.
ALGORITHM:
Step 2: Declare an integer variable named num to hold the input number.
Step 3: Constructors
1. Define a default constructor MobiusCalculator() that initializes num with the value 78.
2. Define a parameterized constructor MobiusCalculator(int a) that sets num to the provided
value.
Variable
Name Type Description
flag int Used in the prime checking loop to count factors of a number.
hasDuplicate int Used to determine if there are duplicate prime factors of the number.
SOURCE CODE:
import java.util.*;
class MobiusCalculator
{
int num;
MobiusCalculator()
{
num = 78;
}
MobiusCalculator(int a)
{
num = a;
}
public void Input()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
num = scanner.nextInt();
}
public boolean checkPrime(int a)
{
int flag = 0;
int i;
for (i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
flag++;
}
}
if (flag == 0)
return true;
else
return false;
}
public int countDistinctPrimeFactors(int a)
{
int count = 0;
int i;
for (i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
if (checkPrime(i))
count++;
}
}
return count;
}
public void displayResult()
{
int hasDuplicate = 0;
int product = 1;
int i;
if (num == 1)
{
System.out.println("1 = 1");
System.out.println("NO PRIME FACTORS");
System.out.println("M(1) = 1");
} else
{
System.out.print(num + " = ");
for (i = 2; i < num; i++)
{
if (num % i == 0 && checkPrime(i))
{
if (num % (i * i) == 0)
{
hasDuplicate = 1;
System.out.print(i + "*");
product = product * i * i;
} else
{
product = product * i;
}
if (product!= num)
System.out.print(i + "*");
else
System.out.print(i);
}
}
if (hasDuplicate == 1)
{
System.out.println("\nDUPLICATE PRIME FACTORS");
System.out.println("M(" + num + ") = 0");
}
else {
System.out.println("\nNUMBER OF DISTINCT PRIME FACTORS: " +
countDistinctPrimeFactors(num));
System.out.println("M(" + num + ") = " + (int) Math.pow(-1,
countDistinctPrimeFactors(num)));
}
}
}
public static void main(String args[])
{
MobiusCalculator calculator = new MobiusCalculator();
calculator.Input();
calculator.displayResult();
}
OUTPUT:
}
QUESTION 3
A Fascinating number is one which when multiplied by 2 and 3 and then, after the results are concatenated
with the original number, the new number contains all the digits from 1 to 9 exactly once. There can be any
number of zeroes and are to be ignored.
Concatenating the results we get, 273546819 which contains all digits from 1 to 9 exactly once. Thus, 273 is
a Fascinating number. Accept two positive integers m and n, where m must be less than n and the values of
both ‘m’ and ‘n’ must be greater than 99 and less than 10000 as user input. Display all Fascinating numbers
that are in the range between m and n (both inclusive) and output them along with the frequency, in the
format given below: Test your program with the following data and some random data:
Example 1:
OUTPUT: THE FASCINATING NUMBERS ARE: 1902 1920 2019 2190 2703 2730 3027 3270
Example 3:
Example 4:
INPUT: m = 70 n = 450
ALGORITHM:
-STEP 1: Start the program.
isFNum method:
- STEP 2 : The method takes an integer num as input.
- STEP 3: It calculates num2 (2 times num) and num3 (3 times num).
- STEP 4:It concatenates the string representation of num, num2, and num3 into the concat string.It
initializes an array digitCount of size 10 to count the occurrence of digits (from 0 to 9).
- STEP 5: It iterates over each character in the concat string, excluding '0' digits. For each non-zero
digit, it increments the corresponding count in the digitCount array.
-STEP 6 :After counting the digits, it checks if each digit from 1 to 9 occurs exactly once in the
digitCount array. If any digit occurs more than once or if any of the digits from 1 to 9 is missing, it
returns false, indicating that num is not fascinating.
- STEP 7: If all the digits from 1 to 9 occur exactly once, it returns true, indicating that num is
fascinating.
findFascinatingNumbers method:
-STEP 8: The method takes two integers m and n as inputs, representing the range.
-STEP 9: It first checks if the input range is valid (m < 100, n > 9999, m > n). If the range is invalid,
it prints "INVALID INPUT" and returns.
-STEP 10: It initializes a boolean variable foundFascinating to track whether any fascinating
numbers are found in the range.
- STEP 11 : It then iterates through the range from m to n.
- STEP 12 : For each number in the range, it calls the isFNum method to check if the number is
fascinating.If a fascinating number is found, it prints the number and sets foundFascinating to
true.If no fascinating numbers are found, it prints "NIL".
-STEP 13 : Finally, it calls the countFascinatingNumbers method to count the total fascinating
numbers in the range and prints the count.
countFascinatingNumbers method:
-STEP 14 : The method takes two integers m and n as inputs, representing the range. It initializes a
counter variable count to 0. It then iterates through the range from m to n.
STEP 15: For each number in the range, it calls the isFNum method to check if the number is
fascinating. If the number is fascinating, it increments the count variable. After iterating through the
range, it returns the total count of fascinating numbers.
main method:
- STEP 16: The main method is the entry point of the program. It prompts the user to enter the range
[m, n]. It reads the values of m and n from the user using a Scanner. It then calls the
findFascinatingNumbers method with the entered range to find and display the fascinating numbers
and their count.
- STEP 17:End the program.
VARIABLE DESCRIPTION TABLE:
// Parameterized constructor
public FascinatingNumbers(int m, int n)
{
this.num2 = m;
this.num3 = n;
FascinatingNumber(m, n); // Call the FascinatingNumber method with the given range
}
// Method to check if a number is a fascinating number
public boolean isFascinatingNumber(int num)
{
num2 = num * 2;
num3 = num * 3;
String concat = Integer.toString(num) + Integer.toString(num2) +
Integer.toString(num3);
int[] digitCount = new int[10];
EXAMPLE 2:
EXAMPLE 3:
EXAMPLE 4:
QUESTION 4
Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows and ‘N’
is the number of columns such that the value of ‘M’ must be greater than 0 and less than 10 and the
value of ‘N’ must be greater than 2 and less than 6. Allow the user to input digits (0 – 7) only at
each location, such that each row represents an octal number.
Example: 2 3 1 (decimal equivalent of 1st row = 153 i.e. 2 × 82 + 3 × 81 + 1 × 80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4 × 82 + 0 × 81 + 5 × 80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1 × 82 + 5 × 81 + 6 × 80)
Perform the following tasks on the matrix
a) Display the original matrix.
b) Calculate the decimal equivalent for each row and display as per the format given below.
Test your program for the following data and some random data:
Example 1: INPUT:
M = 1 N = 3 Enter elements for row 1: 1 4 4
OUTPUT: Filled Matrix: 1 4 4
Decimal Equivalent: 100
Example 2: INPUT: M = 3 N = 4
Enter elements for row 1: 1 1 3 7
Enter elements for row 2: 2 1 0 6
Enter elements for row 3: 0 2 4 5
OUTPUT:
Filled Matrix: 1 1 3 7
2106
. 0245
Decimal Equivalent: 607 1094 165
Example 3:
INPUT: M = 3 N = 3
Enter elements for row 1: 2 4 8
OUTPUT: Invalid Input.
Example 4: INPUT: M = 4 N = 6
OUTPUT: Out of range.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create a Scanner object to read input from the user.
STEP 3: Prompt the user to input the number of rows M for the matrix and validate it to be between
1 and 9 (inclusive).Prompt the user to input the number of columns N for the matrix and validate it
to be between 3 and 5 (inclusive).
STEP 4: Create a 2D array matrix with dimensions M x N to store the octal elements.
STEP 5: Input elements for each row of the matrix:
a. For each row i from 1 to M:
i. Prompt the user to enter N octal elements between 0 and 7 (inclusive) for the row.
ii. If any of the input elements are out of the valid range, display an error message and prompt again
for the invalid input.
iii. Store the valid input elements in the matrix array.
STEP 6: Display the filled original matrix:
a. For each row i from 1 to M:
i. For each column j from 1 to N, display the element in the matrix at position [i][j].
ii. Move to the next line after displaying each row.
STEP 7: Calculate and display the decimal equivalents:
a. For each row i from 1 to M:
i. Initialize a variable decimal to 0.
ii. For each column j from N to 1 (reverse order):
STEP 8. Calculate the decimal value of the element at position [i][j] using matrix[i][j] * 8^(N - j).
STEP 9:. Add the calculated decimal value to the decimal variable. Display the decimal value for
the current row.
STEP 10: End the program.
VARIABLE DESCRIPTION TABLE:
Data
Variable Type Description
i int Loop variable used for iterating through rows of the matrix.
j int Loop variable used for iterating through columns of the matrix.
Temporary variable used to store the user's input for each element of
input int the matrix.
// Default Constructor
public OctalMatrix()
{
sc = new Scanner(System.in);
readMatrixDimensions(); // Read matrix dimensions from user
createMatrix(); // Create the matrix with given dimensions
fillMatrix(); // Input elements for each row
}
// Parameterized Constructor
public OctalMatrix(int rows, int columns)
{
sc = new Scanner(System.in);
M = rows; // Set rows
N = columns; // Set columns
createMatrix(); // Create the matrix with given dimensions
fillMatrix(); // Input elements for each row
}
// Method to read matrix dimensions from user
private void readMatrixDimensions()
{
// Input M and N from the user
do {
System.out.print("Enter the number of rows (M, 1-9): ");
M = sc.nextInt();
if (M <= 0 || M >= 10)
{
System.out.println("Invalid Input. The number of rows must be
between 1 and 9.");
}
} while (M <= 0 || M >= 10);
do {
System.out.print("Enter the number of columns (N, 3-5): ");
N = sc.nextInt();
if (N <= 2 || N >= 6)
{
System.out.println("Out of range. The number of columns must be
between 3 and 5.");
}
} while (N <= 2 || N >= 6);
}
matrix[i][j] = input;
}
}
}
// Method to display the matrix
public void displayMatrix()
{
System.out.println("\nFilled Matrix:");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
// Main method
public static void main(String[] args)
{
OctalMatrix defaultMatrix = new OctalMatrix(); // Using the default
constructor
defaultMatrix.displayMatrix();
defaultMatrix.displayDecimalEquivalents();
EXAMPLE 2:
EXAMPLE 3:
EXAMPLE 4:
QUESTION 5:
Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user to generate
and display the corresponding date.
Also, accept N (1 <= N <= 100) from the user to compute and display the future date corresponding to ‘N’
days after the generated date. Display an error message if the value of the day number, year and N are not
within the limit or not according to the condition specified.
Test your program with the following data and some random data:
Example 1:
YEAR: 2018
Example 2:
INPUT:
Example 3:
YEAR: 2018
Example 4: INPUT:
OUTPUT:
Data
Variable Description Type
scanner Scanner object to read input from the user Scanner
dayNumber The day number input by the user int
year The year input by the user int
date The generated date in the format "DAY MONTH_NAME, YEAR" String
// Default Constructor
public DateGenerator()
{
Scanner scanner = new Scanner(System.in);
System.out.print("DAY NUMBER: ");
dayNumber = scanner.nextInt();
System.out.print("YEAR: ");
year = scanner.nextInt();
System.out.print("DATE AFTER (N DAYS): ");
n = scanner.nextInt();
scanner.close();
if (dayNumber < 1 || dayNumber > 366 || year < 1000 || year > 9999 || n < 1 || n >
100) {
System.out.println("INPUT OUT OF RANGE");
return;
}
// Generate and display the corresponding date
String date = generateDate(dayNumber, year);
System.out.println("DATE: " + date);
// Compute and display the future date after N days
String futureDate = FutureDate(dayNumber, year, n);
System.out.println("DATE AFTER " + n + " DAYS: " + futureDate);
}
// Parameterized Constructor
public DateGenerator(int dayNumber, int year, int n){
this.dayNumber = dayNumber;
this.year = year;
this.n = n;
}
public static String generateDate(int dayNumber, int year)
{
int month = 0;
int day = 0;
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
{
daysInMonth[2] = 29; // Leap year
}
String suffix;
if (day >= 11 && day <= 13) {
suffix = "TH";
} else if (day % 10 == 1) {
suffix = "ST";
} else if (day % 10 == 2) {
suffix = "ND";
} else if (day % 10 == 3) {
suffix = "RD";
} else {
suffix = "TH";
}
String monthName;
switch (month) {
case 1:
monthName = "JANUARY";
break;
case 2:
monthName = "FEBRUARY";
break;
case 3:
monthName = "MARCH";
break;
case 4:
monthName = "APRIL";
break;
case 5:
monthName = "MAY";
break;
case 6:
monthName = "JUNE";
break;
case 7:
monthName = "JULY";
break;
case 8:
monthName = "AUGUST";
break;
case 9:
monthName = "SEPTEMBER";
break;
case 10:
monthName = "OCTOBER";
break;
case 11:
monthName = "NOVEMBER";
break;
case 12:
monthName = "DECEMBER";
break;
default:
monthName = "";
}
return day + suffix + " " + monthName + ", " + year;
}
public static void main(String[] args)
{
DateGenerator defaultDate = new DateGenerator(); // Using the default
constructor
int customDayNumber = 150;
int customYear = 2023;
int customN = 30;
EXAMPLE 1:
EXAMPLE 2:
EXAMPLE 3:
EXAMPLE 4:
Question 6
Write a program to declare a single-dimensional array a[] and a square matrix b[][] of size N,
where N > 2 and N < 10. Allow the user to input positive integers into the single dimensional array.
Perform the following tasks on the matrix
: a) Sort the elements of the single-dimensional array in ascending order using any standard sorting
technique and display the sorted elements.
b) Fill the square matrix b[][] in the following format. If the array a[] = {5, 2, 8, 1} then, after
sorting a[] = {1, 2, 5, 8} Then, the matrix b[][] would fill as below: 1 2 5 8 1 2 5 1 1 2 1 2 1 1 2 5
c) Display the filled matrix in the above format.
Test your program for the following data and some random data:
Example 1: INPUT: N = 3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT: SORTED ARRAY: 1 3 7
FILLED MATRIX
137
131
113
Example 2: INPUT: N = 13
OUTPUT: MATRIX SIZE OUT OF RANGE
ALGORITHM:
Variable
Name Type Description
matrix 2D array Represents the square matrix that will store the elements.
Loop variable used for iterating over rows and columns of the matrix
i int and arrays.
temp int Temporary variable used for swapping elements during array rotation.
Size of the matrix, input by the user and used for matrix and array
N int dimensions.
SOURCE CODE:
import java.util.*;
import java.util.Scanner;
MatrixTasks(int a, int b)
{
this.m = a;
this.n = b;
matrix = new int[m][n];
}
// Function to fill the elements of a square matrix with the elements of an array
public void fillMatrix(int[] arr)
{
int len = arr.length;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
matrix[i][j] = arr[j];
}
int temp = arr[0];
for (int j = 0; j < len - 1; j++)
{
arr[j] = arr[j + 1];
}
arr[len - 1] = temp;
}
}
// Prompt the user to input the value of N (matrix size) and validate it
do {
System.out.print("Enter the value of N (between 3 and 9): ");
N = scanner.nextInt();
if (N <= 2 || N >= 10)
{
System.out.println("MATRIX OUT OF RANGE");
}
}
while (N <= 2 || N >= 10);
// b) Fill the elements of the square matrix using the sorted array
obj.fillMatrix(arr);
scanner.close();
}
}
OUTPUT:
EXAMPLE 1:
EXAMPLE 2:
EXAMPLE 3:
Question 7
A Goldbach number is a positive even integer that can be expressed as the sum of two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example: 6 = 3 + 3 10 = 3 + 7 10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3.
Similarly, 10 has two odd prime pairs, i.e. 3, 7 and 5, 5.
Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all the odd prime pairs
whose sum is equal to the number ‘N’.
Test your program with the following data and some random data:
Example 1: INPUT: N = 14
OUTPUT:
Prime pairs are: 3, 11 7, 7
Example 2: INPUT: N = 30
OUTPUT:
Prime numbers are: 7, 23 11, 19 13, 17
Example 3: INPUT: N = 17
OUTPUT: Invalid input. Number is odd.
Example 4: INPUT: N = 126
OUTPUT: Invalid input. Number is out of range.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Define a function isPrime(num) that takes an integer num as input and returns a boolean
value indicating whether the number is prime or not.
-Within the isPrime function:
STEP 3:
a. Check if the input num is less than or equal to 1. If yes, return false since prime numbers are
greater than 1.
b. Use a for loop to check for divisors of num from 2 to the square root of num.
c. If num is divisible by any integer between 2 and the square root of num, return false, as it's not a
prime number.
d. If no divisor is found, return true, indicating that num is a prime number.
STEP 4: Define a function findGoldbachPairs(N) that takes an integer N as input and finds the
Goldbach pairs for the given even number.
-Within the findGoldbachPairs function:
STEP 5:
a. Check if N is odd (i.e., not even). If yes, print "Invalid input. Number is odd." and return.
b. Check if N is less than 10 or greater than 48. If yes, print "Invalid input. Number is out of range."
and return.
c. Initialize a boolean variable foundPair as false. This variable will be used to check if any
Goldbach pair is found.
d. Print "Prime pairs are:" to indicate the list of Goldbach pairs.
e. Use a for loop to iterate from 3 to N / 2 with a step of 2, as the pairs should consist of odd prime
numbers and (N - odd prime) is also odd.
f. Inside the loop, check if both i and (N - i) are prime numbers using the isPrime function.
g. If both i and (N - i) are prime, print the pair (i, N - i) as a Goldbach pair.
h. Set foundPair to true if at least one Goldbach pair is found.
i. After the loop, if no Goldbach pair is found (i.e., foundPair is false), print "No prime pairs found."
STEP 6:
In the main function:
a. Create a Scanner object to read input from the user.
b. Prompt the user to enter an even integer between 10 and 48 (inclusive).
c. Read the input integer N.
d. Call the findGoldbachPairs(N) function to find and display the Goldbach pairs for the given N.
e. Close the scanner.
STEP 7: End the program.
N int The even integer entered by the user to find Goldbach pairs.
SOURCE CODE:
import java.util.Scanner;
if (!foundPair)
{
System.out.println("No prime pairs found.");
}
}
// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an even integer (10 to 48): ");
int N = scanner.nextInt();
scanner.close();
}
}
OUTPUT:
EXAMPLE 1:
EXAMPLE 2:
EXAMPLE 3:
EXAMPLE 4:
Question 8
The names of the teams participating in a competition should be displayed on a banner
vertically, to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display them in
vertical order, side by side with a horizontal tab (i.e. eight spaces).
Test your program for the following data and some random data:
ALGORITHM:
1. Start the program.
STEP 1:
2. Initialize a Scanner object for input (inputScanner).
STEP 2:
3. Print "Enter the number of teams (between 2 and 9): ".
Read and store the number of teams as numTeams.
4. If numTeams is less than or equal to 2 or greater than or equal to 9, then
4.1 Print "Invalid input."
4.2 Exit.
5. Consume the newline character from the previous input.
6. Initialize an array teamNames of size numTeams to store team names.
7. Repeat for i = 0 to numTeams - 1:
7.1 Print "Team " + (i + 1) + ": ".
7.2 Read a line of input and store it in teamNames[i].
8. Initialize maxLength to 0.
9. For each teamName in teamNames:
9.1 If the length of teamName is greater than maxLength, update maxLength.
10. For row = 0 to maxLength - 1:
10.1 For each teamName in teamNames:
10.1.1 If row is less than the length of teamName, print the character at
position 'row' in teamName followed by a tab
10.1.2 Else, print a tab.
10.2 Print a newline.
11. Close the input scanner (inputScanner).
12. End the program.
Data
Variable Type Description
numTeams int An integer to store the number of teams entered by the user.
row int A loop variable used to iterate through rows when printing the banner.
SOURCE CODE:
import java.util.Scanner;
public class TeamVerticalBanner {
private String[] teamNames;
public Scanner scanner; // Scanner object for user input
// Default constructor
public TeamVerticalBanner()
{
scanner = new Scanner(System.in);
}
// Parameterized constructor
public TeamVerticalBanner(int numTeams)
{
teamNames = new String[numTeams];
}
public void inputTeamNames(Scanner scanner)
{
scanner.nextLine(); // Consume newline
for (int i = 0; i < teamNames.length; i++)
{
System.out.print("Team " + (i + 1) + ": ");
teamNames[i] = scanner.nextLine();
}
}
public void displayVerticalBanner(){
int maxLength = 0;
for (String teamName : teamNames)
{
if (teamName.length() > maxLength)
{
maxLength = teamName.length();
}
}
for (int row = 0; row < maxLength; row++) {
for (String teamName : teamNames)
{
if (row < teamName.length())
{
System.out.print(teamName.charAt(row) + "\t");
} else
{
System.out.print("\t");
}}
System.out.println();
}
}
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
// Input the number of teams
System.out.print("Enter the number of teams (between 2 and 9): ");
int numTeams = inputScanner.nextInt();
if (numTeams <= 2 || numTeams >= 9)
{
System.out.println("Invalid input.");
} else
{ // Using the parameterized constructor
TeamVerticalBanner banner = new TeamVerticalBanner(numTeams);
// Input team names
banner.inputTeamNames(inputScanner);
// Display the vertical banner
banner.displayVerticalBanner();
TeamVerticalBanner obj = new TeamVerticalBanner();
obj.inputTeamNames(inputScanner);
obj.displayVerticalBanner();
}
// Close the input scanner
inputScanner.close();
}
}
}
OUTPUT:
Question 9
A company manufactures packing cartons in four sizes, i.e. cartons to accomodate 6 boxes,
12 boxes, 24 boxes and 48 boxes. Design a program to accept the number of boxes to be
packed (N) by the user (maximum up to 1000 boxes) and display the break up of the cartons
used in descending order of capacity (i.e. preference should be given to the highest capacity
available, and if boxes left are less than 6, an extra carton of capacity 6 should be used.)
Test your program with the following data and some random data:
Example 1: INPUT: N = 726
OUTPUT: 48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Example 2: INPUT: N = 140
OUTPUT: 48 * 2 = 96
24 * 1 = 24
12 * 1 = 12
6*1=6
Remaining boxes = 2 * 1 = 2
Total number of boxes = 140
Total number of cartons = 6
Example 3: INPUT: N = 4296
OUTPUT: INVALID INPUT
ALGORITHM:
STEP 1: START THE PROGRAM
STEP 2: Create a new Scanner object to read input from the user.
STEP 3: Ask the user to enter the number of boxes to be packed (N).
STEP 4: Check if the input is valid (between 1 and 1000 inclusive). If not,
print"INVALID INPUT" and terminate the program.
STEP 5: Initialize an array of carton sizes: {48, 24, 12, 6}.
STEP 6: Create an array to store the count of each carton size (cartonCount) and
initialize all counts to 0.
STEP 7: Initialize a variable (remainingBoxes) to keep track of the number of
boxes that still need to be packed and set it to N initially.
STEP 8: Initialize a variable (totalCartons) to keep track of the total number of
cartons used and set it to 0 initially.
STEP 9: Use a loop to iterate through each carton size and pack the boxes in the
available cartons.
STEP 10: For each carton size, check if the remainingBoxes are greater than or
equal to the current carton size.
STEP 11: If yes, calculate how many cartons of that size can be used and update
the cartonCount and remainingBoxes accordingly.
STEP 12: Print the output of the packing process, showing the number of each
carton size used and their total capacity.
STEP 13: If there are any remainingBoxes after using all available cartons, pack
the remaining boxes in an additional carton of size 6.
STEP 14: Print the total number of boxes and the total number of cartons used.
STEP 15: Close the Scanner object.
STEP 16: END OF THE PROGRAM
VARIABLE DESCRIPTION TABLE:
cartonCount int[] Array to store the count of each carton size used.
remainingBoxes int Stores the number of boxes that are yet to be packed.
totalCartons int Stores the total number of cartons used for packing.
SOURCE CODE:
import java.util.Scanner;
if (remainingBoxes == 0)
{
System.out.println("Remaining boxes = 0");
}
if (remainingBoxes > 0)
{
System.out.println("Remaining boxes = " + remainingBoxes + " * 1 = "
+ remainingBoxes);
totalCartons++;
}
System.out.println("Total number of boxes = " + N);
System.out.println("Total number of cartons = " + totalCartons);
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of boxes to be packed (maximum up to
1000 boxes): ");
int N = input.nextInt();
// Default constructor
public QuizCompetition()
{
input = new Scanner(System.in);
}
// Parameterized constructoR
public QuizCompetition(int participants)
{
N = participants;
input = new Scanner(System.in);
}
int numQuestions = 5;
String[][] participantsAnswers = new String[N][numQuestions];
String[] correctAnswers = new String[numQuestions];
collectParticipantsAnswers(participantsAnswers, numQuestions);
collectCorrectAnswers(correctAnswers, numQuestions);
input.close();
}
// Loop through each participant's answers and compare with the correct answers
for (int i = 0; i < participantsAnswers.length; i++) {
for (int j = 0; j < correctAnswers.length; j++) {
if (participantsAnswers[i][j].equals(correctAnswers[j])) {
// If the participant's answer matches the correct answer, increment their score
scores[i]++;
}
}
}
return scores;
}
// Loop through all scores to find the highest score and count the number of
participants with that score
for (int score : scores)
{
if (score > maxScore)
{
maxScore = score;
numOfMaxScorers = 1;
} else if (score == maxScore)
{
numOfMaxScorers++;
}
}
// Initialize an array to store the index(es) of the highest scorer(s)
int[] highestScorers = new int[numOfMaxScorers];
int index = 0;
// Loop through the scores array again to find the index(es) of the highest scorer(s)
for (int i = 0; i < scores.length; i++)
{
if (scores[i] == maxScore)
{
highestScorers[index++] = i + 1; // Add 1 to convert from 0-based index to
participant number
}
}
sc.close();
}
}
OUTPUT:
EXAMPLE 2
EXAMPLE 3:
EXAMPLE 4:
Question 11
Caesar Cipher is an encryption technique which is implemented as ROT13 (‘rotate by 13
places’).
It is a simple letter substitution cipher that replaces a letter with the letter 13 places after it in
the alphabets, with the other characters remaining unchanged.
ROT13
A/a B/b C/c D/d E/e F/f G/g H/h I/I J/j K/k L/l M/m
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/w X/x Y/y Z/z
Write a program to accept a plain text of length L, where L must be greater than 3 and less
than 100. Encrypt the text if valid as per the Caesar Cipher.
Test your program with the sample data and some random data.
Example 1: INPUT: Hello! How are you?
OUTPUT: The cipher text is: Uryyb! Ubj ner lbh?
Example 2: INPUT: Encryption helps to secure data.
OUTPUT: The cipher text is: Rapelcgvba urycf gb frpher qngn.
Example 3: INPUT: You
OUTPUT: INVALID LENGTH
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a new Scanner object to read input from the user.
STEP 3: Prompt the user to enter a plain text (L > 3 and L < 100).
STEP 4: Read the plain text input from the user.
STEP 5: Get the length of the plain text (L).
STEP 6: Check if the length (L) of the plain text is within the range of 4 to 100 (inclusive).
STEP 7: If the length is not within the valid range, display "INVALID LENGTH", close the
Scanner object, and terminate the program.
STEP 8: Call the "encrypt" method, passing the plain text as an argument, to get the cipher
text.
STEP 9: Print "The cipher text is:"
STEP 10: Print the cipher text obtained from the "encrypt" method.
STEP 11: Close the Scanner object to release resources.
STEP 12: End of the program.
base char Holds the base character ('A' or 'a') depending on case.
encryptedChar char Holds the encrypted character after applying Caesar cipher.
cipherChars char[] Array to store the encrypted characters of the plain text.
import java.util.Scanner;
// Default constructor
public CaesarCipher()
{
// Initialize with an empty string
plainText = "";
}
// Parameterized constructor
public CaesarCipher(String text)
{
plainText = text;
}
EXAMPLE 2:
EXAMPLE 3:
EXAMPLE 4
Question 12
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less
than 100. Find the smallest integer that is greater than M and whose digits add up to N. For
example, if M = 100 and N = 11, then the smallest integer greater than 100 whose digits add
up to 11 is 119.
Write a program to accept the numbers M and N from the user and print the smallest required
number whose sum of all its digits is equal to N. Also, print the total number of digits present
in the required number. The program should check for the validity of the inputs and display
an appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1: INPUT: M = 100 N = 11
OUTPUT: The required number = 119
Total number of digits = 3
Example 2: INPUT: M = 1500 N = 25
OUTPUT: The required number = 1699
Total number of digits = 4
Example 3: INPUT: M = 99 N = 11
OUTPUT: INVALID INPUT
Example 4: INPUT: M = 112 N = 130
OUTPUT: INVALID INPUT
ALGORITHM:
STEP 1: Start of the Program
STEP 2: Create a new Scanner object to read user input.
STEP 3: Prompt the user to enter a positive number M between 100 and 10000.
Read the value of M.
STEP 4: Check if M is within the valid range (between 100 and 10000). If not,
print "INVALID INPUT," close the Scanner, and return.
STEP 5: Prompt the user to enter a positive number N (less than 100).
Read the value of N.
STEP 6: Check if N is greater than or equal to 100. If so, print "INVALID
INPUT," close the Scanner, and return.
STEP 7 : Find the Smallest Integer with the Sum of Digits Equal to N
input Scanner A Scanner object used to read input from the user.
M int Stores the positive number entered by the user (between 100 and 10000).
N int Stores the positive number entered by the user (less than 100).
smallestInteger int Stores the smallest integer with the sum of digits equal to N.
totalDigits int Stores the total number of digits in the smallest integer found.
SOURCE CODE:
import java.util.Scanner;
// Parameterized constructor
public SmallestInteger(int m, int n)
{
M = m;
N = n;
}
if (smallestInteger != -1)
{
System.out.println("The required number = " + smallestInteger);
System.out.println("Total number of digits = " + countTotalDigits(smallestInteger));
} else {
System.out.println("No number found with the sum of digits equal to " + N);
}
}
input.close();
}
}
}
OUTPUT:
EXAMPLE 3:
EXAMPLE 4:
Question 13
A composite magic number is a positive integer which is composite as well as a magic
number. Composite number: A composite number is a number that has more than two factors.
For example: 10 Factors are: 1, 2, 5, 10. Magic number: A magic number is a number in
which the eventual sum of the digits is equal to 1.
For example: 28 2 + 8 = 10. 1 + 0 = 1.
Accept two positive integers ‘m’ and ‘n’, where m is less than n as user input. Display the
number of composite magic integers that are in the range between ‘m’ and ‘n’ (both inclusive)
and output them along with the frequency, in the format specified below.
Test your program with the sample data and some random data:
Example 1: INPUT: m = 10 n = 100
OUTPUT: THE COMPOSITE MAGIC INTEGERS ARE: 10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2: INPUT: m = 1200 n = 1300
OUTPUT: THE COMPOSITE MAGIC INTEGERS ARE: 1207, 1216, 1225, 1234, 1243,
1252, 1261, 1270, 1288
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9
Example 3: INPUT: m = 120 n = 99
OUTPUT: INVALID INPUT
ALGORITHM:
// Default constructor
public CompositeMagicNumbers()
{
m = 0;
n = 0;
}
// Parameterized constructor
public CompositeMagicNumbers(int start, int end)
{
m = start;
n = end;
}
int count = 0;
System.out.println("THE COMPOSITE MAGIC INTEGERS ARE:");
if (count == 0)
{
System.out.println("No composite magic integers found in the range.");
} else
{
System.out.println();
System.out.println("FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: " +
count);
}
}
ALGORITHM:
i int Loop variable used in the isPrime method to check for divisibility.
// Default constructor
public PrimePalindrome()
{
m = 0;
n = 0;
}
// Parameterized constructor
public PrimePalindrome(int start, int end)
{
m = start;
n = end;
}
int count = 0;
if (isPrime(m) && isPalindrome(m))
{
System.out.print(m + ", ");
count++;
}
count += findPrimePalindromes(m + 1, n);
return count;
}
ALGORITHM:
input Scanner A Scanner object used to read input from the user.
maxValue int An integer variable to store the maximum value found in the matrix.
minValue int An integer variable to store the minimum value found in the matrix.
Variable Data
Name Type Description
SOURCE CODE:
import java.util.Scanner;
// Parameterized constructor
public MatrixOperations(int[][] inputMatrix)
{
matrix = inputMatrix;
}
// Prompt the user to enter the number of rows (M > 2 and M < 20).
// Read the input value for M using the Scanner.
do {
System.out.print("Enter the number of rows (M > 2 and M < 20): ");
M = input.nextInt();
// Prompt the user to enter the number of columns (N > 2 and N < 20).
// Read the input value for N using the Scanner.
do {
System.out.print("Enter the number of columns (N > 2 and N < 20): ");
N = input.nextInt();
// Task 2: Find the maximum and minimum value in the matrix and display them along
with their position
int[] maxPosition = MaxPosition(matrix);
int[] minPosition = MinPosition(matrix);
int maxValue = matrix[maxPosition[0]][maxPosition[1]];
int minValue = matrix[minPosition[0]][minPosition[1]];
System.out.println("\nLARGEST NUMBER: " + maxValue);
System.out.println("ROW = " + maxPosition[0]);
System.out.println("COLUMN = " + maxPosition[1]);
// Task 3: Sort the elements of the matrix in ascending order using any standard sorting
technique
sortMatrix(matrix);
index = 0;
// Rearrange the sorted elements back into the matrix
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++)
{
matrix[i][j] = tempArray[index++];
}
}
}
}
OUTPUT:
Question 16
Write a program to input a natural number less than 1000 and display it in words.
Test your program for the given sample data and some random data.
INPUT: 29
OUTPUT: TWENTY NINE
INPUT: 17001
OUTPUT: OUT OF RANGE
INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN
INPUT: 500
OUTPUT: FIVE HUNDRED
ALGORITHM:
SOURCE CODE:
import java.util.Scanner;
// Default constructor
public NumberToWordsConverter()
{
number = 0;
}
// Parameterized constructor
public NumberToWordsConverter(int num)
{
number = num;
}
// Arrays to store the word representations for units, teens, and tens
String[] units = {"", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
"EIGHT", "NINE"};
String[] teens = {"TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN",
"FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN", "NINETEEN"};
String[] tens = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY",
"SEVENTY", "EIGHTY", "NINETY"};
// If the number is between 100 and 999 (inclusive), return the word for the hundreds digit,
"HUNDRED", and the remaining two digits (if applicable)
if (number >= 100 && number <= 999)
{
int hundredsDigit = number / 100;
int remainingNumber = number % 100;
return units[hundredsDigit] + " HUNDRED" + (remainingNumber > 0 ? " AND " + new
NumberToWordsConverter(remainingNumber).Num_Words() : "");
}
// If the number is not within the valid range, return "OUT OF RANGE"
return "OUT OF RANGE";
}
}
OUTPUT:
Question 17
Consider the sequence of natural numbers. 1, 2, 3, 4, 5, 6, 7 ………………………………….
Removing every second number produces the sequences 1, 3, 5, 7, 9, 11, 13, 15,
17………………………….
This process continues indefinitely by removing the fourth, fifth….and so on, till after a
fixed number of steps, certain natural numbers remain indefinitely. These are known as lucky
numbers.
Write a program to generate and print lucky numbers less than a given number N < 50.
SAMPLE INPUT : N = 10
OUTPUT : THE LUCKY NUMBERS LESS THAN 10 ARE: 1 3 7.
SAMPLE
INPUT : N = 25
OUTPUT :
THE LUCKY NUMBERS LESS THAN 10 ARE: 1 3 7 13 19
ALGORITHM:
STEP 1: Start the program.
STEP 2: Read an integer 'N' (less than 50) from the user.
STEP 3: Print a message indicating the lucky numbers less than N are going to
be displayed.
STEP 4: Initialize a loop with 'i' starting from 1 and incrementing by 2 (to
consider only odd numbers).
STEP 5: Inside the loop, check if the current 'i' is a lucky number by calling the
method 'isLuckyNumber(i).
a) Base case 1: If 'num' is less than 'step', return true (the number is considered
lucky as it is not divisible by any of its digits).
b) Base case 2: If 'num' is divisible by 'step', return false (the number is not
lucky).
c) Recursive case: Call the method 'isLuckyNumber' with the updated 'num'
and 'step + 1' to continue checking for lucky properties
STEP 6: If the 'i' is a lucky number (the method returns true), print 'i' as a lucky
number.
STEP 7: Continue the loop until 'i' is less than N.
STEP 8: Close the Scanner to release system resources.
STEP 9: End of the program.
VARIABLE DESCRIPTION TABLE:
input Scanner A Scanner object used to read input from the user.
step int The step value used in the luckiness checking algorithm.
SOURCE CODE:
import java.util.Scanner;
input.close();
}
Data
Variable Type Description
scanner Scanner A Scanner object to read user input from the console.
matrix int[][] A 2D integer array to store the elements of the square matrix.
Row int[] An integer array to store the row indices of saddle points.
Col int[] An integer array to store the column indices of saddle points.
Count int An integer variable to keep track of the number of saddle points found.
import java.util.Scanner;
System.out.println("OUTPUT :");
printMatrix(matrix, n);
// Find and display saddle points
SaddlePoint(matrix, n);
scanner.close();
}
ALGORITHM:
STEP 1: Start the program.
STEP 2: Prompt the user to enter the coded text and the shift value.
STEP 3: Read the user input for coded text and shift value.
STEP 4: Check if the shift value is valid (between 1 to 26 inclusive). If not, print "INVALID
SHIFT VALUE" and exit the program.
STEP 5: Call the decodeCodedText method with the provided coded text and shift value.
STEP 6: The decodeCodedText method takes the coded text and shift value as inputs.
STEP 7: In the decodeCodedText method, call the getRawEncoded method with coded text
and shift value.
STEP 8: The getRawEncoded method takes coded text and shift value as inputs and returns
the raw encoded text without spaces.
STEP 9: In the getRawEncoded method, create a new string alphabetsShift that represents the
alphabets shifted according to the given shift value.
STEP 10:Iterate through each character of the coded text, remove spaces, and append the
characters to the sb StringBuilder.
STEP 11: Find the index of the letter 'Q' in the alphabets string.
STEP 12: Get the corresponding character at the found index from the alphabetsShift string
and store it in newIndex.
STEP 13: Create a string space by concatenating the newIndex character twice.
STEP 14: Replace all occurrences of the double space (Q) with a single space character in the
sb StringBuilder using the replace method.
STEP 15: Return the modified sb StringBuilder as a string, which is the raw encoded text
without spaces.
STEP 16: In the decodeCodedText method, iterate through each character of the raw encoded
text.
a)If the character is a space, print a space.
b)Otherwise, find the index of the character in the alphabetsShift string and print the
corresponding character from the original alphabets string.
STEP 17: End the program.
codedText String Stores the input coded text provided by the user.
Variable Data Type Description
index int Stores the index of the letter 'Q' in the alphabets string.
scanner.close();
}
// Create a StringBuilder to store the characters of the coded text without spaces
StringBuilder sb = new StringBuilder();
for (String str : codedText.split("\\s"))
sb.append(str);
// Create a string 'space' by concatenating the 'newIndex' character twice (to represent
double spaces)
String space = (char) newIndex + "" + (char) newIndex;
// Replace all occurrences of the double space (Q) with a single space character in the
StringBuilder 'sb'
return sb.toString().replace(space, " ");
}
// Method to decode the coded text using the given shift value
public void decodeCodedText()
{
if (codedText == null)
return;
// Create a string 'alphabetsShift' representing the alphabets shifted according to the
given shift value
String alphabetsShift = alphabets.substring(26 - shift + 1) + alphabets.substring(0, 26 -
shift + 1);
// Get the raw encoded text without spaces using the 'getRawEncoded' method
String rawEncoded = getRawEncoded();