0% found this document useful (0 votes)
4 views31 pages

Computer Program 2

The document outlines a series of programming tasks that involve writing recursive functions in Java. These tasks include computing sums, checking palindromes, extracting tokens from strings, finding factors, and managing packing cartons. Each task is accompanied by an algorithm, Java code, and variable descriptions to guide implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views31 pages

Computer Program 2

The document outlines a series of programming tasks that involve writing recursive functions in Java. These tasks include computing sums, checking palindromes, extracting tokens from strings, finding factors, and managing packing cartons. Each task is accompanied by an algorithm, Java code, and variable descriptions to guide implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 31

INDEX

SI. NO. PROGRAM

1. Write a recursive function that computes the sum of all numbers from 1 to nwhere n is given as
parameter.use the function name as void int sum(n).

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.

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.
Sample Input:
Enter a String: Understanding Computer Science
Sample Output:
UnderstandingComputerScience

4. Write a program to input a number. Use a recursive function that finds and displays the factors of the
number.
Example:
Input: 24
Output: The factors are:
2, 2, 2, 3

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 cartonsused 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

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

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
pg. 1
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018

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.

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.

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.

pg. 2
QUESTION 1:-
Write a recursive function that computes the sum of all numbers from 1 to nwhere n is given as parameter.use the
function name as void int sum(n).

Algorithm:
1. Base Case: If is equal to 1, return 1 since the sum of the first 1 natural number is 1.

2. Recursive Case: Otherwise, return added to the sum of numbers from 1 to .

3. Function Signature: void int sum(int n) is incorrect; Java methods should have a proper return type. We'll use int
sum(int n).

4. Call Stack Behavior: The function keeps calling itself with until it reaches the base case.

JAVA CODE:-
import java.util.Scanner;

public class SumCalculator {

// Recursive method to calculate sum from 1 to n

public static int sum(int n) {

// Base case: if n is 0 or negative, return 0

if (n <= 0) {

return 0;

// Recursive step: sum the current number and call the function for n-1

return n + sum(n - 1);

public static void main(String[] args) {

// Scanner to take input from the user

Scanner sc = new Scanner(System.in);

// Asking user for input

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

int n = sc.nextInt();

// Calling the recursive sum function and displaying the result

int result = sum(n);

System.out.println("The sum of all numbers from 1 to " + n + " is: " + result);

// Close the scanner

pg. 3
sc.close();

VARIABLE DESCRIPTION TABLE:


SI.NO. VARIABLE DATA TYPE PURPOSE
1. sc Scanner Object of scanner class
2. n Int To store the input
3. result Int Stores the sum

OUTPUT:

pg. 4
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.

Algorithm
1. Start

2. Input a string from the user

3. Convert the string to uppercase to make it case insensitive

4. Call a recursive function to reverse the string

5. Compare the original string with the reversed string

6. If they are equal, print "It is a palindrome word."

7. Otherwise, print "It is not a palindrome word."

8. END

Java Code
import java.util.Scanner;

public class PalindromeChecker {

// Recursive function to reverse a string

public static String reverseString(String str) {

if (str.isEmpty()) {

return str;

return reverseString(str.substring(1)) + str.charAt(0);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input string from user

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

String originalString = scanner.nextLine();

pg. 5
// Convert string to uppercase to handle case insensitivity

String upperString = originalString.toUpperCase();

// Reverse the string using recursion

String reversedString = reverseString(upperString);

// Check if the original and reversed strings are equal

if (upperString.equals(reversedString)) {

System.out.println("It is a palindrome word.");

} else {

System.out.println("It is not a palindrome word.");

scanner.close();

Variable Description Table


SI. NO. VARIABLE DATA TYPE PURPOSE
1. scanner Scanner Object of Scanner class
2. originalstring String To store the original String
3. upperString String To store the uppercase
string
4. ReversedString String To store the reversed
String

OUTPUT:

pg. 6
QUESTION 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.

Sample Input:

Enter a String: Understanding Computer Science

Sample Output:

UnderstandingComputerScience

Algorithm
1. Start

2. Input a string from the user

3. Call a recursive function to extract and print tokens from the string

4. Use StringTokenizer to split the string into tokens

5. In the recursive function:

If more tokens exist, print the current token

Call the function recursively with the remaining tokens

6. End

Java Code
import java.util.Scanner;

import java.util.StringTokenizer;

public class StringTokenizerRecursive {

// Recursive function to print tokens

public static void printTokens(StringTokenizer tokenizer) {

if (!tokenizer.hasMoreTokens()) {

return; // Base case: No more tokens to process

System.out.print(tokenizer.nextToken()); // Print current token

printTokens(tokenizer); // Recursive call for the next token

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


pg. 7
// Input string from user

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

String inputString = scanner.nextLine();

// Create StringTokenizer to extract words

StringTokenizer tokenizer = new StringTokenizer(inputString);

// Call recursive function to print tokens

printTokens(tokenizer);

scanner.close();

Variable Description Table


SI. NO. VARIABLE DATA TYPE PURPOSE
1. scanner Scanner Object of scanner class
2. inputstring String Stores the user input
3. tokenizer StringTokenizer Used to break string into
tokens

OUTPUT:

QUESTION 4:-
pg. 8
Write a program to input a number. Use a recursive function that finds and displays the factors of the number.

Example:

Input: 24

Output: The factors are:

2, 2, 2, 3

ALGORITHM:-
1. Start

2. Input a number from the user

3. Call a recursive function to find and print the factors

4. In the recursive function:

If the number becomes 1, return (base case)

Find the smallest factor (starting from 2)

Print the factor and divide the number by this factor

Recursively call the function with the new number

5. End

Java Code
import java.util.Scanner;

public class FactorizationRecursive {

// Recursive function to find and display factors

public static void findFactors(int number, int divisor) {

if (number == 1) {

return; // Base case: When number is fully factored

if (number % divisor == 0) {

System.out.print(divisor + " "); // Print the factor

findFactors(number / divisor, divisor); // Recursive call with reduced number

} else {

findFactors(number, divisor + 1); // Increase divisor if it's not a factor

}
pg. 9
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input number from user

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

int number = scanner.nextInt();

System.out.print("The factors are: ");

findFactors(number, 2); // Start finding factors from 2

scanner.close();

Variable Description Table


SI.NO. VARIABLE DATA TYPE PURPOSE
1. scanner Scanner Object of scanner class
2. Number Int To store the user input
3. Divisor Int To represent the current
divisor.

OUTPUT:

QUESTION 5:-
pg. 10
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 cartonsused 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

Algorithm:-
1. Start

2. Input the number of boxes N (1 ≤ N ≤ 1000)

3. Initialize an array with carton sizes {48, 24, 12, 6} in descending order

4. Initialize variables to store the number of cartons used and remaining boxes

5. Iterate through the carton sizes:

Calculate how many cartons of the current size can fit into the remaining boxes

Update the remaining boxes

Print the carton size and quantity used if it's greater than 0

6. If any boxes remain (less than 6), add one extra carton of size 6

7. Print the total number of cartons used and the total number of boxes

8. End

Java Code
import java.util.Scanner;

public class PackingCartons {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input the number of boxes

pg. 11
System.out.print("Enter the number of boxes (max 1000): ");

int N = scanner.nextInt();

// Array of carton sizes in descending order

int[] cartonSizes = {48, 24, 12, 6};

int totalCartons = 0, remainingBoxes = N;

System.out.println("Carton Breakdown:");

// Process each carton size

for (int size : cartonSizes) {

int count = remainingBoxes / size;

remainingBoxes %= size;

if (count > 0) {

System.out.println(size + " * " + count + " = " + (size * count));

totalCartons += count;

// If any boxes remain, add one extra 6-box carton

if (remainingBoxes > 0) {

System.out.println("6 * 1 = 6");

totalCartons++;

remainingBoxes = 0;

// Display final results

System.out.println("Remaining boxes = " + remainingBoxes);

System.out.println("Total number of boxes = " + N);

System.out.println("Total number of cartons = " + totalCartons);

scanner.close();

pg. 12
}

---

Variable Description Table


SI. NO. VARIABLE DATA TYPE PURPOSE
1. Scanner Scanner object of scanner class
2. N Int To store total no. of boxes
3. Cartoonsize Int[] Array to store variety of
cartoon box size
4. Totalcartoon Int To store the total no. of
cartoon
5. remainingboxes Int To store no. of boxes to be
packed
6. Size Int To represent the current
cartoon size
7. Count Int Stores the no. of cartoons
of current size

OUTPUT:

QUESTION 6:-
pg. 13
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).

ALGORITHM:-
1. Start

2. Input the number of teams N (where 2 < N < 9)

3. Create an array to store the team names

4. Determine the length of the longest team name

5. Iterate through each character position (row-wise):

For each team, if the character at the current position exists, print it

Otherwise, print a space

Separate the columns with a horizontal tab (\t)

6. Print the output in a vertical format

7. End

Java Code
import java.util.Scanner;

public class VerticalBanner {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input number of teams

System.out.print("Enter the number of teams (between 3 and 8): ");

int N = scanner.nextInt();

scanner.nextLine(); // Consume newline

// Validate input

if (N <= 2 || N >= 9) {

System.out.println("Invalid input. N must be between 3 and 8.");

return;

pg. 14
// Array to store team names

String[] teams = new String[N];

// Input team names

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

System.out.print("Team " + (i + 1) + ": ");

teams[i] = scanner.nextLine();

// Find the maximum length among team names

int maxLength = 0;

for (String team : teams) {

if (team.length() > maxLength) {

maxLength = team.length();

// Print the names in vertical order

System.out.println("\nOutput:");

for (int i = 0; i < maxLength; i++) { // Iterate through rows

for (int j = 0; j < N; j++) { // Iterate through columns (teams)

if (i < teams[j].length()) {

System.out.print(teams[j].charAt(i)); // Print character if exists

} else {

System.out.print(" "); // Print space for shorter names

System.out.print("\t"); // Add horizontal tab

System.out.println(); // Move to next row

scanner.close();

pg. 15
Variable Description Table
SINO. VARIABLE DATA TYPE PURPOSE
1. scanner Scanner An object of scanner class
2. N Int To store the no. of teams
3. Teams String[] Array to store the name of
the team
4. I Int To regulate inner loop
5. J Int To regulate outer loop
6. Maxleangth Int Stores the length of the
longest team
7. Team String To represent each team
name.

OUTPUT:

QUESTION 7:-

pg. 16
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

Algorithm
1. Start

2. Input the day number (between 1 and 366) and year (4-digit format) from the user.

3. Validate if the year is a leap year or not. A year is a leap year if:

It is divisible by 4, and

Not divisible by 100 unless also divisible by 400.

4. Check if the day number is within the valid range (1-365 for non-leap years, 1-366 for leap years). If not, display an
error message and terminate.

5. Convert the day number into an actual date (day, month, year).

6. Display the generated date in the format: DDTH MONTH, YYYY

7. Input N (between 1 and 100) from the user. If invalid, display an error message and terminate.

8. Compute the future date by adding N days to the generated date, handling month and year transitions correctly.

9. Display the new future date.

10. End.

Java Code
import java.util.Scanner;

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

pg. 17
public class FutureDateCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input: Day number and Year

System.out.print("Enter the day number (1-366): ");

int dayNumber = scanner.nextInt();

System.out.print("Enter the year (4-digit format): ");

int year = scanner.nextInt();

// Validate leap year

boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

// Validate day number

if (dayNumber < 1 || dayNumber > (isLeapYear ? 366 : 365)) {

System.out.println("Invalid day number for the given year.");

return;

// Convert day number to actual date

LocalDate date = LocalDate.ofYearDay(year, dayNumber);

// Display the formatted date

System.out.println("DATE: " + formatDate(date));

// Input: N days to add

System.out.print("Enter the number of days after (1-100): ");

int N = scanner.nextInt();

// Validate N

if (N < 1 || N > 100) {

System.out.println("Invalid input for N. It must be between 1 and 100.");

return;

pg. 18
}

// Calculate future date

LocalDate futureDate = date.plusDays(N);

// Display the future date

System.out.println("DATE AFTER " + N + " DAYS: " + formatDate(futureDate));

scanner.close();

// Method to format the date in the required format (e.g., 12TH SEPTEMBER, 2018)

private static String formatDate(LocalDate date) {

int day = date.getDayOfMonth();

String month = date.getMonth().toString(); // Get month name in uppercase

int year = date.getYear();

// Convert month to title case

month = month.charAt(0) + month.substring(1).toLowerCase();

return day + getDaySuffix(day) + " " + month + ", " + year;

// Method to get the correct day suffix (st, nd, rd, th)

private static String getDaySuffix(int day) {

if (day >= 11 && day <= 13) return "TH"; // Special case for 11th, 12th, 13th

switch (day % 10) {

case 1: return "ST";

case 2: return "ND";

case 3: return "RD";

default: return "TH";

pg. 19
Variable Description Table
SI.NO. VARIABLE DATA TYPE PURPOSE
1. Scanner Scanner Object of scanner class
2. DayNumber Int Stores the daynumber
3. Year Int Stores the year
4. isLeapYear boolean Stores whether the year is
leap or not
5. date Int Stores the date on that day
6. N Int To store the no. of days to
add
7. Future date Int To store the future date.

OUTPUT:

QUESTION 8:-
pg. 20
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.

Algorithm
1. Start

2. Input N (size of the matrix), ensuring 2 < N < 10. If invalid, display an error and terminate.

3. Declare a single-dimensional array a[] of size N.

4. Input N positive integers into a[].

5. Sort the array a[] in ascending order (using any sorting method, e.g., Bubble Sort).

6. Declare an N × N square matrix b[][].

7. Fill b[][] such that:

The first row contains a[] in order.

The second row is a cyclic shift of the first row (first element moves to last).

Repeat this shifting pattern for all rows.

8. Display the sorted array.

9. Display the filled matrix in the specified format.

10. End.

Java Code
import java.util.Scanner;

import java.util.Arrays;

public class MatrixFill {


pg. 21
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input: Size of the matrix

System.out.print("Enter N (size of matrix, 3-9): ");

int N = scanner.nextInt();

// Validate N

if (N <= 2 || N >= 10) {

System.out.println("Invalid input. N must be between 3 and 9.");

return;

// Declare and input single-dimensional array

int[] a = new int[N];

System.out.print("Enter " + N + " positive integers: ");

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

a[i] = scanner.nextInt();

// Sort the array

Arrays.sort(a);

// Declare and fill the matrix

int[][] b = new int[N][N];

// Fill first row with sorted array

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

b[0][i] = a[i];

// Fill remaining rows by shifting the previous row

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

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

pg. 22
b[i][j] = b[i - 1][j + 1];

b[i][N - 1] = b[i - 1][0]; // Move first element to last position

// Display sorted array

System.out.println("\nSORTED ARRAY: " + Arrays.toString(a).replaceAll("[\ \ ,]", ""));

// Display filled matrix

System.out.println("\nFILLED MATRIX:");

for (int[] row : b) {

for (int num : row) {

System.out.print(num);

System.out.println(); // Move to next row

scanner.close();

Variable Description Table


SI.NO. VARIABLE DATA TYPE PURPOSE
1. N int To store size of matrix
2. A int[] Array to store user input
3. B int[][] Array filled with sorted
element
4. I int To regulate loop
5. J int To regulate loop
6. Row int[] To represent each row of
matrix b
7. Num int To represent elements of
row

OUTPUT:
pg. 23
QUESTION 9:-
pg. 24
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.

Algorithm
1. Start

2. Input the sentence from the user and check its validity:

It should end with '.', '!', or '?'

It should be in uppercase and contain words separated by single spaces

3. If the sentence is invalid, display an error message and terminate.

4. Split the sentence into words based on spaces.

5. Process each word:

Check if the word is a palindrome by comparing it with its reverse.

If it is not a palindrome, convert it to a palindrome:

Reverse the word (excluding the last character).

Concatenate the original word with the reversed substring.

Handle special cases where the last character repeats.

6. Reconstruct the new sentence while keeping the original punctuation mark.

7. Display the original and transformed sentences.

8. End.

Java Code
import java.util.Scanner;

public class PalindromeSentence {

public static void main(String[] args) {

pg. 25
Scanner scanner = new Scanner(System.in);

// Input sentence

System.out.print("Enter a sentence (uppercase, ending with '.', '!', or '?'): ");

String sentence = scanner.nextLine().trim();

// Validate the sentence

if (!isValidSentence(sentence)) {

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

return;

// Extract punctuation

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

// Remove punctuation and split words

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

// Process words

StringBuilder transformedSentence = new StringBuilder();

for (String word : words) {

transformedSentence.append(makePalindrome(word)).append(" ");

// Add punctuation back

transformedSentence.append(punctuation);

// Display results

System.out.println("\nOriginal Sentence: " + sentence);

System.out.println("Converted Sentence: " + transformedSentence.toString().trim());

scanner.close();

pg. 26
// Method to validate the sentence format

private static boolean isValidSentence(String sentence) {

if (sentence.length() < 2) return false;

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

if (lastChar != '.' && lastChar != '?' && lastChar != '!') return false;

for (int i = 0; i < sentence.length() - 1; i++) {

char c = sentence.charAt(i);

if (!(Character.isUpperCase(c) || c == ' ')) return false;

return true;

// Method to check if a word is a palindrome

private static boolean isPalindrome(String word) {

int left = 0, right = word.length() - 1;

while (left < right) {

if (word.charAt(left) != word.charAt(right)) return false;

left++;

right--;

return true;

// Method to transform a word into a palindrome if necessary

private static String makePalindrome(String word) {

if (isPalindrome(word)) return word;

// Find the point where the repetition starts from the end

int lastIndex = word.length() - 1;

while (lastIndex > 0 && word.charAt(lastIndex) == word.charAt(lastIndex - 1)) {

lastIndex--;

pg. 27
}

// Reverse the word excluding the last repeated part

String reversed = new StringBuilder(word.substring(0, lastIndex)).reverse().toString();

return word + reversed;

---

Variable Description Table


SI.NO. VARIABLE DATA TYPE PURPOSE
1. scanneer Scanner An object of scanner class
2. sentence String Stores user input sentence
3. punctuation Char Stores the punctuation at
the end
4. words String[] The array of words
5. Transformedsentence String Used to build the
transformed sentence.

OUTPUT:

QUESTION 10:-
pg. 28
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.

Algorithm
1. Input Matrix Dimensions

Prompt the user to input values for M (rows) and N (columns).

Ensure M is in the range 1 ≤ M < 10 and N is in the range 3 ≤ N < 6.

2. Input Matrix Elements

Create a MxN matrix A[][].

Loop through each element, allowing input values from 0-7 (valid octal digits).

3. Display the Original Matrix

Print the matrix in tabular form.

4. Compute Decimal Equivalents

For each row, compute its decimal equivalent using the octal-to-decimal conversion formula:

\text{decimal value} = \sum A[i][j] \times 8^{(N-1-j)}

5. Output the Results

Print the matrix followed by its decimal equivalents.

Java Program
import java.util.Scanner;

public class OctalMatrix {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Step 1: Input matrix dimensions

int M, N;

do {

System.out.print("Enter number of rows (1-9): ");

M = sc.nextInt();

} while (M <= 0 || M >= 10);

pg. 29
do {

System.out.print("Enter number of columns (3-5): ");

N = sc.nextInt();

} while (N <= 2 || N >= 6);

// Step 2: Declare and input matrix

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

System.out.println("Enter elements (digits 0-7 only):");

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

System.out.print("Row " + (i + 1) + ": ");

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

int num;

do {

num = sc.nextInt();

if (num < 0 || num > 7) {

System.out.println("Invalid input! Enter a digit between 0 and 7.");

} while (num < 0 || num > 7);

A[i][j] = num;

// Step 3: Display the matrix

System.out.println("\nFILLED MATRIX:");

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

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

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

System.out.println();

// Step 4: Compute and display decimal equivalents

System.out.println("\nDECIMAL EQUIVALENTS:");

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

int decimalValue = 0;

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

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

System.out.println(decimalValue);

sc.close();

Variable Description Table


SI. NO. VARIABLE DATA TYPE PURPOSE
1. Sc Scanner Object of scanner class
2. M int To store the no. of rows
3. N int To store the no. of coloumns
4. A Int[][] 2d array to store the octal digits
5. I int To regulate loop
6. J int To regulate inner loop
7. Num int To store octal digit no.
8. decimalValue int To store the decimal equivalent

OUTPUT:

pg. 31

You might also like