0% found this document useful (0 votes)
61 views79 pages

Name - Aryan Mishra Class-12 A SL - NO-07 ROLL - NO-4403 Subject - Computer

document of comp

Uploaded by

aryansujo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views79 pages

Name - Aryan Mishra Class-12 A SL - NO-07 ROLL - NO-4403 Subject - Computer

document of comp

Uploaded by

aryansujo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

NAME – ARYAN MISHRA

CLASS- 12 A

SL.NO-07

ROLL.NO-4403

SUBJECT- COMPUTER

1
ACKNOWLEDGEMENT
I would like to extend my heartfelt gratitude to everyone
who played a role in the successful completion of this
project. Their guidance, encouragement, and expertise
were invaluable, and I am truly thankful for their support.
1.Our Computer Science Teacher (Spondon
Ganguly Sir): Thank you for imparting your
knowledge, patiently answering our questions, and
providing valuable insights throughout the project.
2.Classmates and Friends: Your brainstorming
sessions, late-night coding marathons, and
collaborative efforts made this project both enjoyable
and enlightening.
3.Families: Their unwavering encouragement and
understanding during those intense project weeks
kept us motivated.

-Aryan Mishra

2
INDEX
Page Content
Sl.n No.
o
1. 4 Introduction To java
2. 5 Concept of oops
4. 7-10 Question 1
5. 11-15 Question 2
6. 16-20 Question 3
7. 21-25 Question 4
8. 26-29 Question 5
9. 30-33 Question 6
10. 34-38 Question 7
11. 39-41 Question 8
12. 42-45 Question 9
13. 46-48 Question 10
14. 49-51 Question 11
15. 52-54 Question 12
16. 55-57 Question 13
17. 58-60 Question 14
18. 61-64 Question 15
19. 65 Bibliography

3
JAVA-AN INTRODUCTION

Java is a versatile and widely-used programming


language that has become a cornerstone of modern
software development. Originally developed by Sun
Microsystems in the mid-1990s, Java was designed
with the principles of simplicity, portability, and
security in mind. Its "write once, run anywhere"
capability allows developers to create applications
that can run on any device with a Java Virtual
Machine (JVM), making it an ideal choice for cross-
platform development.

Java's robust feature set includes strong typing,


automatic memory management through garbage
collection, and a rich standard library that simplifies
tasks ranging from data manipulation to
networking. The language supports object-oriented
programming (OOP), allowing for modular code
design, which enhances maintainability and
reusability.

Java is a dominant force in various domains,


including web applications, mobile development
(especially Android), and enterprise-level solutions.
Its strong community support, extensive
frameworks, and tools contribute to its ongoing
popularity, making it a key language for both
beginners and experienced developers. Whether
you are building a small app or a large-scale
4
system, Java provides the flexibility and reliability
needed to meet diverse programming challenges.

5
CONCEPT OF OBJECT ORIENTED
PROGRAMMING
Object-oriented programming (OOP) is a powerful
paradigm that revolutionizes the way we approach
software development. By organizing code around
objects—collections of data and methods that
operate on that data—OOP enhances modularity,
reusability, and maintainability. The core principles
of OOP include encapsulation, inheritance, and
polymorphism, which together allow developers to
create more intuitive and manageable code
structures.

Encapsulation involves bundling data and behavior


within objects, protecting the integrity of the data
by exposing only necessary interfaces. Inheritance
enables the creation of new classes based on
existing ones, fostering code reuse and a clear
hierarchical structure. Polymorphism allows
methods to operate on objects of different classes,
providing flexibility and adaptability in code
behavior.

OOP is foundational in many modern programming


languages, such as Java, C++, and Python, making
it a critical concept for aspiring developers. By
embracing OOP, programmers can build complex
systems that are easier to understand, extend, and
6
maintain, ultimately leading to more efficient and
effective software solutions.

7
Question 1.

A unique digit integer is a positive integer (without leading


zeros) with no duplicate digits. For example, 7, 135, and 214
are all unique digit integers whereas 33, 3121, and 30021
are not. Given two positive integers m and n, where m<n,
write a program to determine how many unique digit
integers are there in the range between m and n (both
inclusive) and print them as output. The program should
take input as two positive integers m and n, where m<30000
and n<30000. The program should print all the unique-digit
numbers along with the count.*/

Algorithm:

· Input Reading: Read the integer values of m and n from


the user.

· Validation: Ensure m and n are both less than 30000.


Ensure m is less than n. If not, swap the values of m and n.

· Initialization: Initialize a count variable to zero to keep


track of the number of unique digit integers.

· Unique Digit Check: For each number in the range from m


to n (inclusive):

· Check if the number has unique digits by:

o Initializing a boolean array of size 10 to track


seen digits.
o Iterating over each digit of the number:
 If the digit has already been seen, the
number does not have unique digits.
 If the digit has not been seen, mark it as
seen.
 If the number has unique digits, print the number and
increment the count.

· Output: Print the total count of unique digit integers.

· Termination: Close the scanner.

8
Program Code:

import java.util.*;

public class UniqueDigitIntegers {

// Function to check if a number has unique digits

public static boolean hasUniqueDigits(int number) {

boolean[] digitSeen = new boolean[10]; // Array to track


seen digits

int currentNumber = number;

while (currentNumber > 0) {

int digit = currentNumber % 10;

if (digitSeen[digit]) {

return false;

digitSeen[digit] = true;

currentNumber /= 10;

return true;

// Function to find and print unique digit integers in the


range [m, n]

public static void findUniqueDigitIntegers(int m, int n) {

int count = 0;

9
System.out.println("Unique digit integers between " +
m + " and " + n + ":");

for (int number = m; number <= n; number++) {

if (hasUniqueDigits(number)) {

System.out.println(number);

count++;

System.out.println("Total count: " + count);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read input values

System.out.print("Enter the value of m: ");

int m = scanner.nextInt();

System.out.print("Enter the value of n: ");

int n = scanner.nextInt();

// Ensure m < n

if (m >30000 || n>30000) {

10
System.out.println("Invalid input: Value should be
less than 30000");

return;

//swapping m and n values for creating a valid range

m=m+n;

n=m-n;

m=m-n;

// Find and print unique digit integers

findUniqueDigitIntegers(m, n);

// Close the scanner

scanner.close();

Variable Description Table:

Variable Name Data Type Description


Lower bound of
m int the range (input
from the user).
Upper bound of
n int the range (input
from the user).
Scanner object to
scanner Scanner read input from
the user.
Counter for the
count int number of unique
digit integers.
digitSeen boolean[] Array to track if a
digit has been
seen while

11
processing a
number.
Variable to hold
the current
currentNumber int
number being
checked.
Variable to hold
the current digit of
digit int
the number being
checked.
Variable used in
the loop to iterate
number int
over the range
from m to n.

Output:

12
Question 2.
Write a program which takes a string (maximum 80
characters) terminated by a full stop. The
words in this string are assumed to be separated by one or
more blanks.
Arrange the words of the input string in descending order of
their lengths. Same-length words
should be sorted alphabetically. Each word must start with
an uppercase letter and the sentence
should be terminated by a full stop.
INPUT:
“This is human resource department.”
OUTPUT:
Department Resource Human This Is.

Algotrithm:

· Input Reading:

 Read the input string from the user.

· Validation:

 Ensure the string is terminated by a full stop ('.'). If


not, prompt the user to try again.
 Ensure the length of the string does not exceed 80
characters. If it does, prompt the user to try again.

· String Processing:

 Remove the full stop at the end of the input string.


 Split the string into words using spaces as the
delimiter and store it in an array.
 Capitalize the first letter of each word.
 Sort the words by length in descending order, and
alphabetically for words of the same length.

· String Reconstruction:

· Join the sorted words back into a single string with a


full stop at the end.

· Output:

· Print the original input string and the sorted output


string.

13
Program Code:

import java.util.Scanner;

public class SortWordsInString {

// Function to process the input string

static String processInputString(String input) {

// Remove the full stop at the end

String trimmedInput = input.substring(0, input.length()


- 1).trim();

// Split the string into words using spaces as the


delimiter and store it in an array

String[] words = trimmedInput.split(" ");

// Capitalize the first letter of each word

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

words[i] = capitalizeFirstLetter(words[i]);

// Sort words by length in descending order, and


alphabetically for same-length words

sortWords(words);

// Join the words back into a single string with a full


stop at the end

14
return joinWords(words);

// Function to capitalize the first letter of a word

static String capitalizeFirstLetter(String word) {

if (word == null || word.isEmpty()) {

return word;

return word.substring(0, 1).toUpperCase() +


word.substring(1);

// Function to sort words by length in descending order


and alphabetically for same-length words

static void sortWords(String[] words) {

for (int i = 0; i < words.length - 1; i++) {//using bubble


sort technique

for (int j = i + 1; j < words.length; j++) {

if (words[j].length() > words[i].length() ||

(words[j].length() == words[i].length() &&


words[j].compareTo(words[i]) < 0)) {

// Swap words[i] and words[j]

String temp = words[i];

words[i] = words[j];

words[j] = temp;

15
}

// Function to join words into a single string with a full


stop at the end

static String joinWords(String[] words) {

String newStr="";

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

newStr+=words[i]+" ";

return newStr.trim() + ".";

// Function to print the output

static void printOutput(String input,String output) {

System.out.println("Original String: "+"\""+input+"\"");

System.out.println("Sorted String: "+output);

public static void main() {

Scanner sc=new Scanner(System.in);

System.out.println("Enter the String: ");

String input =sc.nextLine(); //"This is human resource


department.";

if(input.length()>80){

System.out.println("Maximum 80 characters
allowed!! Try Again!");

16
main();

if(input.charAt(input.length()-1)!='.'){

System.out.println("The string should be terminated


by a full stop('.') Try Again!");

main();

// Process the input string

String output = processInputString(input);

// Print the result

printOutput(input,output);

Variable Description Table:

Variable Name Data Type Description


Input string
input String provided by the
user.
trimmedInput String Input string after
removing the full
stop at the end.
Array of words
obtained by
words String[]
splitting the input
string.
String to store the
concatenated
newStr String
result of sorted
words.
Scanner object to
sc Scanner read input from
the user.

17
Processed output
output String string after sorting
words.
Temporary
variable used for
temp String
swapping words
during sorting.

Output:

18
Question 3. Write a program that accepts N words from the
user, where N will also be entered by the user.
Now print all those words which are anagrams among
themselves. If no anagram is possible, the
program will display an appropriate message. The program
should take words containing only
alphabets (in upper or lower or mixed case).
Also, display the number of anagrams possible.

Algortihm:

· Input Reading:

· Read the number of words (n) from the user.

 Read n words from the user and store them in an array


(words).

· Anagram Finding:

· Initialize variables to track if any anagrams are found


(foundAnagram) and to count the number of anagram
groups (anagramCount).

 Iterate through each pair of words in the array:

o For each word, check if it forms an anagram


group with any of the following words.
o If a word forms an anagram group, print the word
and the anagrams.
o Increment the anagramCount for each anagram
group found.

· Output:

· If no anagrams are found, print "No anagrams found."

 Otherwise, print the total number of anagram groups


found.

· Anagram Check:

· Convert both words to lowercase.

 If the lengths of the words are different, return false.


 Count the frequency of each letter in both words.

19
 If the frequency counts match for all letters, the words
are anagrams.

Program Code:

import java.util.Scanner;

public class AnagramFinder {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Get the number of words

System.out.println("Enter the number of words: ");

int n = sc.nextInt();

sc.nextLine(); // Consume the newline character

// Get the words from the user

String[] words = new String[n];

System.out.println("Enter the words:");

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

words[i] = sc.nextLine();

// Find and print anagrams

20
findAndPrintAnagrams(words);

sc.close();

private static void findAndPrintAnagrams(String[] words)


{

boolean foundAnagram = false; // Flag to check if any


anagrams are found

int anagramCount = 0; // Counter for anagram


groups

// Iterate through each pair of words

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

boolean isAnagramGroup = false; // Flag to check if


the current word is part of an anagram group

for (int j = i + 1; j < words.length; j++) {

if (areAnagrams(words[i], words[j])) {

if (!isAnagramGroup) {

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

isAnagramGroup = true;

foundAnagram = true;

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

21
if (isAnagramGroup) {

System.out.println();

anagramCount++;

if (!foundAnagram) {

System.out.println("No anagrams found.");

} else {

System.out.println("Number of anagram groups: " +


anagramCount);

// Helper method to check if two words are anagrams

private static boolean areAnagrams(String word1, String


word2) {

word1 = word1.toLowerCase();

word2 = word2.toLowerCase();

if (word1.length() != word2.length()) {

return false;

22
int[] letterCounts = new int[26]; // Array to count letter
frequencies

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

letterCounts[word1.charAt(i) - 'a']++;

letterCounts[word2.charAt(i) - 'a']--;

for (int count : letterCounts) {

if (count != 0) {

return false;

return true;

Variable Description Table:

Variable Name Data Type Description


Scanner object to
sc Scanner read input from
the user.
Number of words
n int
input by the user.
Array to store the
words String[] words input by the
user.
Flag to indicate if
foundAnagram boolean any anagrams
were found.
Counter for the
number of
anagramCount int
anagram groups
found.
isAnagramGroup boolean Flag to indicate if
the current word

23
starts a new
anagram group.
First word in the
word1 String pair being checked
for anagrams.
Second word in the
word2 String pair being checked
for anagrams.
Array to count the
frequency of
letterCounts int[]
letters in the
words.
Temporary
variable to hold
count int the letter count
during anagram
check.

Output:

Question 4.
Numbers have different representations depending on the
bases on which they are expressed. For example, 110 in
base 3 = 12 (1x3² + 1x3¹ +0x3º), also 14 in base 8 = 12 (1x8¹
+ 4x8º). So, we can say that 110 and 14 will generate the
same value i.e., 12 in the bases 3 and 8 respectively.
Consider, for example, the integers 12 and 5. Certainly,
these are not equal if base 10 is used for each. But suppose
12 was a base 3 number and 5 was a base 6 number then
what happens, 12 base 3=1x3¹ + 2x3º = 5, and 5 in base
6=5x60 = 5 or 5 base 10 (5 in any base is equal to 5 base
10). So, 12 and 5 can be equal of at the bases 3 and 6
respectively.
Write a program to input two integers, X and Y, and
calculate the smallest base for X and the smallest base for Y
(likely different from X) so that X and Y represent the same
value. The base associated with x and Y will be between 1
and 20 (both inclusive). In representing these numbers, the
digits 0 and 9 have their usual decimal interpretation. The

24
uppercase characters A to J represent digits 10 to 19
respectively

Algorithm:

· Input Handling:

 · Read two strings X and Y representing the integers.


 Convert the strings to uppercase to handle both digits
and letters uniformly.

· Determine Base Range:

 · Calculate the minimum base required for each string.


 Initialize the minimum base to 2 and maximum base to
20.
 For each character in the string, update the minimum
base:

o If the character is a digit, the base is the


maximum of the current base and (digit value +
1).
o If the character is a letter, the base is the
maximum of the current base and (letter value -
'A' + 11).

· Iterate Through Possible Bases:

 · Iterate through possible bases for X from its


minimum base to the maximum base.
 For each base, convert the string X from the current
base to its decimal equivalent:

o Initialize a variable to store the decimal value.


o For each character in the string, calculate its
value based on whether it is a digit or a letter.
o Multiply the current decimal value by the base
and add the character's value.
o If any character is invalid for the current base,
mark the conversion as invalid.

· Match Decimal Values:

 · For each valid base of X, iterate through possible


bases for Y from its minimum base to the maximum
base.

25
 Convert the string Y from the current base to its
decimal equivalent using the same conversion method.
 If the decimal values of X and Y match for any pair of
bases, print the bases and the matching decimal value,
and terminate the program.

· No Match Found:

 · If no matching bases are found within the given


range, print a message indicating no match.

26
Program Code:

import java.util.Scanner;

public class SmallestBaseMatch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input integers X and Y


System.out.print("Enter integer X: ");
String X = scanner.next().toUpperCase();
System.out.print("Enter integer Y: ");
String Y = scanner.next().toUpperCase();

int[] xBaseRange = findBaseRange(X);


int[] yBaseRange = findBaseRange(Y);

for (int baseX = xBaseRange[0]; baseX <=


xBaseRange[1]; baseX++) {
int valueX = convertToDecimal(X, baseX);
if (valueX == -1) continue; // Invalid conversion, skip
this base

for (int baseY = yBaseRange[0]; baseY <=


yBaseRange[1]; baseY++) {
int valueY = convertToDecimal(Y, baseY);
if (valueY == -1) continue; // Invalid conversion,
skip this base

if (valueX == valueY) {
System.out.println("Smallest base for X: " +
baseX);
System.out.println("Smallest base for Y: " +
baseY);
System.out.println("Value: " + valueX);
return;
}
}
}

System.out.println("No matching bases found within


the range.");
}

// Determine the minimum base required for a given


number in string representation
private static int[] findBaseRange(String number) {
int minBase = 2;
int maxBase = 20;
for (char ch : number.toCharArray()) {

27
if (Character.isDigit(ch)) {
minBase = Math.max(minBase,
Character.getNumericValue(ch) + 1);
} else {
minBase = Math.max(minBase, ch - 'A' + 11);
}
}
return new int[]{minBase, maxBase};
}

// Convert a number in a given base to its decimal (base


10) equivalent
private static int convertToDecimal(String number, int
base) {
int value = 0;
try {
for (char ch : number.toCharArray()) {
int digitValue;
if (Character.isDigit(ch)) {
digitValue = Character.getNumericValue(ch);
} else {
digitValue = ch - 'A' + 10;
}
if (digitValue >= base) {
return -1; // Invalid digit for the base
}
value = value * base + digitValue;
}
} catch (Exception e) {
return -1; // Conversion error
}
return value;
}
}

Variable Description Table:

Variable Name Type Description


Scanner object
used for reading
scanner Scanner
input from the
user.
Input string
representing the
X String first integer,
converted to
uppercase.
Y String Input string
representing the

28
second integer,
converted to
uppercase.
Array containing
the minimum and
xBaseRange int[] maximum possible
bases for the
number X.
Array containing
the minimum and
yBaseRange int[] maximum possible
bases for the
number Y.
Variable used to
iterate through
baseX int
possible bases for
the number X.
Variable used to
iterate through
baseY int
possible bases for
the number Y.
Decimal value of
the number X
valueX int when converted
from the base
baseX.
Decimal value of
the number Y
valueY int when converted
from the base
baseY.
Input string
representing
number String
either X or Y in the
helper methods.
Minimum base
required for the
minBase int input number,
calculated based
on its characters.
Maximum base
limit for the input
maxBase int
number, arbitrarily
set to 20.
Character from the
input string used
ch char in base range and
decimal conversion
calculations.

29
Numerical value of
the character ch
digitValue int
when converted to
a digit.
Decimal value of
the input string
value int being converted in
the helper
methods.

Output:

30
Question 5.

Write a program to do the following: Read an integer n


(which can be at most 50). Then read in n integers one by
one and store them in an array data from index 0 to n-1.
Now we want to rearrange the integers in the data in the
following way: Find the maximum value in data and put it in
the centre of the array (that is at (n/2)); find the next
largest value and put it to its right; then the next largest
and place it to its left and so on alternating right and left
until all integers in data are done. For example, if the array
is initially: 7, 3, 6, 4, 2, 5, 1 then after rearranging it
becomes 1, 3, 5, 7, 6, 4, 2 However, since we have very little
memory, you are not allowed to use any other array apart
from data.

Algortihm:

· Input Handling:

 · Read the number of integers n from the user.


 Ensure n is less than or equal to 50.
 Initialize an array data of size n.

· Reading Input:

 · Read n integers from the user and store them in the


array data.

· Sorting the Array:

 · Sort the array data in ascending order.


 Reverse the array to get it sorted in descending order.

· Rearranging the Array:

 · Initialize an empty array result of size n.


 Calculate the center index of the array.
 Place the largest element (first element of sorted
array) at the center of the result array.
 Initialize two pointers: left to center - 1 and right to
center + 1.
 Initialize an index variable to 1 for iterating through
the remaining elements of the sorted array.
 Initialize a boolean moveLeft to false.
 Iterate while either left is non-negative or right is less
than n:

31
o If moveLeft is true and left is non-negative, place
the current element from the sorted array at the
left index of result and decrement left.
o If moveLeft is false and right is less than n, place
the current element from the sorted array at the
right index of result and increment right.
o Toggle moveLeft to alternate the placement
between left and right.

 Increment the index variable after placing each


element.

· Copying Result to Original Array:

 · Copy the rearranged array from result back to the


original array data.

· Output the Rearranged Array:

 · Print the rearranged array data.

Program Code:

import java.util.*;

public class RearrangeArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of integers (n <=
50): ");
int n = scanner.nextInt();

int[] data = new int[n];


System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
data[i] = scanner.nextInt();
}

rearrangeArray(data);

System.out.println("Rearranged array:");
for (int i = 0; i < n; i++) {
System.out.print(data[i] + " ");
}
}

private static void rearrangeArray(int[] data) {


int n = data.length;

32
// Sort the array in descending order
Arrays.sort(data);
for (int i = 0; i < n / 2; i++) {
int temp = data[i];
data[i] = data[n - i - 1];
data[n - i - 1] = temp;
}

// Rearrange the array in place


int[] result = new int[n];
int center = n / 2;
int left = center - 1;
int right = center + 1;

// Place the largest number at the center


result[center] = data[0];
int index = 1;
boolean moveLeft = false;

// Place remaining numbers alternating left and right


while (left >= 0 || right < n) {
if (moveLeft && left >= 0) {
result[left--] = data[index++];
} else if (!moveLeft && right < n) {
result[right++] = data[index++];
}
moveLeft = !moveLeft;
}

// Copy the result back into the original array


for (int i = 0; i < n; i++) {
data[i] = result[i];
}
}
}

Variable Description Table:

Variable Name Type Description


Scanner object
used for reading
scanner Scanner
input from the
user.
n int Number of
integers to be
entered by the
user, constrained
to be less than or

33
equal to 50.
Array of integers
data int[] entered by the
user.
Array used to store
result int[] the rearranged
elements.
Index representing
center int the center of the
result array.
Pointer used to
place elements to
left int the left of the
center in the result
array.
Pointer used to
place elements to
right int the right of the
center in the result
array.
Index used to
index int iterate through the
sorted data array.
Boolean flag used
to alternate
placement of
moveLeft boolean
elements between
left and right of
the center.
Temporary
variable used for
swapping
temp int
elements during
the reverse
operation.
Loop variable used
i int for various
iterations.

Output:

34
35
Question 6.
A palindrome number is one that reads the same from left to
right or right to left. There is an ingenious method to get a
palindrome from any positive integer. The procedure is as
follows: Start with any positive number of 2 or more digits.
Obtain another positive number by reversing the digits of
the starting number. Add the two numbers together. Repeat
the whole procedure with the sum as the starting number
till you get a sum that is a palindrome number. Program to
calculate the palindrome of a given number in a maximum
15 terms. Assume that the starting number is not a
palindrome. Sample Input: 87. Output: 4884 Steps: 4.

Algorithm:

· Input Handling:

 · Prompt the user to enter a starting number greater


than 9.
 Read the starting number and store it in
startingNumber.

· Calculate Palindrome:

 · Initialize steps to 0.
 Initialize currentNumber to startingNumber.

· Iterate to Find Palindrome:

 · Repeat while steps is less than 15:

o Reverse the digits of currentNumber using the


reverseNumber function.
o Calculate the sum of currentNumber and
reversedNumber.
o Check if the sum is a palindrome using the
isPalindrome function.
o If the sum is a palindrome, print the palindrome
number and return steps + 1.
o If not, update currentNumber to the sum and
increment steps.

· Return Steps:

 · If no palindrome is found within 15 steps, return the


number of steps tried.

36
Program Code:

import java.util.Scanner;

public class PalindromeFromNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the starting number


System.out.print("Enter the starting number (greater
than 9): ");
int startingNumber = scanner.nextInt();

// Calculate the palindrome


int steps = calculatePalindrome(startingNumber);

// Output the result


System.out.println("Steps: " + steps);
}

/**
* Function to calculate the palindrome number derived
from a starting number.
* @param startingNumber The starting positive integer.
* @return The number of steps taken to find the
palindrome.
*/
private static int calculatePalindrome(int startingNumber)
{
int steps = 0;
int currentNumber = startingNumber;

// Maximum 15 terms as per the problem statement


while (steps < 15) {
// Reverse the digits of the current number
int reversedNumber =
reverseNumber(currentNumber);

// Add the current number and its reverse


int sum = currentNumber + reversedNumber;

// Check if the sum is a palindrome


if (isPalindrome(sum)) {
System.out.println("Palindrome number found: " +
sum);
return steps + 1; // Return steps + 1 because we
found the palindrome
}

37
// Update current number to the sum for the next
iteration
currentNumber = sum;
steps++;
}

// If no palindrome found within 15 steps, return the


number of steps tried
return steps;
}

/**
* Function to reverse the digits of a given number.
* @param number The number to reverse.
* @return The reversed number.
*/
private static int reverseNumber(int number) {
int reversed = 0;
while (number > 0) {
reversed = reversed * 10 + number % 10;
number /= 10;
}
return reversed;
}

/**
* Function to check if a number is palindrome.
* @param number The number to check.
* @return True if the number is palindrome, false
otherwise.
*/
private static boolean isPalindrome(int number) {
int original = number;
int reversed = 0;

// Reverse the number


while (number > 0) {
reversed = reversed * 10 + number % 10;
number /= 10;
}

// Check if original number equals reversed number


return original == reversed;
}
}

Variable Description Table:

38
Variable Name Type Description
Scanner object
used for reading
scanner Scanner
input from the
user.
The starting
number entered by
startingNumber int
the user, which is
greater than 9.
Counter for the
number of steps
steps int
taken to find the
palindrome.
The current
number being
currentNumber int
processed to find
the palindrome.
The reversed
reversedNumber int digits of the
current number.
The sum of
currentNumber
sum int
and
reversedNumber.
The original
number being
checked if it is a
original int
palindrome (used
in isPalindrome
function).
The reversed
digits of the
original number
reversed int
(used in
isPalindrome
function).
Temporary
variable used for
number int
reversing the
digits of a number.

Output:

39
40
Question 7.
Write a program to find the age of a person in year-month-
day after taking the birth date and current date as input in
dd-mm-yyyy format. The required validations of the
existence of the dates must be given in the program.

Algorithm:

· Input Handling:

 · Prompt the user to enter the birth date in dd-mm-


yyyy format.
 Prompt the user to enter the current date in dd-mm-
yyyy format.
 Split the birth date input into birthDay, birthMonth,
and birthYear.
 Split the current date input into currentDay,
currentMonth, and currentYear.

· Validation:

 · Validate the birth date using the isValidDate


function.

o If the birth date is invalid, print "Invalid birth


date" and terminate.

 Validate the current date using the isValidDate


function.
o If the current date is invalid, print "Invalid current
date" and terminate.

· Date Comparison:

 · Check if the birth date is before the current date


using the isDateBefore function.
o If the birth date is not before the current date,
print "Birth date should be before the current
date" and terminate.
 If the birth date is valid and before the current date,
proceed to calculate the age.

· Age Calculation:

 · Calculate the age using the calculateAge function.


 Print the calculated age in years, months, and days.

41
Program Code:

import java.util.Scanner;

public class AgeCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter birth date


System.out.print("Enter birth date (dd-mm-yyyy): ");
String birthDateInput = scanner.nextLine();

// Prompt the user to enter current date


System.out.print("Enter current date (dd-mm-yyyy): ");
String currentDateInput = scanner.nextLine();

// Split the birth date input into day, month, and year
String[] birthDateParts = birthDateInput.split("-");
String[] currentDateParts = currentDateInput.split("-");

int birthDay = Integer.parseInt(birthDateParts[0]);


int birthMonth = Integer.parseInt(birthDateParts[1]);
int birthYear = Integer.parseInt(birthDateParts[2]);

// Split the current date input into day, month, and year
int currentDay = Integer.parseInt(currentDateParts[0]);
int currentMonth =
Integer.parseInt(currentDateParts[1]);
int currentYear =
Integer.parseInt(currentDateParts[2]);

// Validate birth date


if (!isValidDate(birthDay, birthMonth, birthYear)) {
System.out.println("Invalid birth date");
return;
}

// Validate current date


if (!isValidDate(currentDay, currentMonth,
currentYear)) {
System.out.println("Invalid current date");
return;
}

// Check if birth date is before current date


if (isDateBefore(birthDay, birthMonth, birthYear,
currentDay, currentMonth, currentYear)) {
// Calculate age if dates are valid

42
int[] age = calculateAge(birthDay, birthMonth,
birthYear, currentDay, currentMonth, currentYear);
System.out.println("Age: " + age[0] + " years, " +
age[1] + " months, " + age[2] + " days.");
} else {
System.out.println("Birth date should be before the
current date.");
}
}

// Function to validate if a given date is valid


private static boolean isValidDate(int day, int month, int
year) {
if (year < 1 || month < 1 || month > 12 || day < 1 || day
> daysInMonth(month, year)) {
return false;
}
return true;
}

// Function to get the number of days in a given month


and year
private static int daysInMonth(int month, int year) {
int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31 };
if (month == 2 && isLeapYear(year)) {
return 29;
}
return days[month - 1];
}

// Function to check if a given year is a leap year


private static boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
}
return true;
}
return false;
}

// Function to check if the first date is before the second


date
private static boolean isDateBefore(int day1, int month1,
int year1, int day2, int month2, int year2) {
if (year1 < year2) {
return true;
}

43
if (year1 == year2) {
if (month1 < month2) {
return true;
}
if (month1 == month2) {
return day1 < day2;
}
}
return false;
}

// Function to calculate age given the birth date and


current date
private static int[] calculateAge(int birthDay, int
birthMonth, int birthYear, int currentDay, int currentMonth,
int currentYear) {
int[] age = new int[3];

// Adjust days and months if current day is less than


birth day
if (currentDay < birthDay) {
currentDay += daysInMonth(currentMonth - 1,
currentYear);
currentMonth -= 1;
}
age[2] = currentDay - birthDay;

// Adjust months and years if current month is less than


birth month
if (currentMonth < birthMonth) {
currentMonth += 12;
currentYear -= 1;
}
age[1] = currentMonth - birthMonth;
age[0] = currentYear - birthYear;

return age;
}
}

Variable Description Table:

Variable Name Type Description


Scanner object
used for reading
scanner Scanner
input from the
user.
birthDateInput String Input string

44
representing the
birth date in dd-
mm-yyyy format.
Input string
representing the
currentDateInput String
current date in dd-
mm-yyyy format.
Array containing
birthDateParts String[] parts of the birth
date split by -.
Array containing
parts of the
currentDateParts String[]
current date split
by -.
Day part of the
birthDay int
birth date.
Month part of the
birthMonth int
birth date.
Year part of the
birthYear int
birth date.
Day part of the
currentDay int
current date.
Month part of the
currentMonth int
current date.
Year part of the
currentYear int
current date.
Array containing
the calculated age
age int[]
in years, months,
and days.
Temporary
variable
day int representing day
in isValidDate
function.
Temporary
variable
representing
month int
month in
isValidDate
function.
Temporary
variable
year int representing year
in isValidDate
function.
days int[] Array containing
the number of
days in each

45
month.
Original year in
original int isLeapYear
function.
Reversed digits of
the original year in
reversed int
isLeapYear
function.
Date components
of the first date
day1, month1,
int (birth date) in
year1
isDateBefore
function.
Date components
of the second date
day2, month2,
int (current date) in
year2
isDateBefore
function.

Output:

46
Question 8.
Given a time in numbers we can convert it into words. For
example, 5: 00 five o'clock 5: 10 ten minutes past five 5: 15
quarter past five 5: 30 half past five 5: 40 twenty minutes to
six 5: 45 quarter to six 5: 47 thirteen minutes to six Write a
program which first inputs two integers, the first between 1
and 12 (both inclusive) and the second between 0 and 59
(both inclusive) and then prints out the time they represent,
in words. Your program should follow the format of the
examples above.

Algorithm:

· Input:

 · Read the hour (between 1 and 12).


 Read the minutes (between 0 and 59).

· Validation:

 · Check if the hour is between 1 and 12.


 Check if the minutes are between 0 and 59.
 If either validation fails, output an error message and
terminate.

· Conversion to Words:

 · Create an array of words for numbers from 0 to 29.


 Depending on the value of minutes, convert the time to
words using the following conditions:

o If minutes == 0: Return "<hour> o'clock".


o If minutes == 15: Return "quarter past <hour>".
o If minutes == 30: Return "half past <hour>".
o If minutes == 45: Return "quarter to <next
hour>".
o If minutes == 1: Return "one minute past
<hour>".
o If 0 < minutes < 30: Return "<minutes> minutes
past <hour>".
o If 30 < minutes < 60: Return "<(60 - minutes)>
minutes to <next hour>".

· Output:

 · Print the converted time in words.

Program Code:

47
import java.util.Scanner;

public class TimeInWords {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the hour


System.out.print("Enter the hour (1-12): ");
int hour = scanner.nextInt();

// Prompt the user to enter the minutes


System.out.print("Enter the minutes (0-59): ");
int minutes = scanner.nextInt();

// Validate the input values


if (hour < 1 || hour > 12 || minutes < 0 || minutes > 59)
{
System.out.println("Invalid input. Please enter the
hour between 1 and 12, and minutes between 0 and 59.");
return;
}

// Convert the time to words


String timeInWords = convertTimeToWords(hour,
minutes);

// Print the time in words


System.out.println(timeInWords);
}

/**
* Convert the given hour and minutes into words.
* @param hour The hour of the time (1-12).
* @param minutes The minutes of the time (0-59).
* @return The time represented in words.
*/
private static String convertTimeToWords(int hour, int
minutes) {
// Array of words for numbers from 0 to 29
String[] numbers = {
"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen", "twenty",
"twenty one", "twenty two", "twenty three", "twenty
four", "twenty five", "twenty six", "twenty seven", "twenty
eight", "twenty nine"
};

48
// Convert the time based on the value of minutes
if (minutes == 0) {
return numbers[hour] + " o'clock";
} else if (minutes == 15) {
return "quarter past " + numbers[hour];
} else if (minutes == 30) {
return "half past " + numbers[hour];
} else if (minutes == 45) {
return "quarter to " + numbers[(hour % 12) + 1];
} else if (minutes == 1) {
return "one minute past " + numbers[hour];
} else if (minutes < 30) {
return numbers[minutes] + " minutes past " +
numbers[hour];
} else if (minutes > 30 && minutes < 60) {
return numbers[60 - minutes] + " minutes to " +
numbers[(hour % 12) + 1];
}

return "";
}
}

Variable Description Table:

Variable Data Type Description


The hour part of
hour int
the time (1-12).
The minutes part
minutes int
of the time (0-59).
Array of number
numbers String[] words from 0 to
29.
The time
converted to
timeInWords String
words based on
the rules.

Output:

49
50
Question 9.
Consider the sequence of natural numbers 1, 2, 3, 4, 5, 6, 7
…….. Removing every second number produces the
sequence 1, 3, 5, 7, 9, 11, 13, 15, 17 ……… Removing every
third number from above produces the sequence 1, 3, 7, 9,
13, 15, 19, 21, 25, 27 ………. This process continues
indefinitely by removing the fourth, fifth…........ and so on,
till after a fixed number of steps, certain natural numbers
remain indefinitely. These are known as Lucky Numbers.
Write a program to generate and print lucky numbers less
than a given natural number N where N<=50.

Algorithm:

· Input Reading

 · Read an integer N from the user where 1≤N≤501 \leq


N \leq 501≤N≤50.

· Input Validation

 · Check if N is within the valid range (1 to 50). If not,


print an error message and exit.

· Initialization

 · Create a boolean array isLucky of size N+1 to track


which numbers are considered "lucky".
 Initialize all entries in isLucky to true.

· Lucky Number Removal Process

 · Initialize counter to 2.
 Enter a loop that continues until the number of
remaining "lucky" numbers is less than counter:

o Count Remaining Lucky Numbers


 Traverse the isLucky array and count how
many entries are still true.
o Check Remaining Numbers

 If the count of remaining lucky numbers is


less than counter, exit the loop.

o Remove Every counter-th Lucky Number

 Traverse the isLucky array and set every


counter-th true entry to false.

51
o Increment Counter

 Increase counter by 1 for the next iteration.

· Output

 · Print all numbers that are still true in the isLucky


array.

Program Code:

import java.util.Scanner;

public class LuckyNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user for input and read the integer N


System.out.print("Enter a natural number N (N <= 50):
");
int N = scanner.nextInt();

// Validate the input to ensure N is between 1 and 50


if (N < 1 || N > 50) {
System.out.println("Invalid input. N should be
between 1 and 50.");
return;
}

// Initialize a boolean array to track which numbers are


"lucky"
boolean[] isLucky = new boolean[N + 1];
for (int i = 1; i <= N; i++) {
isLucky[i] = true; // Initially, all numbers are
considered lucky
}

// Start with removing every second number


int counter = 2;
while (true) {
// Count remaining numbers that are still "lucky"
int remaining = 0;
for (int i = 1; i <= N; i++) {
if (isLucky[i]) {
remaining++;
}
}

52
// If fewer numbers remain than the current counter,
break the loop
if (remaining < counter) {
break;
}

// Remove every `counter`-th number from the list of


lucky numbers
int removed = 0;
for (int i = 1; i <= N; i++) {
if (isLucky[i]) {
removed++;
if (removed % counter == 0) {
isLucky[i] = false; // Mark this number as
unlucky
}
}
}

// Increment the counter for the next iteration


counter++;
}

// Print the lucky numbers


System.out.println("Lucky numbers less than " + N +
":");
for (int i = 1; i <= N; i++) {
if (isLucky[i]) {
System.out.print(i + " "); // Print each lucky
number
}
}
}
}

Variable Description Table:

Variable Data Type Description


The input number
for which lucky
N int
numbers are
found.
Array where true
indicates a lucky
isLucky boolean[] number and false
indicates an
unlucky number.
counter int The interval for

53
removing numbers
from the lucky list
(starts at 2 and
increments).
Count of numbers
remaining int that are still
considered lucky.
Counter to keep
track of numbers
removed int
removed in each
iteration.

Output:

54
Question 10. Given a sequence of N integers 1<=N<=30. A
maximal subsequence (for the purpose of the program) is
the subsequence with the highest sum. Thus, for the
sequence given below: -1, 2, 8, -7, 3, 5, -20, 2, 1. The
maximal subsequence runs from the 2nd number to the 6th
number (the sum of the numbers is 11), since no other
subsequence has the highest sum. (Note: To get a
subsequence the position of the elements in the sequence
should not be altered.) Write a program which reads the
sequence and finds its maximal subsequence. Input will
consist of a number (N) and followed by N numbers. The
sequence will have a positive sum for the maximal
subsequence. Output should consist of the start and the end
indices of the maximal subsequence and its resulting sum. If
more than one maximal subsequence is present then print
any one of them.

Algorithm:

· Input Reading

 · Read the number of elements N in the sequence


where 1≤N≤301 \leq N \leq 301≤N≤30.
 Read N integers into an array sequence.

· Input Validation

 · Check if N is between 1 and 30. If not, print an error


message and exit.

· Initialization

 · Initialize maxSum to Integer.MIN_VALUE to keep


track of the maximum sum of the subsequence.
 Initialize startIndex and endIndex to 0 for tracking the
indices of the maximal subsequence.
 Initialize currentSum to 0 to accumulate the sum of the
current subsequence.
 Initialize tempStartIndex to 0 for tracking the potential
start index of the current subsequence.

· Kadane's Algorithm

 · Iterate through each element of the sequence:

o Add the current element to currentSum.


o If currentSum is greater than maxSum, update
maxSum, startIndex, and endIndex.

55
o If currentSum becomes negative, reset
currentSum to 0 and update tempStartIndex to
the next index.

· Output

 · Print the start and end indices of the maximal


subsequence (1-based index) and its sum.

Program Code:

import java.util.Scanner;

public class MaximalSubsequence {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of elements in the sequence


System.out.print("Enter the number of elements in the
sequence (1 <= N <= 30): ");
int N = scanner.nextInt();

// Validate the input for N


if (N < 1 || N > 30) {
System.out.println("Invalid input. N should be
between 1 and 30.");
return;
}

// Input the sequence of integers


int[] sequence = new int[N];
System.out.println("Enter " + N + " integers:");
for (int i = 0; i < N; i++) {
sequence[i] = scanner.nextInt();
}

// Variables to keep track of the maximal subsequence


int maxSum = Integer.MIN_VALUE;
int startIndex = 0;
int endIndex = 0;

// Kadane's Algorithm to find the maximal subsequence


int currentSum = 0;
int tempStartIndex = 0;

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


currentSum += sequence[i];

if (currentSum > maxSum) {

56
maxSum = currentSum;
startIndex = tempStartIndex;
endIndex = i;
}

if (currentSum < 0) {
currentSum = 0;
tempStartIndex = i + 1;
}
}

// Output the start and end indices of the maximal


subsequence and its sum
System.out.println("Maximal Subsequence:");
System.out.println("Start Index: " + (startIndex + 1));
System.out.println("End Index: " + (endIndex + 1));
System.out.println("Sum: " + maxSum);
}
}

Variable Description Table:

Variable Data Type Description


Number of
elements in the
N int
sequence (1 <= N
<= 30).
Array to store the
sequence int[] sequence of
integers.
Maximum sum of
maxSum int any subsequence
found so far.
Start index of the
maximal
startIndex int
subsequence (0-
based index).
End index of the
maximal
endIndex int
subsequence (0-
based index).
Current sum of the
currentSum int subsequence being
considered.
Temporary start
index of the
tempStartIndex int
current
subsequence.

57
Output:

58
Question 11. Trinomial Triangle The trinomial triangle is a
number triangle of trinomial coefficients. It can be obtained
by starting with a row containing a single "1" and the next
row containing three 1s and then letting subsequent row
elements be computed by summing the elements above to
the left, directly above, and above to the right: Write a
program to accept the number of terms from the user and
print the above pattern of the Trinomial triangle in the given
format. Use the recursive technique to print the pattern. 1 1
1 1 1 2 3 2 1 1 3 6 7 6 3 1 1 4 10 16 19 16 10 4 1

Algorithm:

· Input Reading

 · Read the height of the triangle n from the user.

· Triangle Generation

 · For each row from 0 to n-1 (let's call the current row
index i):

o Print leading spaces to format the triangle


properly. The number of spaces is n−i−1n - i -
1n−i−1.
o For each column from -i to i (let's call the current
column index j):
 Calculate the trinomial value using the
trinomialValue function.
 Print the trinomial value, followed by a
space if j is less than i.
o Print a newline after each row.

· Trinomial Value Calculation

 · Use the recursive function trinomialValue to calculate


the value at position (n, k) in the trinomial triangle:

o If n is 0 and k is 0, return 1.
o If k is less than -n or greater than n, return 0.
o Otherwise, return the sum of trinomialValue(n - 1,
k - 1), trinomialValue(n - 1, k), and
trinomialValue(n - 1, k + 1).

59
Program Code:

import java.util.Scanner;

public class TRINOMIAL_TRIANGLE {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the height of the triangle: ");
int n = sc.nextInt();

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


// Print leading spaces for formatting
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
// Print trinomial values
for (int j = -i; j <= i; j++) {
System.out.print(trinomialValue(i, j));
if (j < i) {
System.out.print(" ");
}
}
System.out.println();
}
}

// Recursive function to calculate trinomial value


static int trinomialValue(int n, int k) {
if (n == 0 && k == 0) {
return 1;
}
if (k < -n || k > n) {
return 0;
}
return trinomialValue(n - 1, k - 1) + trinomialValue(n -
1, k) + trinomialValue(n - 1, k + 1);
}
}

Variable Description Table:

Variable Data Type Description


Height of the
n int
trinomial triangle.
Current row index
i int in the triangle
generation loop.
j int Current column
index in the

60
trinomial values
loop.
Function to
compute the
trinomialValue int
trinomial value at
a given (n, k).
Current column
index relative to
k int the current row in
the trinomial value
calculation.

Output:

61
Question 12. Unique Prime Number A prime number whose
all the digits are unique and not repeated in the number. For
example, 3, 7, 13, 37… whereas 11, 101… are not unique
prime numbers. Write a program in Java to accept a positive
number and check and print if it is a Unique Prime number
or a non-unique prime number. Use a separate method for
prime check that will use the recursive technique to check
the number passed as the argument is prime or not and
return true or false.

Algorithm:

· Input Reading

 · Read a positive integer number from the user.

· Check Unique Prime

 · Call the isUniquePrime method with the input


number.

o Inside isUniquePrime:
 Check if the number is prime using the
isPrime method.
 Check if the number has unique digits using
the hasUniqueDigits method.
 Return true if both conditions are met,
otherwise return false.

· Prime Check

 · Inside the isPrime method:

o If the number is less than or equal to 1, return


false (not a prime).
o If the divisor is 1, return true (base case, the
number is prime).
o If the number is divisible by the current divisor,
return false (not a prime).
o Otherwise, recursively call isPrime with a
decremented divisor.

· Unique Digits Check

 · Inside the hasUniqueDigits method:

62
o Initialize a boolean array digitSeen to keep track
of digits from 0 to 9.
o While there are digits left in the number:

 Extract the last digit of the number.


 If the digit has already been seen, return
false (digits are not unique).
 Mark the digit as seen.
 Remove the last digit from the number.

o If all digits are unique, return true.

· Output Result

 · Print whether the number is a unique prime or a non-


unique prime based on the result from isUniquePrime.

Program Code:

import java.util.Scanner;

public class UniquePrimeNumber {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int number = scanner.nextInt();

if (isUniquePrime(number)) {
System.out.println(number + " is a unique prime
number.");
} else {
System.out.println(number + " is a non-unique prime
number.");
}
}

// Method to check if a number is a unique prime


private static boolean isUniquePrime(int number) {
return isPrime(number, number / 2) &&
hasUniqueDigits(number);
}

// Recursive method to check if a number is prime


private static boolean isPrime(int number, int divisor) {
if (number <= 1) {

63
return false; // Numbers less than or equal to 1 are
not prime
}
if (divisor == 1) {
return true; // Base case: if divisor is 1, the number is
prime
}
if (number % divisor == 0) {
return false; // If number is divisible by any divisor, it
is not prime
}
return isPrime(number, divisor - 1); // Recursive call
with decremented divisor
}

// Method to check if a number has unique digits


private static boolean hasUniqueDigits(int number) {
boolean[] digitSeen = new boolean[10]; // Array to track
digits 0-9
while (number > 0) {
int digit = number % 10;
if (digitSeen[digit]) {
return false; // If digit is already seen, digits are
not unique
}
digitSeen[digit] = true;
number /= 10;
}
return true; // All digits are unique
}
}

Variable Description Table:

Variable Data Type Description


The positive
number int number input by
the user.
Array to track
digits from 0 to 9
digitSeen boolean[]
to check for
uniqueness.
The current digit
digit int being checked for
uniqueness.
divisor int The current divisor

64
used to check if
the number is
prime.
Result indicating
whether the
isPrime boolean
number is prime or
not.
Result indicating
whether all digits
hasUniqueDigits boolean
in the number are
unique.

Output:

65
Question 13. Parkside's Triangle is a mathematical pattern
that generates a triangle of numbers given two variables,
the size and the seed. Parkside's triangle is generated from
two numbers: the number of rows R, 1 <= R <= 39, and the
seed S, 1 <= S <= 9. The seed determines the upper left
number of the triangle. Using the sample input (below) to
determine the pattern of Parkside's Triangle, write a
program that accepts R and S from the input file and prints
Parkside's Triangle for those two values. INPUT FORMAT:
Two integers, R and S. OUTPUT FORMAT: Parkside's triangle,
printed with no extra blanks on the end and with the proper
spacing in the front as shown in the sample. INPUT: 6 1
OUTPUT : 1 2 4 7 2 7 3 5 8 3 8 6 9 4 9 1 5 1 6 2 3

Algortihm:

· Input Reading:

 · Prompt the user to enter the number of rows RRR for


the triangle.
 Prompt the user to enter the seed SSS for the triangle.

· Initialize Triangle:

 · Create a 2D array triangle of size R×RR \times RR×R


to store the values.

· Generate Parkside’s Triangle:

 · Set the first element of the triangle (triangle[0][0])


to the seed SSS.
 Initialize counters ccc and cccccc for the pattern
generation.
 For each row iii from 0 to R−1R-1R−1:

o Set the first element of the current row based on


the previous row’s first element and ccc,
adjusting it to be within 1-9 if necessary.
o For each subsequent element jjj in the current
row:
 Set the element based on the previous
element in the row and cccccc, adjusting it
to be within 1-9 if necessary.
 Increment cccccc for the next element.
o Increment ccc and reset cccccc to ccc for the next
row.

· Print Triangle:

66
 · For each row iii:

o Print leading spaces for formatting.


o Print the elements of the current row with proper
spacing.

Program Code:

import java.util.Scanner;

public class ParksideTriangle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read input values


System.out.println("Enter the Number of Rows(R): ");
int R = scanner.nextInt();
System.out.println("Enter the Seed(S): ");
int S = scanner.nextInt();

// Generate and print Parkside's Triangle


generateParksideTriangle(R, S);
}

// Method to generate and print Parkside's Triangle


private static void generateParksideTriangle(int R, int S)
{
int[][] triangle = new int[R][R];

// Initialize the first element of the triangle with the


seed
triangle[0][0] = S;
int c=1,cc=c;
// Fill the triangle according to the pattern rules
for (int i = 0; i < R; i++) {
// Calculate the first element of the current row
if(i>0)
triangle[i][0] = (triangle[i - 1][0] + c) ;
if(i==0)
triangle[i][0]=S;
if(triangle[i][0]>9)
triangle[i][0]-=9;
// Calculate the subsequent elements of the current
row
for (int j = 1; j < R - i; j++) {
triangle[i][j] = (triangle[i][j - 1] + cc);
cc++;
if(triangle[i][j]>9)

67
triangle[i][j]-=9;
}
c++;
cc=c;
}

// Print the triangle with proper formatting


for (int i = 0; i < R; i++) {
// Print leading spaces
for (int k = 0; k < i; k++) {
System.out.print(" ");
}
// Print the elements of the current row
for (int j = 0; j < R - i; j++) {
System.out.print(triangle[i][j]);
if (j != R - i - 1) {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Variable Description Table:

Variable Data Type Description


Number of rows in
R int the Parkside's
Triangle.
Seed value to
S int initialize the
triangle.
2D array to store
the values of
triangle int[][]
Parkside’s
Triangle.
Counter used to
increment the
c int
starting value of
each row.
Counter used to
cc int increment values
within each row.
Loop variable for
i int iterating through
rows.
j int Loop variable for
iterating through

68
elements within a
row.
Loop variable for
k int printing leading
spaces.

Output:

69
Question 14. Write a program to read three lines of upper
case (i.e., all CAPITAL LETTERS) text input (not more than 72
characters per line) from the user and print a vertical
histogram that shows how many times each letter (but not
blanks, digits, or punctuation) appears in the all-upper-case
input. Format your output exactly as shown below. INPUT
FORMAT: Three lines of upper-case text, not more than 72
characters per line. OUTPUT FORMAT: Several lines with
asterisks and spaces are followed by one line with the
upper-case alphabet separated by spaces. Do not print
unneeded blanks at the end of any line. Do not print any
leading blank lines.

Algorithm:

· Initialize:

 · Create an integer array counts of size 26 to store


counts for each letter from 'A' to 'Z'.

· Read Input:

 · Read three lines of input from the user.

· Process Input:

 · For each line, remove all non-uppercase letters.


 Count occurrences of each letter and update the counts
array accordingly.

· Determine Maximum Count:

 · Find the maximum value in the counts array to


determine the height of the histogram.

· Print Histogram:

 · Print the letters of the alphabet.


 Print the histogram upside down, where each row
corresponds to the counts of letters. Use * for counts
and spaces for zeros.

· Print Letters Again:

 · Print the letters of the alphabet again to align with


the histogram.

70
Program Code:

import java.util.Scanner;

public class VerticalHistogram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter three sentences: “);
int[] counts = new int[26]; // Array to store counts for
each letter

// Read three lines of input


for (int i = 0; i < 3; i++) {
String line = scanner.nextLine();
line = line.replaceAll("[^A-Z]", ""); // Remove non-
uppercase letters

// Count each letter


for (char c : line.toCharArray()) {
counts[c - 'A']++;
}
}

// Determine the maximum count to know the height of


the histogram
int maxCount = 0;
for (int count : counts) {
if (count > maxCount) {
maxCount = count;
}
}

// Print the alphabet letters


for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
System.out.println();

// Print the histogram upside down directly under the


corresponding alphabet letters
for (int i = maxCount; i > 0; i--) {
for (int j = 0; j < 26; j++) {
if (counts[j] >= i) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}

71
System.out.println();
}
System.out.println();
}
}

Variable Description Table:

Variable Data Type Description


Array to store
counts of
counts int[]
occurrences for
each letter (A-Z).
Maximum count of
occurrences of any
maxCount int
letter, determines
histogram height.
Stores each line of
input after
line String
removing non-
uppercase letters.
Character used to
iterate over the
c char
alphabet for
printing.
Loop variable used
i int for rows in the
histogram.
Loop variable used
j int for columns in the
histogram.

Output:

72
73
Question 15. The computer department of the Agency of
International Espionage is trying to decode intercepted
messages. The agency’s spies have determined that the
enemy encodes messages by first converting all characters
to their ASCII values and then reversing the string. For
example, consider A_z (the underscore is just to highlight
the space). The ASCII values for A, , z are 65, 32, 122
respectively. Concatenate them to get 6532122, and then
reverse this to get 2212356 as the coded message. Write a
program which reads a coded message and decodes it. The
coded message will not exceed 200 characters. it will
contain only alphabets (A……Z, and a-z) and spaces. ASCII
values of A…..Z are 65……90 and those of a….z are 97 ……
122. Test your program for the following data and some
random data. INPUT: Encoded Message: 2 3 1 2 1 7 9 8 6 2 3
1 0 1 9 9 5 0 1 8 7 2 3 7 9 2 3 1 0 1 8 1 1 7 9 2 7 OUTPUT:
THE DECODED MESSAGE: Have a Nice Day

Algorithm:

1.

Read Input:

2.
1. Prompt the user for the encoded message and
read it as a string.
3.

Decode the Message:

4.

1. Remove all spaces from the encoded message.


2. Reverse the string of digits.
3. Initialize an empty string to build the decoded
message.
4. Loop through the reversed string:

1. Check if the next three digits represent a


valid ASCII value (between 97-122 or 65-90):
1. If yes, convert these three digits to an
integer, then to a character, and
append to the decoded message.
2. If no, use the next two digits instead.

5. Return the decoded message.

74
5.

Check ASCII Validity:

6.

1. Convert the string to an integer and verify if it


falls within the range of valid ASCII values for
letters (either uppercase or lowercase).

Program Code:

import java.util.Scanner;

public class MessageDecoder {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user for the encoded message


System.out.print("Encoded Message: ");
String encodedMessage = scanner.nextLine();

// Call the method to decode the message and store the


result
String decodedMessage =
decodeMessage(encodedMessage);

// Print the decoded message


System.out.println("THE DECODED MESSAGE: " +
decodedMessage);
}

/**
* Decodes the given encoded message.
*
* @param encodedMessage The encoded message as a
string of digits separated by spaces.
* @return The decoded message as a string of characters.
*/
public static String decodeMessage(String
encodedMessage) {
// Remove spaces from the encoded message
String digits = encodedMessage.replace(" ", "");

// Reverse the digits manually


char[] reversedArray = new char[digits.length()];

75
for (int i = 0; i < digits.length(); i++) {
// Populate the reversedArray with characters from
the end of the digits string
reversedArray[i] = digits.charAt(digits.length() - 1 -
i);
}
// Convert the reversed character array back to a string
String reversedDigits = new String(reversedArray);

// Initialize an empty string to collect the decoded


message
String decodedMessage = "";
int i = 0;

// Loop through the reversed digits string to extract


ASCII values
while (i < reversedDigits.length()) {
// Check if the next three digits form a valid ASCII
value (between 97-122 or 65-90)
if (i + 2 < reversedDigits.length() &&
isValidASCII(reversedDigits.substring(i, i + 3))) {
// Extract the next three digits, convert to an
integer, then to a character and append to the decoded
message
decodedMessage += (char)
Integer.parseInt(reversedDigits.substring(i, i + 3));
i += 3; // Move to the next part of the string
} else {
// Extract the next two digits, convert to an
integer, then to a character and append to the decoded
message
decodedMessage += (char)
Integer.parseInt(reversedDigits.substring(i, i + 2));
i += 2; // Move to the next part of the string
}
}

// Return the decoded message


return decodedMessage;
}

/**
* Checks if a given string represents a valid ASCII value
for a character.
*
* @param str The string representing the ASCII value.
* @return True if the ASCII value is valid (A-Z or a-z),
false otherwise.
*/

76
public static boolean isValidASCII(String str) {
// Convert the string to an integer
int value = Integer.parseInt(str);
// Check if the value is within the range of uppercase or
lowercase letters
return (value >= 97 && value <= 122) || (value >= 65
&& value <= 90);
}
}

Variable Descirption Table:

Variable Data Type Description


Scanner object to
scanner Scanner read input from
the user.
The encoded
encodedMessage String message input by
the user.
The decoded
decodedMessage String message after
processing.
The encoded
digits String message with
spaces removed.
Character array
reversedArray char[] used to store the
reversed digits.
The string of digits
reversedDigits String
in reverse order.
Loop variable used
to iterate through
i int
the reversed
digits.
Substring
representing
str String
potential ASCII
values.
Integer value of
value int the ASCII
representation.

Output:

77
78
Bibliography:
The following sites have been
referred to for the following
projects:

 Blackbox coding.com
 Isc help.com
 Shutterstock.com
 Pintrest.com
 Passionate codin.com

79

You might also like