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

Computer 1

The document outlines several programming tasks involving recursion in Java, including calculating the sum of numbers, checking for palindromes, tokenizing strings, finding factors, packing cartons, and displaying team names vertically. Each task includes a detailed algorithm and sample Java code for implementation. Additionally, it provides examples for testing the programs with various inputs.

Uploaded by

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

Computer 1

The document outlines several programming tasks involving recursion in Java, including calculating the sum of numbers, checking for palindromes, tokenizing strings, finding factors, packing cartons, and displaying team names vertically. Each task includes a detailed algorithm and sample Java code for implementation. Additionally, it provides examples for testing the programs with various inputs.

Uploaded by

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

Page-1

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.

General
Page-2

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

General
Page-3

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.

General
Page-4

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

General
Page-5

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

General
Page-6

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

General
Page-7

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.

General
Page-8

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

General
Page-9

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

General
Page-10

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.

Page-11

General
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();

Page-12

System.out.println("The factors of " + number + " are:");

General
// 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

Page-13

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

Page-14

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

Page-15

// Display the carton breakdown

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

Page-16

// Close the scanner object

General
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:

Page-17

Example:-

General
INPUT:
N=3

Team 1: Emus

Team 2: Road Rols

Team 3: Coyote

OUTPUT:
ERC

moo

uay

sdo

Re

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.

Page-18

Step 2: Input the Names of Teams

General
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

Page-19

String[] teams = new String[N];

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

General
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();

Page-20

Variable Description Table

General
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

Page-21

OUTPUT:
DATE: 12TH SEPTEMBER, 2018

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

Page-22

Step 6: Display the Results:

 Output the generated date and the future date after adding N days.

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

Page-23

if (isLeapYear(year) && day Number > 366) {

System.out.println("Error: Day number for a leap year must be between 1 and 366.");

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

Page-24

int year = scanner.nextInt();

// Generate the date based on the input

General
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();

Page-25

Variable Description Table

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

Page-26

Test your program for the following data and some random data:

Example:-

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

Page-27

Step 5: Output

 Print the sorted array a[].

General
 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++) {

Page-28

System.out.print(matrix[i][j]);

General
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

Page-29

System.out.println("Array before sorting: " + Arrays.toString(a));

sortArray(a);

General
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

Page-30

Question 9:

General
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

Algorithm
Step 1: Input the Sentence:

 Accept a sentence from the user which should be in uppercase.


 The sentence must end with one of the punctuation marks: ., ?, or !.

Step 2: Validate the Sentence:

General
Step 2.1: Check if the sentence ends with a valid punctuation mark (., ?, or !).

 If the sentence does not end with any of these punctuation marks, print "Invalid
sentence!" and STOP.

Step 2.2: Ensure that all words in the sentence are in uppercase and separated by exactly one
space.

 If any word is not in uppercase, or if there are multiple spaces between words, print
"Invalid sentence!" and STOP.

Step 3: Remove the Punctuation:

Step 3.1: Remove the punctuation mark (., ?, or !) from the end of the sentence.

 Store the punctuation mark separately to add it back later.

Step 4: Split the Sentence into Words:

Step 4.1: Split the sentence into individual words using spaces as separators.

Step 5: Process Each Word:

Step 5.1: For each word in the sentence:

 Step 5.1.1: Check if the word is a palindrome.


o A palindrome is a word that reads the same forwards and backwards.
o Step 5.1.2: If the word is a palindrome, leave it unchanged.
o Step 5.1.3: If the word is not a palindrome:
 Step 5.1.3.1: Exclude the last character of the word.
 Step 5.1.3.2: Reverse the remaining part of the word.
 Step 5.1.3.3: Concatenate the original word with the reversed part to
form a palindrome word.

Step 6: Reconstruct the Converted Sentence:

Step 6.1: Join all the processed words back together with a single space in between.

Step 6.2: Append the previously removed punctuation mark to the end of the sentence.

Step 7: Output the Sentences:

Step 7.1: Display the original sentence. Step 7.2: Display the converted sentence.

General
Java Codes:-
import java.util.Scanner;

public class SentenceProcessor {

// Function to check if a word is a palindrome

public static boolean isPalindrome(String word) {

String reversed = new StringBuilder(word).reverse().toString();

return word.equals(reversed);

// Function to convert a non-palindrome word into a palindrome

public static String convertToPalindrome(String word) {

if (isPalindrome(word)) {

return word;

} else {

String reverse = new StringBuilder(word.substring(0, word.length() -


1)).reverse().toString();

return word + reverse;

// Function to check the validity of the sentence

public static boolean isValidSentence(String sentence) {

// Check if sentence ends with one of the allowed punctuation marks

if (!(sentence.endsWith(".") || sentence.endsWith("?") || sentence.endsWith("!"))) {

return false;

General
// Ensure that the words are separated by a single space and all letters are uppercase

String[] words = sentence.substring(0, sentence.length() - 1).split(" "); // Remove the


punctuation

for (String word : words) {

if (!word.equals(word.toUpperCase())) {

return false;

return true;

// Main program logic

public static void processSentence(String sentence) {

if (!isValidSentence(sentence)) {

System.out.println("Invalid sentence!");

return;

// Display the original sentence

System.out.println("Original sentence: " + sentence);

// Removing the punctuation at the end and split the words

char punctuation = sentence.charAt(sentence.length() - 1);

String[] words = sentence.substring(0, sentence.length() - 1).split(" ");

// Convert the words into palindrome words

StringBuilder convertedSentence = new StringBuilder();

for (String word : words) {

General
String convertedWord = convertToPalindrome(word);

convertedSentence.append(convertedWord).append(" ");

// Remove the extra space at the end and append the punctuation

String result = convertedSentence.toString().trim() + punctuation;

// Display the converted sentence

System.out.println("Converted sentence: " + result);

public static void main(String[] args) {

// Create a scanner object to read input

Scanner scanner = new Scanner(System.in);

// Accept the sentence from the user

System.out.print("Enter a sentence: ");

String sentence = scanner.nextLine();

// Process the sentence

processSentence(sentence);

// Close the scanner

scanner.close();

Variable Description Table

General
Question 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:

General
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: Input Validation for Matrix Dimensions (M and N)

 Step 1.1: Ask the user to input the number of rows M and the number of columns N.
 Step 1.2: Ensure that M > 0 and M < 10 (valid range for rows).
 Step 1.3: Ensure that N > 2 and N < 6 (valid range for columns).
 Step 1.4: If the values of M or N are outside the valid range, prompt the user to re-enter
the values for M and N until valid inputs are provided.

Step 2: Input Matrix Elements

 Step 2.1: Initialize a 2D array matrix[M][N] to store the matrix elements.


 Step 2.2: Loop through each row (from 1 to M):
o Step 2.3: For each row, ask the user to input N octal digits (values between 0
and 7) for that row.
o Step 2.4: Ensure that each input value for a matrix element is between 0 and 7
(inclusive). If any input is outside this range, prompt the user to re-enter that
value.
o Step 2.5: Store the valid digits in the corresponding positions in the matrix.

Step 3: Display the Matrix

 Step 3.1: Display the matrix in a readable format where each row is printed on a new
line.
 Step 3.2: Print the elements of the matrix separated by spaces.

Step 4: Calculate and Display the Decimal Equivalent of Each Row

 Step 4.1: For each row in the matrix:


o Step 4.2: Initialize a variable decimal_value = 0 to store the decimal
equivalent of the row.
o Step 4.3: Loop through the elements of the row (from 0 to N-1):

General
 Step 4.4: Calculate the decimal value of each element using the
formula: \text{decimal_value} += \text{row}[i] \times 8^{(N-i-1)}
 Step 4.5: Print the row of octal numbers followed by its calculated
decimal equivalent.

Step 5: End of Program

 Step 5.1: The program terminates after displaying the matrix and its decimal
equivalents.

Java Codes:-
import java.util.Scanner;

public class MatrixOctalToDecimal {

// Function to input the matrix elements

public static int[][] inputMatrix(int M, int N, Scanner sc) {

int[][] matrix = new int[M][N];

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

System.out.println("ENTER ELEMENTS FOR ROW " + (i + 1) + ": ");

for (int j = 0; j < N; j++) {

while (true) {

int element = sc.nextInt();

if (element >= 0 && element <= 7) {

matrix[i][j] = element;

break;

} else {

System.out.println("Please enter a digit between 0 and 7.");

return matrix;

General
// Function to display the matrix

public static void displayMatrix(int[][] matrix) {

System.out.println("FILLED MATRIX");

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

// Function to calculate the decimal equivalent of each row

public static void calculateDecimal(int[][] matrix) {

System.out.println("\nDECIMAL EQUIVALENT");

for (int i = 0; i < matrix.length; i++) {

int decimalValue = 0;

for (int j = 0; j < matrix[i].length; j++) {

decimalValue += matrix[i][j] * Math.pow(8, matrix[i].length - 1 - j);

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println(decimalValue);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

General
// Input the number of rows (M) and columns (N)

int M = 0, N = 0;

while (true) {

System.out.print("Enter the number of rows (M): ");

M = sc.nextInt();

System.out.print("Enter the number of columns (N): ");

N = sc.nextInt();

if (M > 0 && M < 10 && N > 2 && N < 6) {

break;

} else {

System.out.println("Please ensure M is between 1 and 9, and N is between 3 and


5.");

// Input the matrix

int[][] matrix = inputMatrix(M, N, sc);

// Display the matrix

displayMatrix(matrix);

// Calculate and display the decimal equivalent of each row

calculateDecimal(matrix);

sc.close();

General
Variable Description Table

General
General

You might also like