Computer 1
Computer 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
General
Page-2
Final Result:
Java Code:
public class SumRecursion {
if (n == 1) {
System.out.println(1);
return;
sum(n - 1);
General
Page-3
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:
Algorithm
Step 1: Input the String
General
Page-4
Java Code:
import java.util.Scanner;
// 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
General
Page-5
return s.equals(reversedString);
if (isPalindrome(inputString)) {
} else {
scanner.close();
General
Page-6
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:
Output:
Understanding
Computer
Science
General
Page-7
Algorithm
Example: If the first token "Hello" was printed, the remaining string to process
might be "world! This is a sample string.".
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;
return;
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
General
Page-9
printTokens(input);
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
2,2,2,3
General
Page-10
Example 2:-
Input: 12
1,2,3,4,6,12
Algorithm
Step 1: Start
Input the number n for which you want to find the factors.
If n % i == 0, then i is a factor of n.
o Print i as one of the factors of n.
Repeat Step 3, Step 4, and Step 5 incrementing i by 1 each time until i becomes
greater than n.
When i > n, the recursion stops, and all the factors have been printed.
Page-11
General
Java Codes:
import java.util.Scanner;
if (i > num) {
return;
if (num % i == 0) {
findFactors(num, i + 1);
Page-12
General
// Call the recursive function starting from 1
findFactors(number, 1);
Question 5:
A company manufactures packing cartons in four sizes, i.e. cartons to
accommodate 6 boxes,
packed (N) by the user (maximum up to 1000 boxes) and display the
break-up of the cartons
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
Algorithm
Step 1: Input the total number of boxes to be packed (N).
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):
Step 6: If there are leftover boxes, use one 6-box carton to pack the remaining boxes.
Page-14
General
Java Codes:
import java.util.Scanner;
cartonCount[i] = N / cartonSizes[i];
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
General
System.out.println("\nCarton break-up:");
if (cartonCount[i] > 0) {
int N = scanner.nextInt();
// Validate input
} else {
calculateCartons(N);
Page-16
General
scanner.close();
Question 6:
The names of the teams participating in a competition should be
displayed on a banner
accept the names of N teams, where 2 < N < 9 and display them in
vertical order, side by side
Test your program for the following data and some random data:
Page-17
Example:-
General
INPUT:
N=3
Team 1: Emus
Team 3: Coyote
OUTPUT:
ERC
moo
uay
sdo
Re
Algorithm
Step 1: Input the Number of Teams
Page-18
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.
Java Codes:
import java.util.Scanner;
int N = scanner.nextInt();
if (N < 3 || N > 8) {
return;
Page-19
General
System.out.print("Enter the name of team " + (i + 1) + ": ");
teams[i] = scanner.nextLine();
int maxLength = 0;
maxLength = team.length();
for (int i = 0; i < maxLength; i++) { // Loop through the longest name length
if (i < teams[j].length()) {
} else {
scanner.close();
Page-20
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
Test your program with the following data and some random data:
Example 1
INPUT:
YEAR: 2018
Page-21
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
General
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2
INPUT:
YEAR: 2018
Page-22
Output the generated date and the future date after adding N days.
General
Step 7: Error Handling:
Java Codes:
import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
// Function to generate the date based on the day number and year
return null;
return null;
Page-23
System.out.println("Error: Day number for a leap year must be between 1 and 366.");
General
return null;
return null;
try {
Page-24
General
LocalDate generatedDate = generateDate(dayNumber, year);
if (generatedDate == null) {
System.out.print("Enter the number of days (N) to calculate the future date (1 <= N
<= 100): ");
int N = scanner.nextInt();
if (futureDate != null) {
} catch (Exception e) {
} finally {
scanner.close();
Page-25
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.
Sort the elements of the single-dimensional array in ascending order using any standard
sorting
1258
1251
1212
1125
Page-26
Test your program for the following data and some random data:
Example:-
General
INPUT:
N=3
OUTPUT:
SORTED ARRAY: 1 3 7
FILLED MATRIX
137
131
113
Algorithm
Step 1: Input N
Page-27
Step 5: Output
General
Print the matrix b[][] row by row.
Java Codes:
import java.util.Scanner;
import java.util.Arrays;
Page-28
System.out.print(matrix[i][j]);
General
System.out.println(); // Print new line after each row
int N = scanner.nextInt();
return;
a[i] = scanner.nextInt();
Page-29
sortArray(a);
General
System.out.println("Array after sorting: " + Arrays.toString(a));
fillMatrix(a, N);
scanner.close();
Page-30
Question 9:
General
Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only.
The
(b) Convert the non-palindrome words of the sentence into palindrome words by
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
[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:
OUTPUT:
Algorithm
Step 1: Input 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.1: Remove the punctuation mark (., ?, or !) from the end of the sentence.
Step 4.1: Split the sentence into individual words using spaces as separators.
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.1: Display the original sentence. Step 7.2: Display the converted sentence.
General
Java Codes:-
import java.util.Scanner;
return word.equals(reversed);
if (isPalindrome(word)) {
return word;
} else {
return false;
General
// Ensure that the words are separated by a single space and all letters are uppercase
if (!word.equals(word.toUpperCase())) {
return false;
return true;
if (!isValidSentence(sentence)) {
System.out.println("Invalid sentence!");
return;
General
String convertedWord = convertToPalindrome(word);
convertedSentence.append(convertedWord).append(" ");
// Remove the extra space at the end and append the punctuation
processSentence(sentence);
scanner.close();
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:
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
OUTPUT:
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 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.
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.1: The program terminates after displaying the matrix and its decimal
equivalents.
Java Codes:-
import java.util.Scanner;
while (true) {
matrix[i][j] = element;
break;
} else {
return matrix;
General
// Function to display the matrix
System.out.println("FILLED MATRIX");
System.out.println();
System.out.println("\nDECIMAL EQUIVALENT");
int decimalValue = 0;
System.out.println(decimalValue);
General
// Input the number of rows (M) and columns (N)
int M = 0, N = 0;
while (true) {
M = sc.nextInt();
N = sc.nextInt();
break;
} else {
displayMatrix(matrix);
calculateDecimal(matrix);
sc.close();
General
Variable Description Table
General
General