The Programs:-
Question 1:
Write a recursive function that computes the sum of all
numbers from 1 to n where n is given as parameter.
Use the function name as void int sum(int n).
Test your program with the sample data and some
random data:-
Example 1:
Output:
Sum from 1 to 5:
12345
Algorithm
Step 1: Call sum(5)
o n = 5, not the base case, so the function calls sum(4).
Step 2: Call sum(4)
o n = 4, not the base case, so the function calls sum(3).
Step 3: Call sum(3)
o n = 3, not the base case, so the function calls sum(2).
Step 4: Call sum(2)
o n = 2, not the base case, so the function calls sum(1).
Step 5: Call sum(1) (Base Case)
o n = 1, the base case is reached, so return 1.
Step 6: Return to sum(2)
o sum(2) receives 1 from sum(1), so it computes 1 + 2 = 3 and returns 3.
Step 7: Return to sum(3)
o sum(3) receives 3 from sum(2), so it computes 3 + 3 = 6 and returns 6.
Step 8: Return to sum(4)
o sum(4) receives 6 from sum(3), so it computes 6 + 4 = 10 and returns 10.
Step 9: Return to sum(5)
o sum(5) receives 10 from sum(4), so it computes 10 + 5 = 15 and returns 15.
Final Result:
The final result returned by sum(5) is 15.
Java Code:
public class SumRecursion {
// Recursive method to compute the sum of numbers from 1 to n
public static void sum(int n) {
// Base case: if n is 1, simply print 1
if (n == 1) {
System.out.println(1);
return;
// Recursive case: first call sum for n-1, then print n
sum(n - 1);
System.out.print(n + " ");
public static void main(String[] args) {
int n = 5; // Example number
System.out.println("Sum from 1 to " + n + ":");
sum(n); // Call the recursive sum function
Variable Description Table
Question 2:
Write a program to input a string. Check and print
whether it is a palindrome or not. Use a recursive
function that returns a string after reversing the
characters of the given string. A string is said to be a
palindrome if it appears to be same after reversing the
characters.
Test your program with the sample data and some
random data:-
Example 1:
Input:
LEVEL
Output:
It is a palindrome word.
Example 2:-
Input:
HELLO
Output:
It is not a palindrome number
Algorithm
Step 1: Input the String
Read the string from the user.
Step 2: Reverse the String Using Recursion
Define a function reverseString(s):
o If s has 0 or 1 character, return the string s.
o Otherwise, take the last character of s, and call reverseString on the rest of
the string, and append the last character to it.
Step 3: Compare the Original String with the Reversed String
In the main program, call reverseString(s) to get the reversed string.
If the original string s is the same as the reversed string, return true (it’s a
palindrome).
Otherwise, return false (it’s not a palindrome).
Step 4: Output the Result
Print whether the string is a palindrome or not based on the comparison.
Java Code:
import java.util.Scanner;
public class PalindromeChecker {
// Recursive function to reverse the string
public static String reverseString(String s) {
// Base case: if the string is empty or has only one character, return the string
if (s.length() <= 1) {
return s;
} else {
// Recursive step: reverse the rest of the string and append the first character
return s.charAt(s.length() - 1) + reverseString(s.substring(0, s.length() - 1));
// Function to check if the string is a palindrome
public static boolean isPalindrome(String s) {
// Reverse the string using the recursive function
String reversedString = reverseString(s);
// Compare the original string with the reversed string
return s.equals(reversedString);
}
public static void main(String[] args) {
// Scanner to read user input
Scanner scanner = new Scanner(System.in);
// Input a string from the user
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Check if the string is a palindrome
if (isPalindrome(inputString)) {
System.out.println("'" + inputString + "' is a palindrome.");
} else {
System.out.println("'" + inputString + "' is not a palindrome.");
// Close the scanner to prevent resource leak
scanner.close();
}
Variable Description Table
Ouestion 3:
Write a program by using recursive function that finds
and prints the tokens present in the given string.
Hint: Use String Tokenizer to display all the tokens of
the string.
Test your program with the following data and some
random data:-
Example:
Input:
Enter a String: Understanding Computer Science
Output:
Understanding
Computer
Science
Algorithm
Step 1: Start with the input string
Begin by taking the input string that you want to tokenize.
Example Input: "Hello world! This is a sample string."
Step 2: Check for an empty string
If the string is empty (or null), stop the recursion and return. This is the base case.
If the input is empty or null, exit the function.
Example: If the input is "" (empty string), the recursion terminates here.
Step 3: Create a StringTokenizer object
Use StringTokenizer to split the string into individual tokens. A token is defined by any
sequence of characters separated by spaces or other delimiters.
Example: StringTokenizer tokenizer = new
StringTokenizer(inputString);
Step 4: Check for available tokens
Use the hasMoreTokens() method to check if there are any tokens left in the string. If there
are tokens, proceed to print them.
If there are tokens, go to Step 5.
If no tokens are left, terminate the recursion.
Step 5: Print the current token
Print the first token using the nextToken() method of the StringTokenizer object.
Example: The first token "Hello" is printed.
Step 6: Recursive call with remaining string
After printing a token, call the function again with the remaining part of the string (which
contains the remaining tokens). This keeps processing and printing tokens recursively.
Example: If the first token "Hello" was printed, the remaining string to process
might be "world! This is a sample string.".
Step 7: Repeat steps 4-6
The function continues to check for tokens and prints each one, making recursive calls for the
remaining string until all tokens are printed.
Step 8: Termination
Once all tokens have been printed, the recursion ends and the program terminates.
Java Codes:
import java.util.StringTokenizer;
public class RecursiveTokenizer {
// Recursive function to tokenize and print tokens
public static void printTokens(String str) {
// Base case: If the string is empty, return
if (str == null || str.isEmpty()) {
return;
}
// Create StringTokenizer to tokenize the string
StringTokenizer tokenizer = new
StringTokenizer(str);
// Print all tokens in the string
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
public static void main(String[] args) {
// Sample input string
String input = "Hello world! This is a sample
string.";
// Calling the recursive function to print tokens
System.out.println("Tokens in the string:");
printTokens(input);
}
}
Variable Description Table
Ouestion 4:
Write a program to input a number. Use a recursive
function that finds and displays the factors of the
number.
Test your program with the following data and some
random data:-
Example 1:-
Input: 24
Output: The factors are:
2,2,2,3
Example 2:-
Input: 12
Output: The factors are:
1,2,3,4,6,12
Algorithm
Step 1: Start
Input the number n for which you want to find the factors.
Step 2: Define the Recursive Function
Define a function findFactors(n, i) where:
o n is the number for which we want to find the factors.
o i is the current number being checked (starting from 1).
Step 3: Base Case
In the function findFactors(n, i), check if i > n.
o If i > n, stop the recursion (this is the termination condition).
o If i <= n, proceed to the next step.
Step 4: Check if i is a Factor of n
If n % i == 0, then i is a factor of n.
o Print i as one of the factors of n.
Step 5: Recursive Call
Call the function findFactors(n, i + 1) to check the next number (i + 1).
o This step moves to the next potential factor and repeats the process.
Step 6: Repeat Steps
Repeat Step 3, Step 4, and Step 5 incrementing i by 1 each time until i becomes
greater than n.
Step 7: Stop Recursion
When i > n, the recursion stops, and all the factors have been printed.
Java Codes:
import java.util.Scanner;
public class FactorFinder {
// Recursive method to find and print the factors of a number
public static void findFactors(int num, int i) {
// Base case: When i exceeds num, stop the recursion
if (i > num) {
return;
// If num is divisible by i, it's a factor, so print it
if (num % i == 0) {
System.out.print(i + " ");
// Recursive call with the next number (i + 1)
findFactors(num, i + 1);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input number from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("The factors of " + number + " are:");
// Call the recursive function starting from 1
findFactors(number, 1);
}
Variable Description Table:
Question 5:
A 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:
Example:-
INPUT:
N = 726
OUTPUT:
48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Algorithm
Step 1: Input the total number of boxes to be packed (N).
Step 2: Validate the input:
Ensure N is between 1 and 1000.
Step 3: Define the carton sizes: [48, 24, 12, 6].
Step 4: Initialize an array cartonCount[] to store the number of cartons used for each size.
Step 5: Loop through each carton size (starting from largest to smallest):
For each size, calculate the number of cartons needed (N // cartonSize).
Update the remaining number of boxes (N % cartonSize).
Store the number of cartons used in the cartonCount[] array.
Step 6: If there are leftover boxes, use one 6-box carton to pack the remaining boxes.
Step 7: Output the number of cartons used for each size.
Step 8: End the program.
Java Codes:
import java.util.Scanner;
public class CartonPacking {
public static void calculateCartons(int N) {
// Define the carton sizes in descending order
int[] cartonSizes = {48, 24, 12, 6};
// Array to store the number of cartons for each
size
int[] cartonCount = new int[cartonSizes.length];
// Loop through the available carton sizes in
descending order
for (int i = 0; i < cartonSizes.length; i++) {
// Calculate how many of these cartons are
needed
cartonCount[i] = N / cartonSizes[i];
// Subtract the number of boxes packed by
these cartons
N -= cartonCount[i] * cartonSizes[i];
}
// If there are any boxes left, use the smallest
carton (6 boxes)
if (N > 0) {
cartonCount[3] += 1;
}
// Display the carton breakdown
System.out.println("\nCarton break-up:");
for (int i = 0; i < cartonSizes.length; i++) {
if (cartonCount[i] > 0) {
System.out.println(cartonSizes[i] + "-box
cartons: " + cartonCount[i]);
}
}
}
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Accept the number of boxes to be packed
System.out.print("Enter the number of boxes to be
packed (max 1000): ");
int N = scanner.nextInt();
// Validate input
if (N < 1 || N > 1000) {
System.out.println("Please enter a number
between 1 and 1000.");
} else {
// Call the method to calculate and display the
carton break-up
calculateCartons(N);
}
// Close the scanner object
scanner.close();
}
}
Variable Description Table
Question 6:
The names of the teams participating in a competition
should be displayed on a banner
vertically, to accommodate as many teams as possible
in a single banner. Design a program to
accept the names of N teams, where 2 < N < 9 and
display them in vertical order, side by side
with a horizontal tab (i.e. eight spaces).
Test your program for the following data and some
random data:
Example:-
INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote
OUTPUT:
ERC
moo
uay
sdo
t
Re
o
l
s
Algorithm
Step 1: Input the Number of Teams
1. Ask the user for the number of teams, N (3 ≤ N ≤ 8).
2. If N is invalid (less than 3 or greater than 8), display an error and exit.
Step 2: Input the Names of Teams
1. Initialize an empty list teams.
2. For each team (from 1 to N), prompt the user for the team name and store it in teams.
Step 3: Find the Longest Team Name
1. Loop through teams to find the longest name (maxLength).
Step 4: Display the Names Vertically
1. For each character position (from 0 to maxLength - 1):
o For each team, print the character at that position or a space if the team name
is shorter.
o Separate each name with a tab (\t).
Java Codes:
import java.util.Scanner;
public class TeamBanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Accept the number of teams (between 3 and 8)
System.out.print("Enter the number of teams (between 3 and 8): ");
int N = scanner.nextInt();
scanner.nextLine(); // Consume the newline character left by nextInt()
if (N < 3 || N > 8) {
System.out.println("Invalid number of teams. Please enter a number between 3 and
8.");
return;
// Accept the names of N teams
String[] teams = new String[N];
for (int i = 0; i < N; i++) {
System.out.print("Enter the name of team " + (i + 1) + ": ");
teams[i] = scanner.nextLine();
// Find the longest team name length for proper alignment
int maxLength = 0;
for (String team : teams) {
if (team.length() > maxLength) {
maxLength = team.length();
}
// Display the team names vertically, with tabs between them
for (int i = 0; i < maxLength; i++) { // Loop through the longest name length
for (int j = 0; j < N; j++) { // Loop through all teams
if (i < teams[j].length()) {
System.out.print(teams[j].charAt(i) + "\t"); // Print character with tab
} else {
System.out.print(" \t"); // Print a space for shorter names
System.out.println(); // Move to the next line after each iteration
scanner.close();
Variable Description Table
Question 7:
Design a program to accept a day number
(between 1 and 366), year (in 4 digits)
from the user
to generate and display the corresponding
date. Also, accept 'N' (1 <= N <= 100) from
the user
to compute and display the future date
corresponding to 'N' days after the
generated date.
Display an error message if the value of
the day number, year and N are not within
the limit or
not according to the condition specified.
Test your program with the following data
and some random data:
Example 1
INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY,
2019
Step 1: Input the Data:
Read dayNumber (1 to 366).
Read year (4-digit integer).
Read N (1 to 100).
Step 2: Validate the Inputs:
Check if dayNumber is valid for the given year.
o For non-leap years, dayNumber should be between 1 and 365.
o For leap years, dayNumber should be between 1 and 366.
Ensure N is between 1 and 100.
Step 3: Check Leap Year:
If (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0), then it's a
leap year.
Step 4: Generate Corresponding Date:
Calculate the date corresponding to dayNumber in the given year.
o Start from January 1st and add dayNumber - 1 days.
Step 5: Calculate Future Date:
Add N days to the generated date.
Step 6: Display the Results:
Output the generated date and the future date after adding N days.
Step 7: Error Handling:
Display an error message if any input is out of range or invalid.
Java Codes:
import java.util.Scanner;
import java.time.LocalDate;
import
java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateCalculator {
// Function to check if the year is a leap
year
public static boolean isLeapYear(int
year) {
return (year % 4 == 0 && year % 100 !
= 0) || (year % 400 == 0);
}
// Function to generate the date based
on the day number and year
public static LocalDate generateDate(int
dayNumber, int year) {
if (dayNumber < 1 || dayNumber >
366) {
System.out.println("Error: Day
number must be between 1 and 366.");
return null;
}
if (!isLeapYear(year) && dayNumber >
365) {
System.out.println("Error: Day
number for a non-leap year must be
between 1 and 365.");
return null;
}
if (isLeapYear(year) && dayNumber >
366) {
System.out.println("Error: Day
number for a leap year must be between
1 and 366.");
return null;
}
// Generate the date from the day
number and year
LocalDate startDate =
LocalDate.of(year, 1, 1); // January 1st of
the given year
return
startDate.plusDays(dayNumber - 1); //
Day number starts at 1, so subtract 1
}
// Function to calculate the future date
after N days
public static LocalDate
calculateFutureDate(LocalDate startDate,
int N) {
if (N < 1 || N > 100) {
System.out.println("Error: N must
be between 1 and 100.");
return null;
}
return startDate.plusDays(N); // Add
N days to the start date
}
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
try {
// Take day number and year as
input
System.out.print("Enter the day
number (1 to 366): ");
int dayNumber = scanner.nextInt();
System.out.print("Enter the year (4
digits): ");
int year = scanner.nextInt();
// Generate the date based on the
input
LocalDate generatedDate =
generateDate(dayNumber, year);
if (generatedDate == null) {
return; // Exit if the date
generation failed
}
// Display the generated date
System.out.println("Generated
Date: " + generatedDate);
// Take the N value to calculate the
future date
System.out.print("Enter the
number of days (N) to calculate the future
date (1 <= N <= 100): ");
int N = scanner.nextInt();
// Calculate and display the future
date
LocalDate futureDate =
calculateFutureDate(generatedDate, N);
if (futureDate != null) {
System.out.println("Future Date
after " + N + " days: " + futureDate);
}
} catch (Exception e) {
System.out.println("Invalid input!
Please enter valid numbers.");
} finally {
scanner.close();
}
}
}
Variable Description Table
Question 8:
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:
Sort the elements of the single-
dimensional array in ascending order
using any standard sorting
technique and display the sorted
elements.
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:
1258
1251
1212
1125
Display the filled matrix in the above
format.
Test your program for the following data
and some random data:
Example:-
INPUT:
N=3
ENTER ELEMENTS OF SINGLE
DIMENSIONAL ARRAY: 3 1 7
OUTPUT:
SORTED ARRAY: 1 3 7
FILLED MATRIX
137
131
113
Algorithm
Step 1: Input N
Ask the user to enter a value N (where 2 < N < 10).
If N is not in the valid range, display an error message and exit the program.
Step 2: Input array a[]
Declare an array a[] of size N.
Prompt the user to enter N positive integers to fill the array a[].
Step 3: Sort array a[]
Sort the array a[] in ascending order.
Step 4: Fill matrix b[][]
Declare a matrix b[][] of size N x N.
For each element b[i][j], calculate:
b[i][j] = a[i] * 100 + a[j] * 10 + a[N-1-j].
Step 5: Output
Print the sorted array a[].
Print the matrix b[][] row by row.
Java Codes:
import java.util.Scanner;
import java.util.Arrays;
public class MatrixFiller {
// Function to sort the array
public static void sortArray(int[] arr) {
Arrays.sort(arr); // Using Arrays.sort()
to sort the array
}
// Function to fill and display the matrix
public static void fillMatrix(int[] arr, int
N) {
// Initialize an empty matrix
int[][] matrix = new int[N][N];
// Fill the matrix based on the sorted
array
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = arr[i] * 100 + arr[j]
* 10 + arr[N - 1 - j];
}
}
// Display the matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j]);
}
System.out.println(); // Print new
line after each row
}
}
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
// Input: size of the matrix (N) and
array a[]
System.out.print("Enter the value of
N (2 < N < 10): ");
int N = scanner.nextInt();
if (N <= 2 || N >= 10) {
System.out.println("N should be
greater than 2 and less than 10.");
return;
}
// Declare a single-dimensional array
a[]
int[] a = new int[N];
for (int i = 0; i < N; i++) {
System.out.print("Enter a positive
integer for a[" + i + "]: ");
a[i] = scanner.nextInt();
}
// Sort the array
System.out.println("Array before
sorting: " + Arrays.toString(a));
sortArray(a);
System.out.println("Array after
sorting: " + Arrays.toString(a));
// Fill and display the square matrix
System.out.println("\nThe matrix b[]
[] filled in the specified pattern:");
fillMatrix(a, N);
scanner.close();
}
}
Variable Description Table
Question 9:
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 uppercase.
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).
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 with repeated
alphabets, for example ABB would
become ABBA
and not ABBBA and XAZZZ becomes
XAZZZAX.
[Palindrome word: Spells same from
either side. Example: DAD, MADAM etc.]
(c) Display the original sentence along
with the converted sentence.
Test your program for the following data
and some random data:
Example 1
INPUT:
THE BIRD IS FLYING.
OUTPUT:
THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNIYLF
Q.10. 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.
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:
Display the original matrix.
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 DECIMAL EQUIVALENT
1 4 4 100
Algorithm
Step 1: Accept Input
Step 1.1: Read the sentence from the user.
Step 1.2: Ensure the sentence ends with ., ?, or !.
Step 2: Validate Sentence
Step 2.1: If the sentence does not end with a valid punctuation mark, output "Invalid
sentence".
Step 2.2: Remove the last character (punctuation).
Step 2.3: Split the sentence into words and check if all words are uppercase and
separated by a single space.
Step 2.4: If invalid (e.g., contains lowercase or extra spaces), output "Invalid
sentence".
Step 3: Process Words
Step 3.1: For each word:
o Step 3.1.1: If the word is a palindrome, keep it unchanged.
o Step 3.1.2: If not, remove the last character, reverse the rest, and append it to
the word to form a new palindrome.
Step 4: Output Result
Step 4.1: Reconstruct the sentence by joining the processed words.
Step 4.2: Append the original punctuation mark back.
Step 4.3: Display the original and converted sentences.
Java Codes:
import java.util.Scanner;
public class PalindromeSentenceConverter {
// Check if a word is a palindrome
public static boolean isPalindrome(String word) {
int len = word.length();
for (int i = 0; i < len / 2; i++) {
if (word.charAt(i) != word.charAt(len - i - 1)) {
return false;
return true;
}
// Convert a non-palindrome word to a palindrome by appending its reverse (excluding last
character)
public static String convertToPalindrome(String word) {
String reversePart = word.substring(0, word.length() - 1); // Exclude the last character
String reversed = new StringBuilder(reversePart).reverse().toString();
return word + reversed; // Concatenate word with reversed part
// Check if the sentence is valid
public static boolean isValidSentence(String sentence) {
// Check if sentence ends with '.', '?', or '!'
if (sentence.isEmpty() ||
!(sentence.endsWith(".") || sentence.endsWith("?") || sentence.endsWith("!"))) {
return false;
// Remove the last character (punctuation)
sentence = sentence.substring(0, sentence.length() - 1);
// Check if words are in uppercase and are separated by a single space
String[] words = sentence.split(" ");
for (String word : words) {
if (!word.matches("[A-Z]+")) { // Check if each word is uppercase
return false;
}
return true;
// Main method to process the sentence
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Accept input sentence
System.out.println("Enter a sentence (terminated by '.', '?', or '!'):");
String sentence = scanner.nextLine();
// Validate the sentence
if (!isValidSentence(sentence)) {
System.out.println("Invalid sentence.");
return;
// Process the words in the sentence
String[] words = sentence.substring(0, sentence.length() - 1).split(" "); // Exclude
punctuation mark
StringBuilder convertedSentence = new StringBuilder();
for (String word : words) {
if (isPalindrome(word)) {
convertedSentence.append(word); // Append palindrome words as they are
} else {
convertedSentence.append(convertToPalindrome(word)); // Convert non-
palindrome words
convertedSentence.append(" "); // Add a space between words
// Append the original punctuation mark at the end
convertedSentence.append(sentence.charAt(sentence.length() - 1));
// Display the original and converted sentences
System.out.println("Original sentence: " + sentence);
System.out.println("Converted sentence: " + convertedSentence.toString().trim());
Variable Description Table