Computer Program 2
Computer Program 2
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.
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;
if (n <= 0) {
return 0;
// Recursive step: sum the current number and call the function for n-1
int n = sc.nextInt();
System.out.println("The sum of all numbers from 1 to " + n + " is: " + result);
pg. 3
sc.close();
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
8. END
Java Code
import java.util.Scanner;
if (str.isEmpty()) {
return str;
pg. 5
// Convert string to uppercase to handle case insensitivity
if (upperString.equals(reversedString)) {
} else {
scanner.close();
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:
Sample Output:
UnderstandingComputerScience
Algorithm
1. Start
3. Call a recursive function to extract and print tokens from the string
6. End
Java Code
import java.util.Scanner;
import java.util.StringTokenizer;
if (!tokenizer.hasMoreTokens()) {
printTokens(tokenizer);
scanner.close();
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
2, 2, 2, 3
ALGORITHM:-
1. Start
5. End
Java Code
import java.util.Scanner;
if (number == 1) {
if (number % divisor == 0) {
} else {
}
pg. 9
public static void main(String[] args) {
scanner.close();
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
Algorithm:-
1. Start
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
Calculate how many cartons of the current size can fit into 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;
pg. 11
System.out.print("Enter the number of boxes (max 1000): ");
int N = scanner.nextInt();
System.out.println("Carton Breakdown:");
remainingBoxes %= size;
if (count > 0) {
totalCartons += count;
if (remainingBoxes > 0) {
System.out.println("6 * 1 = 6");
totalCartons++;
remainingBoxes = 0;
scanner.close();
pg. 12
}
---
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
For each team, if the character at the current position exists, print it
7. End
Java Code
import java.util.Scanner;
int N = scanner.nextInt();
// Validate input
if (N <= 2 || N >= 9) {
return;
pg. 14
// Array to store team names
teams[i] = scanner.nextLine();
int maxLength = 0;
maxLength = team.length();
System.out.println("\nOutput:");
if (i < teams[j].length()) {
} else {
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:
YEAR: 2018
OUTPUT:
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
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).
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.
10. End.
Java Code
import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
pg. 17
public class FutureDateCalculator {
return;
int N = scanner.nextInt();
// Validate N
return;
pg. 18
}
scanner.close();
// Method to format the date in the required format (e.g., 12TH SEPTEMBER, 2018)
// Method to get the correct day suffix (st, nd, rd, th)
if (day >= 11 && day <= 13) return "TH"; // Special case for 11th, 12th, 13th
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.
Sort the elements of the single-dimensional array in ascending order using any standard sorting technique and display
the sorted elements.
1258
1251
1212
1125
Algorithm
1. Start
2. Input N (size of the matrix), ensuring 2 < N < 10. If invalid, display an error and terminate.
5. Sort the array a[] in ascending order (using any sorting method, e.g., Bubble Sort).
The second row is a cyclic shift of the first row (first element moves to last).
10. End.
Java Code
import java.util.Scanner;
import java.util.Arrays;
int N = scanner.nextInt();
// Validate N
return;
a[i] = scanner.nextInt();
Arrays.sort(a);
b[0][i] = a[i];
pg. 22
b[i][j] = b[i - 1][j + 1];
System.out.println("\nFILLED MATRIX:");
System.out.print(num);
scanner.close();
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:
6. Reconstruct the new sentence while keeping the original punctuation mark.
8. End.
Java Code
import java.util.Scanner;
pg. 25
Scanner scanner = new Scanner(System.in);
// Input sentence
if (!isValidSentence(sentence)) {
return;
// Extract punctuation
// Process words
transformedSentence.append(makePalindrome(word)).append(" ");
transformedSentence.append(punctuation);
// Display results
scanner.close();
pg. 26
// Method to validate the sentence format
if (lastChar != '.' && lastChar != '?' && lastChar != '!') return false;
char c = sentence.charAt(i);
return true;
left++;
right--;
return true;
// Find the point where the repetition starts from the end
lastIndex--;
pg. 27
}
---
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
Loop through each element, allowing input values from 0-7 (valid octal digits).
For each row, compute its decimal equivalent using the octal-to-decimal conversion formula:
Java Program
import java.util.Scanner;
int M, N;
do {
M = sc.nextInt();
pg. 29
do {
N = sc.nextInt();
int num;
do {
num = sc.nextInt();
A[i][j] = num;
System.out.println("\nFILLED MATRIX:");
System.out.println();
System.out.println("\nDECIMAL EQUIVALENTS:");
int decimalValue = 0;
pg. 30
for (int j = 0; j < N; j++) {
System.out.println(decimalValue);
sc.close();
OUTPUT:
pg. 31