[go: up one dir, main page]

0% found this document useful (0 votes)
119 views145 pages

Ilovepdf Merged Merged

Uploaded by

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

Ilovepdf Merged Merged

Uploaded by

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

NAME : NAMAN BOTHRA

CLASS : XII
SECTION : D
SERIAL NO. – 21
SUBJECT : COMPUTER APPLICATION,
PROJECT WORK
PROJECT TOPIC: JAVA PROGRAMS
YEAR : ISC 2024
NAME : NAMAN BOTHRA
CLASS: XII
SECTION : D
SERIAL NO. – 21
SUBJECT : COMPUTER APPLICATIONS,
PROJECT WORK
PROJECT TOPIC: JAVA PROGRAMS
YEAR : ISC 2024
Table of Contents:
• Introduction to Java Programming Language:………………………………….
• Introduction to BlueJ Software..………………………………………………...
Program 1: Display all Prime-Adam integers that are in the range between m and n (both inclusive)
and output them along with the frequency, in the format given below: Test your program with the
following data and some random data……………………………………………………………

Program 2: A MOBIUS function M(N) returns the value -1 or 0 or 1 for a natural number (N) by the
following conditions are defined: When, M(N) = 1 if N = 1 M(N) = 0 if any prime factor of N is
contained in N more than once. M(N) = (-1)P if N is the product of ‘P’ distinct prime factors. Write a
program to accept a positive natural number (N) and display the MOBIUS result with proper
message. Design your program which will enable the output.………………………………..

Program 3: Display all Fascinating numbers that are in the range between m and n (both inclusive)
and output them along with the frequency, in the format given below: Test your program with the
following data and some random data……………….………………………………………..

Program 4: Write a program to declare a matrix a[][] of order (M × 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…………………………..

Program 5: 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……………………………………………………………

Program 6: Question 6 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 : a) Sort the elements of the single-
dimensional array in ascending order using any standard sorting technique and display the sorted
elements. b) 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: 1 2 5 8 1 2 5 1 1 2 1 2 1 1 2 5
c) Display the filled matrix in the above format……………………………………………….

Program 7: A Goldbach number is a positive even integer that can be expressed as the sum of two
odd primes. Note: All even integer numbers greater than 4 are Goldbach numbers. Example: 6 = 3 + 3
10 = 3 + 7 10 = 5 + 5 Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs,
i.e. 3, 7 and 5, 5. Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all the
odd prime pairs whose sum is equal to the number ‘N’………………………………………….

Program 8: 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)……………………………………………………..………

Program 9: A company manufactures packing cartons in four sizes, i.e. cartons to accomodate 6
boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to accept the number of boxes to be
packed (N) by the user (maximum up to 1000 boxes) and display the break up of the cartons used in
descending order of capacity (i.e. preference should be given to the highest capacity available, and if
boxes left are less than 6, an extra carton of capacity 6 should be used.)……………………
Program 10: Design a program to accept the number of participants N such that N must be greater
than 3 and less than 11. Create a double- dimensional array of size (N * 5) to store the answers of
each participant row-wise. Calculate the marks for each participant by matching the correct answer
stored in a single-dimensional array of size 5.Display the scores for each participant and also the
participants(s) having the highest score………………………………………………………

Program 11: Write a program to accept a plain text of length L, where L must be greater than 3 and
less than 100. Encrypt the text if valid as per the Caesar Cipher……………………………….

Program 12: Write a program to accept the numbers M and N from the user and print the smallest
required number whose sum of all its digits is equal to N. Also, print the total number of digits
present in the required number. The program should check for the validity of the inputs and display
an appropriate message for an invalid input……………………………………………………….

Program 13: Accept two positive integers ‘m’ and ‘n’, where m is less than n as user input. Display
the number of composite magic integers that are in the range between ‘m’ and ‘n’ (both inclusive) and
output them along with the frequency, in the format specified below…. ………………………

Program 14: , Write a program to determine how many prime palindrome integers are there in the
range between m and n (both inclusive) and output them. The input contains two positive integers m
and n where m < 3000 and n < 3000. Display the number of prime palindrome integers in the
specified range along with their values………………………………………………………..

Program 15: Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of
rows and ‘N’ is the number of columns such that both M and N must be greater than 2 and less than
20. Allow the user to input integers into this matrix. Perform the following tasks on the matrix: 1.
Display the input matrix. 2. Find the maximum and minimum value in the matrix and display them
along with their position. 3. Sort the elements of the matrix in ascending order using any standard
sorting technique and rearrange them in the matrix. 4. Output the rearranged matrix……………

Program 16: Write a program to input a natural number less than 1000 and display it in words.

Program 17: Write a program to generate and print lucky numbers less than a given number
N < 50…...………………………………………………………………………………………

Program 18: Read in 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 data in the
following way : Find the maximum value in data and put 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.…………………………………

Program 19: Write a program to declare a square matrix A [ ] [ ]of order N (N < 20). Allow the user to
input positive integers in to this matrix. Perform the following task on the matrix: (i) Output the
original matrix. (ii) Fins the SADDLE POINT for the matrix such that is the minimum element for
the row to which it belongs and the maximum element for the column to which it belongs. Saddle
point for a given matrix is always unique. If the matrix has no saddle point, output the message “ NO
SADDLE POINT ”.………………………………………………………………………

Program 20: Write a program that takes the coded text (less than 100 characters), the shift value and
prints the decoded original text. Your program must reject any non-valid value for shift and display an
error message “INVALID SHIFT VALUE)”.Assume all characters are upper case……………..
Introduction to Java Programming Language:
Java was created by James Gosling and his team at Sun Microsystems
(which was later acquired by Oracle Corporation). The development of
Java began in the early 1990s, and the first official version, Java 1.0, was
released in 1996. James Gosling is often referred to as the "father of Java"
due to his significant contributions to its design and development.
Java Virtual Machine (JVM):
Java Virtual Machine (JVM) is a critical component of the Java
programming language and platform. It plays a crucial role in enabling
Java's "write once, run anywhere" principle, where Java code can be
written on one platform and executed on any platform with a compatible
JVM. Here are three key aspects of JVM:

Execution Environment:
JVM serves as a runtime environment for executing Java applications. It takes
compiled Java bytecode as input and executes it by converting the bytecode into
native machine code or interpreted code.This enables Java applications to be
platform-independent, as the bytecode remains consistent across different
platforms while the JVM handles the platform-specific execution.

Platform Independence:
Java source code is compiled into bytecode, a platform-independent
representation of the code. Bytecode is not tied to a specific hardware or
operating system.When a Java application runs, the JVM on that platform
interprets or compiles the bytecode, adapting it to the host system's architecture.

Memory Management and Optimization:


JVM manages memory allocation and garbage collection, ensuring efficient
memory utilization and preventing memory leaks.

• Platform Independence: Java is a versatile programming language


known for its platform independence. It achieves this through its
write-once-run-anywhere philosophy. Java source code is compiled
into bytecode, which can run on any platform with a compatible
Java Virtual Machine (JVM). This capability enables developers to
create applications that can be executed on various devices and
operating systems without modification.

• Object-Oriented: Java is fully object-oriented, emphasizing the use


of classes and objects. This promotes modular and reusable code,
making it easier to manage complex projects. Encapsulation,
inheritance, and polymorphism are core principles that facilitate
code organization and maintenance.

• Robust and Secure: Java places a strong emphasis on robustness


and security. Its memory management features, including
automatic garbage collection, help prevent memory leaks and
buffer overflows. Java's security architecture includes features like
sandboxing and access controls to safeguard against malicious
code and unauthorized access to resources.

Introduction to BlueJ Software:


• Educational IDE: BlueJ is a user-friendly Integrated Development
Environment (IDE) designed with education in mind. It provides a
simplified environment for beginners, especially those learning
Java programming. Its intuitive interface and visual tools help
newcomers grasp fundamental programming concepts.

• Object-Oriented Visualization: One of BlueJ's distinctive features


is its ability to visualize object-oriented concepts. It allows
developers to interact with objects, inspect their attributes, and call
methods directly. This hands-on approach aids in understanding
class relationships and object behavior.

• Built-in Tools: BlueJ offers built-in tools that simplify the


development process for learners. Features like an interactive
object bench, class diagram viewer, and debugger enhance the
learning experience. These tools empower beginners to experiment,
debug, and gain insights into program execution.
Question 1
A Prime-Adam integer is a positive integer (without leading zeroes) which is a prime as well as an
Adam number. Prime number: A number which has only two factors, i.e. 1 and the number itself.
Example: 2, 3, 5, 7, etc. Adam number: The square of a number and the square of its reverse are
reverse to each other. Example: If n = 13 and reverse of ‘n’ is 31, then, 132 = 169, and 312 = 961
which is reverse of 169. Thus, 13 is an Adam number. Accept two positive integers m and n, where
m is less than n as user input.
Display all Prime-Adam integers that are in the range between m and n (both inclusive) and output
them along with the frequency, in the format given below: Test your program with the following
data and some random data:
Example 1:
INPUT: m = 5 n = 100
OUTPUT: The Prime-Adam integers are: 11, 13, 31
Frequency of Prime-Adam integers is: 3
Example 2: INPUT: m = 100 n = 200
OUTPUT: The Prime-Adam integers are: 101, 103, 113
Frequency of Prime-Adam integers is: 3
Example 3: INPUT: m = 50 n = 70
OUTPUT: The Prime-Adam integers are: NIL Frequency of Prime-Adam integers is: 0
Example 4: INPUT: m = 700 n = 450
OUTPUT: Invalid Input

ALGORITHM:

Step 1: Define the class PrimeAdamChecker.


Step 2: Declare the data members startRange and endRange.
Step 3: Define the default constructor PrimeAdamChecker(), initialize startRange and endRange to
0.
Step 4: Define the parameterized constructor PrimeAdamChecker(start, end), set startRange to start,
and endRange to end.
Step 5: Define the acceptRange() method to accept the range of integers from the user.
Step 6: Create a Scanner object to read user input.
Step 7: Display a message to the user to enter the range.
Step 8: Read the startRange and endRange from the user.
Step 9: Check if the startRange is greater than the endRange. If true, display "INVALID RANGE"
and exit the program.
Step 10: Define the isPrime(num) method to check if a number is prime or not.
Step 11: Iterate from i = 2 to num/2.
Step 12: If num is divisible by i, return false.
Step 13: If the loop completes without returning false, return true, indicating num is prime.
Step 14: Define the reverseNumber(num) method to reverse a number.
Step 15: Initialize variables reversed to 0 and temp to 0.
Step 16: While num is greater than 0, do the following:
a. Set temp to num % 10 (last digit of num).
b. Update reversed by appending temp to its end.
c. Reduce num to num / 10, removing its last digit.
Step 17: Return the reversed number.
Step 18: Define the displayPrimeAdamIntegers() method to find and display Prime-Adam integers.
Step 19: Initialize count to 0, reversedNum to 0, squaredNum to 0, and squaredReversed to 0.
Step 20: Initialize hasPrimeAdam to false to check if there are any Prime-Adam integers.
Step 21: Iterate from num = startRange to endRange.
Step 22: Check if num is greater than 10 and isPrime(num).
Step 23: If true, do the following:
a. Set reversedNum to reverseNumber(num).
b. Calculate squaredNum as the square of num.
c. Calculate squaredReversed as the square of reversedNum.
d. If squaredNum is equal to the reverse of squaredReversed:
i. Print num and a space.
ii. Increment count by 1.
iii. Set hasPrimeAdam to true.
Step 24: After the loop, print a new line.
Step 25: Check if hasPrimeAdam is false.
Step 26: If true, print "NIL" to indicate no Prime-Adam integers were found.
Step 27: Print the frequency of Prime-Adam integers (the value of count).
Step 28: Define the main() method.
Step 29: Create an object obj of PrimeAdamChecker.
Step 30: Call obj.acceptRange() to get the range from the user.
Step 31: Call obj.displayPrimeAdamIntegers() to display Prime-Adam integers within the given
range.
Step 32: End of the main method and the program.

VARIABLE DEXCRIPTION TABLE:

Variable Data Type Description

Stores the starting value of the range of integers provided by the


startRange int user.

Stores the ending value of the range of integers provided by the


endRange int user.

scanner Scanner Used to read input from the user.

num int Loop variable used to iterate through the numbers in the range.

reversedNum int Stores the reversed form of the current number during the loop.

squaredNum int Stores the square of the current number during the loop.

Stores the square of the reversed form of the current number


squaredReversed int during the loop.

Counts the number of Prime-Adam integers found within the


count int given range.

A boolean flag to check if there are any Prime-Adam integers


hasPrimeAdam boolean within the given range.

PrimeAdamChec An object of the PrimeAdamChecker class used in the main


obj ker method.
SOURCE CODE:
import java.util.Scanner;
public class PrimeAdamChecker {
// Start of the class
private int startRange, endRange; // Data members
public PrimeAdamChecker()
{ // Default constructor
startRange = 0;
endRange = 0;
}

public PrimeAdamChecker(int start, int end)


{ // Parameterized constructor
this.startRange = start;
this.endRange = end;
}
public void acceptRange()
{ // Method to accept the range
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the range:");
startRange = scanner.nextInt();
endRange = scanner.nextInt();
if (startRange > endRange)
{ // Conditional check for invalid range
System.out.println("INVALID RANGE");
System.exit(0);
}
}

public boolean isPrime(int num)


{ // Method to check if a number is prime or not
for (int i = 2; i <= num / 2; i++)
{
if (num % i == 0)
return false;
}
return true;
}
public int reverseNumber(int num)
{ // Method to reverse a number
int reversed = 0;
int temp = 0;
while (num > 0) {
temp = num % 10;
reversed = (reversed * 10) + temp;
num = num / 10;
}
return reversed;
}
public void displayPrimeAdamIntegers()
{ // Method to display Prime-Adam integers
System.out.println("The Prime-Adam Integers are:");
int count = 0;
int reversedNum = 0;
int squaredNum = 0;
int squaredReversed = 0;
boolean hasPrimeAdam = false;
for (int num = startRange; num <= endRange; num++)
{
if (num > 10 && isPrime(num))
{
reversedNum = reverseNumber(num);
squaredNum = num * num; // Square of the number
squaredReversed = reversedNum * reversedNum; // Square of the reversed number
if (squaredNum == reverseNumber(squaredReversed))
{ // Check if the square of the number is equal to
// the square of the reversed number
System.out.print(num + " ");
count++;
hasPrimeAdam = true;
}
}
}
System.out.println();
if (!hasPrimeAdam)
{
System.out.println("NIL");
System.out.println("Frequency of Prime-Adam integers is: " + count);
} else
{
System.out.println("Frequency of Prime-Adam integers is: " + count); // Displays the frequency
}
}
public static void main(String args[])
{ // Start of the main method
PrimeAdamChecker obj = new PrimeAdamChecker();
obj.acceptRange();
obj.displayPrimeAdamIntegers();
} // End of the main method
} // End of the class
OUTPUT:
Question 2
A MOBIUS function M(N) returns the value -1 or 0 or 1 for a natural number (N) by the
following conditions are defined: When, M(N) = 1 if N = 1 M(N) = 0 if any prime factor of N
is contained in N more than once. M(N) = (-1)P if N is the product of ‘P’ distinct prime
factors.
Write a program to accept a positive natural number (N) and display the MOBIUS result with
proper message. Design your program which will enable the output in the format given
below:
Sample 1: INPUT: 78
OUTPUT: 78 = 2 × 3 × 13
NUMBER OF DISTINCT PRIME FACTORS = 3
M(78) = -1
Sample 2: INPUT: 34
OUTPUT: 34 = 2 × 17
NUMBER OF DISTINCT PRIME FACTORS = 2
M(34) = 1
Sample 3: INPUT: 12
OUTPUT: 12 = 2 × 2 × 3
DUPLICATE PRIME FACTORS M(12) = 0
Sample 4: INPUT: 1
OUTPUT: 1 = 1
NO PRIME FACTORS M(1) = 1

ALGORITHM:

Step 1: START OF THE PROGRAM


1. Define a class called MobiusCalculator.

Step 2: Declare an integer variable named num to hold the input number.

Step 3: Constructors
1. Define a default constructor MobiusCalculator() that initializes num with the value 78.
2. Define a parameterized constructor MobiusCalculator(int a) that sets num to the provided
value.

Step 4: Input Method


1. Define a method called takeInput().
2. Create a Scanner object named scanner to read user input.
3. Display a prompt asking the user to enter a number.
4. Read and store the input in the variable num.
Step 5: Prime Checking Method
1. Define a method called checkPrime(int a) that takes an integer a as input.
2. Initialize an integer variable named flag to 0.
3. Use a loop to iterate from 2 to a divided by 2.
a. If a is divisible by the current loop variable i, increment flag.
4. If flag remains 0, return true, indicating that a is prime; otherwise, return false.

Step 6: Count Distinct Prime Factors Method


1. Define a method called countDistinctPrimeFactors(int a) that takes an integer a as input.
2. Initialize an integer variable named count to 0.
3. Use a loop to iterate from 2 to a divided by 2.
a. If a is divisible by the current loop variable i and checkPrime(i) returns true, increment
count.
4. Return the value of count, representing the number of distinct prime factors of a.

Step 7: Display Method


1. Define a method called displayResult().
2. Initialize integer variables: hasDuplicate to 0 and product to 1.
3. Check if num is equal to 1:
a. If true, display "1 = 1", "NO PRIME FACTORS", and "M(1) = 1".
b. If false, continue to the next step.
4. Display num followed by an equal sign.
5. Iterate from 2 to num - 1 using a loop variable i.
6. Check if num is divisible by i and checkPrime(i) returns true.
a. If true:
i. Check if num is divisible by i * i.
- If true, set hasDuplicate to 1, display i followed by "*", and update product.
- If false, update product by multiplying it with i.
ii. Check if product is not equal to num. Display i followed by "*" if true, otherwise just i.
7. Check if hasDuplicate is 1:
a. If true, display "DUPLICATE PRIME FACTORS" and "M(num) = 0".
b. If false, display the number of distinct prime factors using countDistinctPrimeFactors()
and calculate M(num) using (int) Math.pow(-1, countDistinctPrimeFactors(num)).

Step 8: Main Method


1. Define the main method public static void main(String args[]).
2. Create an instance of MobiusCalculator named calculator.
3. Call the takeInput() method on the calculator object to get user input.
4. Call the displayResult() method on the calculator object to display the calculated results.

Step 9: End of Algorithm.


VARIABLE DESCRIPTION TABLE:

Variable
Name Type Description

num int Holds the input number for calculations.

flag int Used in the prime checking loop to count factors of a number.

i int Loop variable for iteration in various loops.

hasDuplicate int Used to determine if there are duplicate prime factors of the number.

Accumulator for the product of prime factors (used to detect


product int duplicates and for Mobius function).

scanner Scanner Input scanner to read user input.

An instance of the MobiusCalculator class used to perform


calculator Object calculations and display results.

SOURCE CODE:
import java.util.*;
class MobiusCalculator
{
int num;
MobiusCalculator()
{
num = 78;
}
MobiusCalculator(int a)
{
num = a;
}
public void Input()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
num = scanner.nextInt();
}
public boolean checkPrime(int a)
{
int flag = 0;
int i;
for (i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
flag++;
}
}
if (flag == 0)
return true;
else
return false;
}
public int countDistinctPrimeFactors(int a)
{
int count = 0;
int i;
for (i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
if (checkPrime(i))
count++;
}
}
return count;
}
public void displayResult()
{
int hasDuplicate = 0;
int product = 1;
int i;
if (num == 1)
{
System.out.println("1 = 1");
System.out.println("NO PRIME FACTORS");
System.out.println("M(1) = 1");
} else
{
System.out.print(num + " = ");
for (i = 2; i < num; i++)
{
if (num % i == 0 && checkPrime(i))
{
if (num % (i * i) == 0)
{
hasDuplicate = 1;
System.out.print(i + "*");
product = product * i * i;
} else
{
product = product * i;
}
if (product!= num)
System.out.print(i + "*");
else
System.out.print(i);
}
}
if (hasDuplicate == 1)
{
System.out.println("\nDUPLICATE PRIME FACTORS");
System.out.println("M(" + num + ") = 0");
}
else {
System.out.println("\nNUMBER OF DISTINCT PRIME FACTORS: " +
countDistinctPrimeFactors(num));
System.out.println("M(" + num + ") = " + (int) Math.pow(-1,
countDistinctPrimeFactors(num)));
}
}
}
public static void main(String args[])
{
MobiusCalculator calculator = new MobiusCalculator();
calculator.Input();
calculator.displayResult();
}
OUTPUT:
}
QUESTION 3
A Fascinating number is one which when multiplied by 2 and 3 and then, after the results are concatenated
with the original number, the new number contains all the digits from 1 to 9 exactly once. There can be any
number of zeroes and are to be ignored.

Example: 273 273 × 1 = 273 273 × 2 = 546 273 × 3 = 819

Concatenating the results we get, 273546819 which contains all digits from 1 to 9 exactly once. Thus, 273 is
a Fascinating number. Accept two positive integers m and n, where m must be less than n and the values of
both ‘m’ and ‘n’ must be greater than 99 and less than 10000 as user input. Display all Fascinating numbers
that are in the range between m and n (both inclusive) and output them along with the frequency, in the
format given below: Test your program with the following data and some random data:

Example 1:

INPUT: m = 100 n = 500

OUTPUT: THE FASCINATING NUMBERS ARE: 192 219 273 327

FREQUENCY OF FASCINATING NUMBERS IS: 4 Example 2:

INPUT: m = 900 n = 5000

OUTPUT: THE FASCINATING NUMBERS ARE: 1902 1920 2019 2190 2703 2730 3027 3270

FREQUENCY OF FASCINATING NUMBERS IS: 8

Example 3:

INPUT: m = 400 n = 900

OUTPUT: THE FASCINATING NUMBERS ARE: NIL

FREQUENCY OF FASCINATING NUMBERS IS: 0

Example 4:

INPUT: m = 70 n = 450

OUTPUT: INVALID INPUT

ALGORITHM:
-STEP 1: Start the program.
isFNum method:
- STEP 2 : The method takes an integer num as input.
- STEP 3: It calculates num2 (2 times num) and num3 (3 times num).
- STEP 4:It concatenates the string representation of num, num2, and num3 into the concat string.It
initializes an array digitCount of size 10 to count the occurrence of digits (from 0 to 9).
- STEP 5: It iterates over each character in the concat string, excluding '0' digits. For each non-zero
digit, it increments the corresponding count in the digitCount array.
-STEP 6 :After counting the digits, it checks if each digit from 1 to 9 occurs exactly once in the
digitCount array. If any digit occurs more than once or if any of the digits from 1 to 9 is missing, it
returns false, indicating that num is not fascinating.
- STEP 7: If all the digits from 1 to 9 occur exactly once, it returns true, indicating that num is
fascinating.
findFascinatingNumbers method:
-STEP 8: The method takes two integers m and n as inputs, representing the range.
-STEP 9: It first checks if the input range is valid (m < 100, n > 9999, m > n). If the range is invalid,
it prints "INVALID INPUT" and returns.
-STEP 10: It initializes a boolean variable foundFascinating to track whether any fascinating
numbers are found in the range.
- STEP 11 : It then iterates through the range from m to n.
- STEP 12 : For each number in the range, it calls the isFNum method to check if the number is
fascinating.If a fascinating number is found, it prints the number and sets foundFascinating to
true.If no fascinating numbers are found, it prints "NIL".
-STEP 13 : Finally, it calls the countFascinatingNumbers method to count the total fascinating
numbers in the range and prints the count.
countFascinatingNumbers method:
-STEP 14 : The method takes two integers m and n as inputs, representing the range. It initializes a
counter variable count to 0. It then iterates through the range from m to n.
STEP 15: For each number in the range, it calls the isFNum method to check if the number is
fascinating. If the number is fascinating, it increments the count variable. After iterating through the
range, it returns the total count of fascinating numbers.
main method:
- STEP 16: The main method is the entry point of the program. It prompts the user to enter the range
[m, n]. It reads the values of m and n from the user using a Scanner. It then calls the
findFascinatingNumbers method with the entered range to find and display the fascinating numbers
and their count.
- STEP 17:End the program.
VARIABLE DESCRIPTION TABLE:

Variable Description Type

Represents the current number being evaluated in the


num range. int

num2 Stores the value of num multiplied by 2. int

num3 Stores the value of num multiplied by 3. int

Concatenates the string representations of num, num2, and


concat num3. String

An array to count the occurrence of digits (from 0 to 9)


digitCount in concat. int[]

m Represents the lower bound of the input range. int

n Represents the upper bound of the input range. int


SOURCE CODE:
import java.util.Scanner;

public class FascinatingNumbers


{
int num2 , num3;

// Parameterized constructor
public FascinatingNumbers(int m, int n)
{
this.num2 = m;
this.num3 = n;
FascinatingNumber(m, n); // Call the FascinatingNumber method with the given range
}
// Method to check if a number is a fascinating number
public boolean isFascinatingNumber(int num)
{
num2 = num * 2;
num3 = num * 3;
String concat = Integer.toString(num) + Integer.toString(num2) +
Integer.toString(num3);
int[] digitCount = new int[10];

// Count the occurrence of digits in the concatenated string


for (char digit : concat.toCharArray())
{
if (digit != '0')
{
digitCount[digit - '0']++;
}
}

// Check if each digit from 1 to 9 occurs exactly once


for (int i = 1; i <= 9; i++)
{
if (digitCount[i] != 1)
{
return false;
}
} return true;
}

// Method to find fascinating numbers and count their frequency


public void FascinatingNumber(int m, int n)
{
if (m < 100 || n > 9999 || m > n)
{
System.out.println("INVALID INPUT");
return;
}
boolean foundFascinating = false;
System.out.println("THE FASCINATING NUMBERS ARE:");

// Iterate through the given range and find fascinating numbers


for (int num = m; num <= n; num++)
{
if (isFascinatingNumber(num))
{
System.out.print(num + " ");
foundFascinating = true;
}
}
if (!foundFascinating)
{
System.out.println("NIL");
}
System.out.println("\nFREQUENCY OF FASCINATING NUMBERS IS: " +
countFascinatingNumbers(m, n));
}

// Method to count the frequency of fascinating numbers in the given range


public int countFascinatingNumbers(int m, int n)
{
int count = 0;

// Iterate through the range and count fascinating numbers


for (int num = m; num <= n; num++)
{
if (isFascinatingNumber(num))
{
count++;
}
} return count;
}
public static void main(String[] args)
{
int m, n;
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE RANGE");
m = sc.nextInt();
n = sc.nextInt();

// Create an instance of FascinatingNumbers using the parameterized constructor


FascinatingNumbers obj = new FascinatingNumbers(m, n);

// Close the scanner


sc.close();
}
}
OUTPUT :

EXAMPLE 2:
EXAMPLE 3:

EXAMPLE 4:
QUESTION 4
Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows and ‘N’
is the number of columns such that the value of ‘M’ must be greater than 0 and less than 10 and the
value of ‘N’ must be greater than 2 and less than 6. Allow the user to input digits (0 – 7) only at
each location, such that each row represents an octal number.
Example: 2 3 1 (decimal equivalent of 1st row = 153 i.e. 2 × 82 + 3 × 81 + 1 × 80)
4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4 × 82 + 0 × 81 + 5 × 80)
1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1 × 82 + 5 × 81 + 6 × 80)
Perform the following tasks on the matrix
a) Display the original matrix.
b) Calculate the decimal equivalent for each row and display as per the format given below.
Test your program for the following data and some random data:
Example 1: INPUT:
M = 1 N = 3 Enter elements for row 1: 1 4 4
OUTPUT: Filled Matrix: 1 4 4
Decimal Equivalent: 100
Example 2: INPUT: M = 3 N = 4
Enter elements for row 1: 1 1 3 7
Enter elements for row 2: 2 1 0 6
Enter elements for row 3: 0 2 4 5
OUTPUT:
Filled Matrix: 1 1 3 7
2106
. 0245
Decimal Equivalent: 607 1094 165
Example 3:
INPUT: M = 3 N = 3
Enter elements for row 1: 2 4 8
OUTPUT: Invalid Input.
Example 4: INPUT: M = 4 N = 6
OUTPUT: Out of range.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create a Scanner object to read input from the user.
STEP 3: Prompt the user to input the number of rows M for the matrix and validate it to be between
1 and 9 (inclusive).Prompt the user to input the number of columns N for the matrix and validate it
to be between 3 and 5 (inclusive).
STEP 4: Create a 2D array matrix with dimensions M x N to store the octal elements.
STEP 5: Input elements for each row of the matrix:
a. For each row i from 1 to M:
i. Prompt the user to enter N octal elements between 0 and 7 (inclusive) for the row.
ii. If any of the input elements are out of the valid range, display an error message and prompt again
for the invalid input.
iii. Store the valid input elements in the matrix array.
STEP 6: Display the filled original matrix:
a. For each row i from 1 to M:
i. For each column j from 1 to N, display the element in the matrix at position [i][j].
ii. Move to the next line after displaying each row.
STEP 7: Calculate and display the decimal equivalents:
a. For each row i from 1 to M:
i. Initialize a variable decimal to 0.
ii. For each column j from N to 1 (reverse order):
STEP 8. Calculate the decimal value of the element at position [i][j] using matrix[i][j] * 8^(N - j).
STEP 9:. Add the calculated decimal value to the decimal variable. Display the decimal value for
the current row.
STEP 10: End the program.
VARIABLE DESCRIPTION TABLE:

Data
Variable Type Description

sc Scanner A Scanner object to read input from the user.

Stores the number of rows in the matrix. It is validated to be between 1


M int and 9 (inclusive).

Stores the number of columns in the matrix. It is validated to be


N int between 3 and 5 (inclusive).

A 2D array to store the octal elements of the matrix. It has dimensions


matrix int[][] M x N.

i int Loop variable used for iterating through rows of the matrix.

j int Loop variable used for iterating through columns of the matrix.

Temporary variable used to store the user's input for each element of
input int the matrix.

Temporary variable used to calculate and store the decimal equivalent


decimal int of each row of the matrix.
SOURCE CODE:
import java.util.Scanner;
public class OctalMatrix
{
// Instance variables
private int[][] matrix; // Stores the matrix elements
private int M; // Number of rows
private int N; // Number of columns
private Scanner sc; // Scanner object for user input

// Default Constructor
public OctalMatrix()
{
sc = new Scanner(System.in);
readMatrixDimensions(); // Read matrix dimensions from user
createMatrix(); // Create the matrix with given dimensions
fillMatrix(); // Input elements for each row
}

// Parameterized Constructor
public OctalMatrix(int rows, int columns)
{
sc = new Scanner(System.in);
M = rows; // Set rows
N = columns; // Set columns
createMatrix(); // Create the matrix with given dimensions
fillMatrix(); // Input elements for each row
}
// Method to read matrix dimensions from user
private void readMatrixDimensions()
{
// Input M and N from the user
do {
System.out.print("Enter the number of rows (M, 1-9): ");
M = sc.nextInt();
if (M <= 0 || M >= 10)
{
System.out.println("Invalid Input. The number of rows must be
between 1 and 9.");
}
} while (M <= 0 || M >= 10);

do {
System.out.print("Enter the number of columns (N, 3-5): ");
N = sc.nextInt();
if (N <= 2 || N >= 6)
{
System.out.println("Out of range. The number of columns must be
between 3 and 5.");
}
} while (N <= 2 || N >= 6);
}

// Method to create the matrix with given dimensions


private void createMatrix()
{
// Create the matrix
matrix = new int[M][N];
}

// Method to input elements for each row of the matrix


private void fillMatrix()
{
// Input elements for each row
for (int i = 0; i < M; i++)
{
System.out.print("Enter elements for row " + (i + 1) + ": ");
for (int j = 0; j < N; j++)
{
int input;
do {
input = sc.nextInt();
if (input < 0 || input > 7)
{
System.out.println("Invalid Input. The elements must be between
0 and 7.");
}
} while (input < 0 || input > 7);

matrix[i][j] = input;
}
}
}
// Method to display the matrix
public void displayMatrix()
{
System.out.println("\nFilled Matrix:");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

// Method to calculate and display decimal equivalents


public void displayDecimalEquivalents()
{
System.out.println("Decimal Equivalent:");
for (int i = 0; i < M; i++)
{
int decimal = 0;
for (int j = N - 1; j >= 0; j--)
{
decimal += matrix[i][j] * Math.pow(8, (N - 1) - j);
}
System.out.println(decimal);
}
}

// Main method
public static void main(String[] args)
{
OctalMatrix defaultMatrix = new OctalMatrix(); // Using the default
constructor
defaultMatrix.displayMatrix();
defaultMatrix.displayDecimalEquivalents();

OctalMatrix customMatrix = new OctalMatrix(3, 4); // Using the


parameterized constructor
customMatrix.displayMatrix();
customMatrix.displayDecimalEquivalents();
}
}
OUTPUT:
EXAMPLE 1:

EXAMPLE 2:
EXAMPLE 3:

EXAMPLE 4:
QUESTION 5:
Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user to generate
and display the corresponding date.

Also, accept N (1 <= N <= 100) from the user to compute and display the future date corresponding to ‘N’
days after the generated date. Display an error message if the value of the day number, year and N are not
within the limit or not according to the condition specified.

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

Example 1:

INPUT: DAY NUMBER: 255

YEAR: 2018

DATE AFTER (N DAYS): 22

OUTPUT: DATE: 12TH SEPTEMBER, 2018

DATE AFTER 22 DAYS: 4TH OCTOBER, 2018

Example 2:

INPUT:

DAY NUMBER: 360

YEAR: 2018 DATE AFTER (N DAYS): 45

OUTPUT: DATE: 26TH DECEMBER, 2018

DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019

Example 3:

INPUT: DAY NUMBER: 500

YEAR: 2018

DATE AFTER (N DAYS): 33

OUTPUT: DAY NUMBER OUT OF RANGE

Example 4: INPUT:

DAY NUMBER: 150

YEAR: 2018 DATE AFTER (N DAYS): 330

OUTPUT:

DATE AFTER (N DAYS) OUT OF RANGE


ALGORITHM:
Step 1: Start the program.
Step 2: Create a Scanner object scanner to read input from the user.
Step 3 :Prompt the user to input the day number dayNumber, the year year, and the
number of days n after which the future date needs to be generated. Close the Scanner
object.
Step 4: Validate the inputs to ensure they are within the valid range:
a. If dayNumber is less than 1, greater than 366, year is less than 1000 or greater than
9999, or n is less than 1 or greater than 100, display "INPUT OUT OF RANGE" and
end the program.
Step 5: Call the generateDate() method with dayNumber and year as arguments to
generate and display the corresponding date in the format "DAY MONTH_NAME,
YEAR".
Step 6: Call the FutureDate() method with dayNumber, year, and n as arguments to
compute and display the future date after n days in the same format as step 6.
Step 7: Define the generateDate() method that takes dayNumber and year as
arguments: Initialize variables month and day to 0 to store the month and day of the
date.
STEP 8: Define an array daysInMonth containing the number of days in each month
(index 0 is not used).
STEP 9: If the year is a leap year (divisible by 4 and not divisible by 100, or divisible
by 400), update daysInMonth for February to 29 days.
STEP 10: Loop through the months (from 1 to 12) and find the month and day of the
date corresponding to dayNumber.
STEP 11: Determine the suffix ("ST", "ND", "RD", or "TH") for the day based on its
value. Determine the month name based on the month number.
STEP 12: Return the formatted date as a string.
Step 13: Define the FutureDate() method that takes dayNumber, year, and n as
arguments:
Step 14:. Initialize a variable totalDays to dayNumber + n to represent the total days
after adding n days to the current day.
Step 15; Update daysInMonth as in step 8 for leap year consideration.
Step 16: While totalDays is greater than 366, keep adjusting for leap years (either
365 or 366 days). Find the month and day of the future date corresponding to
totalDays as in step 8.
Step 17: Determine the suffix ("ST", "ND", "RD", or "TH") for the day based on its
value.
Step 18: Determine the month name based on the month number.
STEP 19: Return the formatted future date as a string.
STEP 20: End the program.

VARIABLE DESCRIPTION TABLE:

Data
Variable Description Type
scanner Scanner object to read input from the user Scanner
dayNumber The day number input by the user int
year The year input by the user int

The number of days input by the user to calculate the future


n date int

date The generated date in the format "DAY MONTH_NAME, YEAR" String

The future date after n days in the format "DAY


futureDate MONTH_NAME, YEAR" String
month The calculated month number in the range 1 to 12 int
day The calculated day number for the date int
daysInMonth An array to store the number of days in each month int[]
suffix The suffix ("ST", "ND", "RD", or "TH") for the day String
monthName The name of the month corresponding to the month number String
totalDays The total days after adding n days to the day number int
i Loop counter variable used in for loops int
SOURCE CODE:
import java.util.Scanner;
public class DateGenerator
{
// Instance variables
private int dayNumber;
private int year;
private int n;

// Default Constructor
public DateGenerator()
{
Scanner scanner = new Scanner(System.in);
System.out.print("DAY NUMBER: ");
dayNumber = scanner.nextInt();
System.out.print("YEAR: ");
year = scanner.nextInt();
System.out.print("DATE AFTER (N DAYS): ");
n = scanner.nextInt();
scanner.close();
if (dayNumber < 1 || dayNumber > 366 || year < 1000 || year > 9999 || n < 1 || n >
100) {
System.out.println("INPUT OUT OF RANGE");
return;
}
// Generate and display the corresponding date
String date = generateDate(dayNumber, year);
System.out.println("DATE: " + date);
// Compute and display the future date after N days
String futureDate = FutureDate(dayNumber, year, n);
System.out.println("DATE AFTER " + n + " DAYS: " + futureDate);
}

// Parameterized Constructor
public DateGenerator(int dayNumber, int year, int n){
this.dayNumber = dayNumber;
this.year = year;
this.n = n;
}
public static String generateDate(int dayNumber, int year)
{
int month = 0;
int day = 0;
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
{
daysInMonth[2] = 29; // Leap year
}

for (int i = 1; i <= 12; i++)


{
if (dayNumber <= daysInMonth[i])
{
month = i;
day = dayNumber;
break;
}
dayNumber -= daysInMonth[i];
}
String suffix;
if (day >= 11 && day <= 13) {
suffix = "TH";
} else if (day % 10 == 1) {
suffix = "ST";
} else if (day % 10 == 2) {
suffix = "ND";
} else if (day % 10 == 3) {
suffix = "RD";
} else {
suffix = "TH";
}
String monthName;
switch (month)
{
case 1:
monthName = "JANUARY";
break;
case 2:
monthName = "FEBRUARY";
break;
case 3:
monthName = "MARCH";
break;
case 4:
monthName = "APRIL";
break;
case 5:
monthName = "MAY";
break;
case 6:
monthName = "JUNE";
break;
case 7:
monthName = "JULY";
break;
case 8:
monthName = "AUGUST";
break;
case 9:
monthName = "SEPTEMBER";
break;
case 10:
monthName = "OCTOBER";
break;
case 11:
monthName = "NOVEMBER";
break;
case 12:
monthName = "DECEMBER";
break;
default:
monthName = "";
}
return day + suffix + " " + monthName + ", " + year;
}
public static String FutureDate(int dayNumber, int year, int n)
{
int totalDays = dayNumber + n;
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))


{
daysInMonth[2] = 29; // Leap year
}
while (totalDays > 366)
{
// Adjust for leap year
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
totalDays -= 366;
year++;
} else {
totalDays -= 365;
year++;
}
}
int month = 0;
int day = 0;
for (int i = 1; i <= 12; i++)
{
if (totalDays <= daysInMonth[i])
{
month = i;
day = totalDays;
break;
}
totalDays -= daysInMonth[i];
}

String suffix;
if (day >= 11 && day <= 13) {
suffix = "TH";
} else if (day % 10 == 1) {
suffix = "ST";
} else if (day % 10 == 2) {
suffix = "ND";
} else if (day % 10 == 3) {
suffix = "RD";
} else {
suffix = "TH";
}

String monthName;
switch (month) {
case 1:
monthName = "JANUARY";
break;
case 2:
monthName = "FEBRUARY";
break;
case 3:
monthName = "MARCH";
break;
case 4:
monthName = "APRIL";
break;
case 5:
monthName = "MAY";
break;
case 6:
monthName = "JUNE";
break;
case 7:
monthName = "JULY";
break;
case 8:
monthName = "AUGUST";
break;
case 9:
monthName = "SEPTEMBER";
break;
case 10:
monthName = "OCTOBER";
break;
case 11:
monthName = "NOVEMBER";
break;
case 12:
monthName = "DECEMBER";
break;
default:
monthName = "";
}
return day + suffix + " " + monthName + ", " + year;
}
public static void main(String[] args)
{
DateGenerator defaultDate = new DateGenerator(); // Using the default
constructor
int customDayNumber = 150;
int customYear = 2023;
int customN = 30;

DateGenerator customDate = new DateGenerator(customDayNumber,


customYear, customN); // Using the parameterized constructor
}
}
OUTPUT:

EXAMPLE 1:

EXAMPLE 2:
EXAMPLE 3:

EXAMPLE 4:
Question 6
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
: a) Sort the elements of the single-dimensional array in ascending order using any standard sorting
technique and display the sorted elements.
b) 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: 1 2 5 8 1 2 5 1 1 2 1 2 1 1 2 5
c) Display the filled matrix in the above format.
Test your program for the following data and some random data:
Example 1: INPUT: N = 3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT: SORTED ARRAY: 1 3 7
FILLED MATRIX
137
131
113
Example 2: INPUT: N = 13
OUTPUT: MATRIX SIZE OUT OF RANGE

ALGORITHM:

STEP 1 :Start the program.


STEP 2: Create a Scanner object to read input from the user.
STEP 3:Prompt the user to input the value of N (between 3 and 9) for the matrix size.
Validate the input to ensure it is within the valid range (between 3 and 9). If the input is invalid,
display an error message and ask the user to input again.
STEP 4: Create an integer array 'arr' of size N to store the elements of the single-dimensional array.
STEP 5: Prompt the user to enter N elements for the single-dimensional array and store them in the
'arr' array. Validate each input to ensure it is an integer.
STEP 6: Display the input array 'arr' to the user.
STEP 7: Sort the array 'arr' in ascending order using a sorting algorithm
STEP 8: Display the sorted array 'arr' to the user.
STEP 9: Create a 2D array 'matrix' of size N x N to store the elements of the matrix.
STEP 10: Fill the matrix using the sorted array 'arr':
STEP 11: For each row i from 0 to N-1: For each column j from 0 to N-1:
VARIABLE DESCRIPTION TABLE:

Variable
Name Type Description

matrix 2D array Represents the square matrix that will store the elements.

m int Represents the number of rows in the matrix.

n int Represents the number of columns in the matrix.

Loop variable used for iterating over rows and columns of the matrix
i int and arrays.

temp int Temporary variable used for swapping elements during array rotation.

scanner Scanner Used for user input from the console.

Size of the matrix, input by the user and used for matrix and array
N int dimensions.

arr int[] Array to store user input of single-dimensional array elements.

obj MatrixTasks Object of the MatrixTasks class to perform matrix-related tasks.

SOURCE CODE:

import java.util.*;
import java.util.Scanner;

public class MatrixTasks


{
int matrix[][];
int m;
int n;

MatrixTasks(int a, int b)
{
this.m = a;
this.n = b;
matrix = new int[m][n];
}

// Function to sort the elements of an integer array in ascending order


public static void sortArray(int[] arr)
{
Arrays.sort(arr);
}

// Function to fill the elements of a square matrix with the elements of an array
public void fillMatrix(int[] arr)
{
int len = arr.length;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
matrix[i][j] = arr[j];
}
int temp = arr[0];
for (int j = 0; j < len - 1; j++)
{
arr[j] = arr[j + 1];
}
arr[len - 1] = temp;
}
}

// Function to display the contents of a square matrix


public void displayMatrix()
{
for (int[] row : matrix)
{
for (int num : row)
{
System.out.print(num + " ");
}
System.out.println();
}
}

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);
int N;

// Prompt the user to input the value of N (matrix size) and validate it
do {
System.out.print("Enter the value of N (between 3 and 9): ");
N = scanner.nextInt();
if (N <= 2 || N >= 10)
{
System.out.println("MATRIX OUT OF RANGE");
}
}
while (N <= 2 || N >= 10);

// Create an array to store N elements input by the user


int[] arr = new int[N];
System.out.print("Enter " + N + " elements of the single-dimensional array: ");
for (int i = 0; i < N; i++)
{
arr[i] = scanner.nextInt();
}

System.out.println("Input array: " + Arrays.toString(arr));

// a) Sort the array


sortArray(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));

// Create a matrix object


MatrixTasks obj = new MatrixTasks(N, N);

// b) Fill the elements of the square matrix using the sorted array
obj.fillMatrix(arr);

// c) Display the filled matrix


System.out.println("Filled matrix:");
obj.displayMatrix();

scanner.close();
}
}
OUTPUT:

EXAMPLE 1:

EXAMPLE 2:
EXAMPLE 3:
Question 7
A Goldbach number is a positive even integer that can be expressed as the sum of two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example: 6 = 3 + 3 10 = 3 + 7 10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3.
Similarly, 10 has two odd prime pairs, i.e. 3, 7 and 5, 5.
Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all the odd prime pairs
whose sum is equal to the number ‘N’.
Test your program with the following data and some random data:
Example 1: INPUT: N = 14
OUTPUT:
Prime pairs are: 3, 11 7, 7
Example 2: INPUT: N = 30
OUTPUT:
Prime numbers are: 7, 23 11, 19 13, 17
Example 3: INPUT: N = 17
OUTPUT: Invalid input. Number is odd.
Example 4: INPUT: N = 126
OUTPUT: Invalid input. Number is out of range.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Define a function isPrime(num) that takes an integer num as input and returns a boolean
value indicating whether the number is prime or not.
-Within the isPrime function:
STEP 3:
a. Check if the input num is less than or equal to 1. If yes, return false since prime numbers are
greater than 1.
b. Use a for loop to check for divisors of num from 2 to the square root of num.
c. If num is divisible by any integer between 2 and the square root of num, return false, as it's not a
prime number.
d. If no divisor is found, return true, indicating that num is a prime number.
STEP 4: Define a function findGoldbachPairs(N) that takes an integer N as input and finds the
Goldbach pairs for the given even number.
-Within the findGoldbachPairs function:
STEP 5:
a. Check if N is odd (i.e., not even). If yes, print "Invalid input. Number is odd." and return.
b. Check if N is less than 10 or greater than 48. If yes, print "Invalid input. Number is out of range."
and return.
c. Initialize a boolean variable foundPair as false. This variable will be used to check if any
Goldbach pair is found.
d. Print "Prime pairs are:" to indicate the list of Goldbach pairs.
e. Use a for loop to iterate from 3 to N / 2 with a step of 2, as the pairs should consist of odd prime
numbers and (N - odd prime) is also odd.
f. Inside the loop, check if both i and (N - i) are prime numbers using the isPrime function.
g. If both i and (N - i) are prime, print the pair (i, N - i) as a Goldbach pair.
h. Set foundPair to true if at least one Goldbach pair is found.
i. After the loop, if no Goldbach pair is found (i.e., foundPair is false), print "No prime pairs found."
STEP 6:
In the main function:
a. Create a Scanner object to read input from the user.
b. Prompt the user to enter an even integer between 10 and 48 (inclusive).
c. Read the input integer N.
d. Call the findGoldbachPairs(N) function to find and display the Goldbach pairs for the given N.
e. Close the scanner.
STEP 7: End the program.

VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

num int Used in the isPrime function to check if a number is prime.

i int Used in the isPrime function and findGoldbachPairs loop.

N int The even integer entered by the user to find Goldbach pairs.

foundPair boolean Indicates if at least one Goldbach pair is found.


VARIABLE DESCRIPTION TABLE:

scanner Scanner Used for user input from the user..

SOURCE CODE:

import java.util.Scanner;

public class Goldbach_Num


{
// Parameterized constructor
public Goldbach_Num(int N)
{
findGoldbachPairs(N);
}

// Function to check if a number is prime


public static boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}

// Function to find and display Goldbach pairs


public static void findGoldbachPairs(int N)
{
if (N % 2 != 0)
{
System.out.println("Invalid input. Number is odd.");
return;
}

if (N < 10 || N > 48)


{
System.out.println("Invalid input. Number is out of range.");
return;
}

boolean foundPair = false;


System.out.println("Prime pairs are:");
// Iterate through all possible values from 3 to N/2
// We increment by 2 to consider only odd numbers as even + odd = odd
for (int i = 3; i <= N / 2; i += 2)
{
if (isPrime(i) && isPrime(N - i))
{
// If both i and (N-i) are prime, we found a Goldbach pair
foundPair = true;
System.out.println(i + ", " + (N - i));
}
}

if (!foundPair)
{
System.out.println("No prime pairs found.");
}
}

// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an even integer (10 to 48): ");
int N = scanner.nextInt();

// Using the parameterized constructor to find and display Goldbach pairs


Goldbach_Num goldbach = new Goldbach_Num(N);

scanner.close();
}
}
OUTPUT:

EXAMPLE 1:

EXAMPLE 2:
EXAMPLE 3:

EXAMPLE 4:
Question 8
The names of the teams participating in a competition should be displayed on a banner
vertically, to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display them in
vertical order, side by side with a horizontal tab (i.e. eight spaces).

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

ALGORITHM:
1. Start the program.
STEP 1:
2. Initialize a Scanner object for input (inputScanner).
STEP 2:
3. Print "Enter the number of teams (between 2 and 9): ".
Read and store the number of teams as numTeams.
4. If numTeams is less than or equal to 2 or greater than or equal to 9, then
4.1 Print "Invalid input."
4.2 Exit.
5. Consume the newline character from the previous input.
6. Initialize an array teamNames of size numTeams to store team names.
7. Repeat for i = 0 to numTeams - 1:
7.1 Print "Team " + (i + 1) + ": ".
7.2 Read a line of input and store it in teamNames[i].
8. Initialize maxLength to 0.
9. For each teamName in teamNames:
9.1 If the length of teamName is greater than maxLength, update maxLength.
10. For row = 0 to maxLength - 1:
10.1 For each teamName in teamNames:
10.1.1 If row is less than the length of teamName, print the character at
position 'row' in teamName followed by a tab
10.1.2 Else, print a tab.
10.2 Print a newline.
11. Close the input scanner (inputScanner).
12. End the program.

VARIABLE DESCRIPTION TABLE :

Data
Variable Type Description

inputScanner Scanner A Scanner object to read input from the console.

numTeams int An integer to store the number of teams entered by the user.

teamNames String[] An array of strings to store the names of the teams.

i int A loop variable used to iterate through team names.


VARIAVLE DESCRIPTION TABLE:
An integer to store the maximum length of a team name among all
maxLength int team names.

row int A loop variable used to iterate through rows when printing the banner.

SOURCE CODE:
import java.util.Scanner;
public class TeamVerticalBanner {
private String[] teamNames;
public Scanner scanner; // Scanner object for user input
// Default constructor
public TeamVerticalBanner()
{
scanner = new Scanner(System.in);
}

// Parameterized constructor
public TeamVerticalBanner(int numTeams)
{
teamNames = new String[numTeams];
}
public void inputTeamNames(Scanner scanner)
{
scanner.nextLine(); // Consume newline
for (int i = 0; i < teamNames.length; i++)
{
System.out.print("Team " + (i + 1) + ": ");
teamNames[i] = scanner.nextLine();
}
}
public void displayVerticalBanner(){
int maxLength = 0;
for (String teamName : teamNames)
{
if (teamName.length() > maxLength)
{
maxLength = teamName.length();
}
}
for (int row = 0; row < maxLength; row++) {
for (String teamName : teamNames)
{
if (row < teamName.length())
{
System.out.print(teamName.charAt(row) + "\t");
} else
{
System.out.print("\t");
}}
System.out.println();
}
}
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
// Input the number of teams
System.out.print("Enter the number of teams (between 2 and 9): ");
int numTeams = inputScanner.nextInt();
if (numTeams <= 2 || numTeams >= 9)
{
System.out.println("Invalid input.");
} else
{ // Using the parameterized constructor
TeamVerticalBanner banner = new TeamVerticalBanner(numTeams);
// Input team names
banner.inputTeamNames(inputScanner);
// Display the vertical banner
banner.displayVerticalBanner();
TeamVerticalBanner obj = new TeamVerticalBanner();
obj.inputTeamNames(inputScanner);
obj.displayVerticalBanner();
}
// Close the input scanner
inputScanner.close();
}
}
}
OUTPUT:
Question 9
A company manufactures packing cartons in four sizes, i.e. cartons to accomodate 6 boxes,
12 boxes, 24 boxes and 48 boxes. Design a program to accept the number of boxes to be
packed (N) by the user (maximum up to 1000 boxes) and display the break up of the cartons
used in descending order of capacity (i.e. preference should be given to the highest capacity
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
Example 2: INPUT: N = 140
OUTPUT: 48 * 2 = 96
24 * 1 = 24
12 * 1 = 12
6*1=6
Remaining boxes = 2 * 1 = 2
Total number of boxes = 140
Total number of cartons = 6
Example 3: INPUT: N = 4296
OUTPUT: INVALID INPUT
ALGORITHM:
STEP 1: START THE PROGRAM
STEP 2: Create a new Scanner object to read input from the user.
STEP 3: Ask the user to enter the number of boxes to be packed (N).
STEP 4: Check if the input is valid (between 1 and 1000 inclusive). If not,
print"INVALID INPUT" and terminate the program.
STEP 5: Initialize an array of carton sizes: {48, 24, 12, 6}.
STEP 6: Create an array to store the count of each carton size (cartonCount) and
initialize all counts to 0.
STEP 7: Initialize a variable (remainingBoxes) to keep track of the number of
boxes that still need to be packed and set it to N initially.
STEP 8: Initialize a variable (totalCartons) to keep track of the total number of
cartons used and set it to 0 initially.
STEP 9: Use a loop to iterate through each carton size and pack the boxes in the
available cartons.
STEP 10: For each carton size, check if the remainingBoxes are greater than or
equal to the current carton size.
STEP 11: If yes, calculate how many cartons of that size can be used and update
the cartonCount and remainingBoxes accordingly.
STEP 12: Print the output of the packing process, showing the number of each
carton size used and their total capacity.
STEP 13: If there are any remainingBoxes after using all available cartons, pack
the remaining boxes in an additional carton of size 6.
STEP 14: Print the total number of boxes and the total number of cartons used.
STEP 15: Close the Scanner object.
STEP 16: END OF THE PROGRAM
VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

N int Stores the number of boxes to be packed.


sc Scanner Scanner object used to read input from the console.
cartonSizes int[] Array containing available carton sizes for packing.

cartonCount int[] Array to store the count of each carton size used.
remainingBoxes int Stores the number of boxes that are yet to be packed.

totalCartons int Stores the total number of cartons used for packing.

SOURCE CODE:
import java.util.Scanner;

public class PackingCartons


{
int N;
private Scanner sc;
// Default constructor
public PackingCartons()
{
sc= new Scanner(System.in);
}
// Parameterized constructor
public PackingCartons(int numBoxes)
{
this.N = numBoxes;
}
public void packBoxes()
{
// Array of carton sizes available for packing
int[] cartonSizes = {48, 24, 12, 6};
int[] cartonCount = new int[4];
int remainingBoxes = N;
int totalCartons = 0;
for (int i = 0; i < cartonSizes.length; i++)
{
if (remainingBoxes >= cartonSizes[i])
{
cartonCount[i] = remainingBoxes / cartonSizes[i];
remainingBoxes %= cartonSizes[i];
} }
System.out.println("OUTPUT:");
for (int i = 0; i < cartonSizes.length; i++)
{
if (cartonCount[i] > 0)
{
System.out.println(cartonSizes[i] + " * " + cartonCount[i] + " = " +
(cartonSizes[i] * cartonCount[i]));
totalCartons += cartonCount[i];
}
}

if (remainingBoxes == 0)
{
System.out.println("Remaining boxes = 0");
}
if (remainingBoxes > 0)
{
System.out.println("Remaining boxes = " + remainingBoxes + " * 1 = "
+ remainingBoxes);
totalCartons++;
}
System.out.println("Total number of boxes = " + N);
System.out.println("Total number of cartons = " + totalCartons);
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of boxes to be packed (maximum up to
1000 boxes): ");
int N = input.nextInt();

if (N <= 0 || N > 1000)


{
System.out.println("INVALID INPUT");
input.close();
return;
}
// Using the parameterized constructor
PackingCartons packer = new PackingCartons(N);
packer.packBoxes();
input.close();
}
}
OUTPUT:
Question 10
The result of a quiz competition is to be prepared as follows: The quiz has five questions with
four multiple choices (A, B, C, D), with each question carrying 1 mark for the correct answer.
Design a program to accept the number of participants N such that N must be greater than 3
and less than 11. Create a double- dimensional array of size (N * 5) to store the answers of
each participant row-wise. Calculate the marks for each participant by matching the correct
answer stored in a single-dimensional array of size 5.Display the scores for each participant
and also the participants(s) having the highest score. Example: If the value of N = 4, then the
array would be:
Test your program for the following data and some random data.
Example 1: INPUT: N = 5
Participant 1 D A B C C
Participant 2 A A D C B
Participant 3 B A C D B
Participant 4 D A D C B
Participant 5 B C A D D
Key: B C D A A
OUTPUT: Scores: Participant 1 = 0
Participant 2 = 1
Participant 3 = 1
Participant 4 = 1
Participant 5 = 2
Highest Score: Participant 5
Example 2: INPUT: N = 4
Participant 1 A C C B D
Participant 2 B C A A C
Participant 3 B C B A A
Participant 4 C C D D B
Key: A C D B B
OUTPUT: Scores:
Participant 1 = 3 Participant 2 = 1 Participant 3 = 1 Participant 4 = 3
Highest score: Participant 1 Participant 4
Example 3: INPUT: N = 12 OUTPUT: INPUT SIZE OUT OF RANGE.
ALGORITHM:

STEP 1: START THE PROGRAM


STEP 2: Define a public class named "QuizCompetition".
STEP 3: Define the main method as "public static void main(String[] args)".
STEP 4: Create a Scanner object to read input from the user.
STEP 5: Prompt the user to enter the number of participants (N) in the quiz competition.
STEP 6: Use a do-while loop to validate that N is within the range of 3 to 10 (inclusive). If N
is not within this range, display "OUT OF RANGE" and prompt the user again.
STEP 7: Initialize variables "numQuestions" to 5, "participantsAnswers" as a 2D array to
store participants' answers, and "correctAnswers" as a 1D array to store correct answers.
STEP 8: Use nested loops to collect answers from each participant for each question and store
them in "participantsAnswers" array. Validate each answer to be one of the choices (A, B, C,
or D) using regular expressions.
STEP 9: Prompt the user to enter the correct answers for each question and store them in the
"correctAnswers" array. Validate each correct answer to be one of the choices (A, B, C, or D)
using regular expressions.
STEP 10: Call the "calculateScore" method, passing "participantsAnswers" and
"correctAnswers" arrays, to calculate the scores for each participant.
STEP 11: Call the "displayScores" method, passing the "scores" array, to display the scores
for each participant.
STEP 12: Call the "getHighestScorers" method, passing the "scores" array, to find the
index(es) of the participant(s) with the highest score.
STEP 13: Call the "displayHighestScorers" method, passing the "highestScorers" and
"scores" arrays, to display the participant(s) with the highest score along with their score.
STEP 14: Close the Scanner object to release resources.
STEP 15: END OF THE PROGRAM.
VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

input Scanner A Scanner object to read input from the user.

Represents the number of participants in the


N int quiz competition.

Represents the number of questions in the


numQuestions int quiz competition.

A 2D array to store participants' answers. The


first dimension represents each participant,
and the second represents each question's
participantsAnswers String[][] answer.

A 1D array to store the correct answers for


correctAnswers String[] each question.

i, j int Loop control variables used in for-loops.

An array to store the scores for each


scores int[] participant.

Stores the maximum score found during


maxScore int calculation.

Stores the number of participants with the


numOfMaxScorers int highest score.

An array to store the indices of participants


highestScorers int[] with the highest score.
SOURCE CODE:
import java.util.Scanner;

public class QuizCompetition {


int N;
Scanner input;

// Default constructor
public QuizCompetition()
{
input = new Scanner(System.in);
}

// Parameterized constructoR
public QuizCompetition(int participants)
{
N = participants;
input = new Scanner(System.in);
}

// Method to run the quiz competition


public void runQuizCompetition()
{
do {
System.out.print("Enter the number of participants (N > 3 and N < 11): ");
N = input.nextInt();
if (N > 10 || N < 3)
{
System.out.println("Invalid input. Please enter a number between 3 and 10
(inclusive).");
}
} while (N < 3 || N > 10);

int numQuestions = 5;
String[][] participantsAnswers = new String[N][numQuestions];
String[] correctAnswers = new String[numQuestions];

collectParticipantsAnswers(participantsAnswers, numQuestions);
collectCorrectAnswers(correctAnswers, numQuestions);

int[] scores = calculateScore(participantsAnswers, correctAnswers);


displayScores(scores);

int[] highestScorers = getHighestScorers(scores);


displayHighestScorers(highestScorers, scores);

input.close();
}

// Method to collect participants' answers


public void collectParticipantsAnswers(String[][] participantsAnswers, int numQuestions) {
for (int i = 0; i < N; i++)
{
System.out.println("Enter answers for Participant " + (i + 1) +
" (one answer per line, choices: A, B, C, D):");
for (int j = 0; j < numQuestions; j++)
{
participantsAnswers[i][j] = validateAnswerFormat();
}
}
}

// Method to collect correct answers


public void collectCorrectAnswers(String[] correctAnswers, int numQuestions) {
System.out.println("Enter the correct answers (one answer per line, choices: A, B, C,
D):");
for (int i = 0; i < numQuestions; i++)
{
correctAnswers[i] = validateAnswerFormat();
}
}

// Method to validate answer format


public String validateAnswerFormat()
{
String answer;
do {
answer = input.next().toUpperCase();
if (!answer.matches("[ABCD]"))
{
System.out.println("Invalid choice. Please enter A, B, C, or D.");
}
} while (!answer.matches("[ABCD]"));
return answer;
}

// Method to calculate the scores for each participant


public int[] calculateScore(String[][] participantsAnswers, String[] correctAnswers) {
// Initialize an array to store the scores for each participant
int[] scores = new int[participantsAnswers.length];

// Loop through each participant's answers and compare with the correct answers
for (int i = 0; i < participantsAnswers.length; i++) {
for (int j = 0; j < correctAnswers.length; j++) {
if (participantsAnswers[i][j].equals(correctAnswers[j])) {
// If the participant's answer matches the correct answer, increment their score
scores[i]++;
}
}
}
return scores;
}

// Method to display the scores for each participant


public static void displayScores(int[] scores)
{
System.out.println("\nScores for each participant:");
for (int i = 0; i < scores.length; i++)
{
// Display the participant number and their respective score
System.out.printf("Participant %d: %d%n", i + 1, scores[i]);
}
}

// Method to find the participant(s) with the highest score


public static int[] getHighestScorers(int[] scores)
{
// Initialize variables to find the highest score and the number of participants with the
highest score
int maxScore = Integer.MIN_VALUE;
int numOfMaxScorers = 0;

// Loop through all scores to find the highest score and count the number of
participants with that score
for (int score : scores)
{
if (score > maxScore)
{
maxScore = score;
numOfMaxScorers = 1;
} else if (score == maxScore)
{
numOfMaxScorers++;
}
}
// Initialize an array to store the index(es) of the highest scorer(s)
int[] highestScorers = new int[numOfMaxScorers];
int index = 0;

// Loop through the scores array again to find the index(es) of the highest scorer(s)
for (int i = 0; i < scores.length; i++)
{
if (scores[i] == maxScore)
{
highestScorers[index++] = i + 1; // Add 1 to convert from 0-based index to
participant number
}
}

// Return the array containing the index(es) of the highest scorer(s)


return highestScorers;
}

// Method to display the participant(s) with the highest score


public static void displayHighestScorers(int[] highestScorers, int[] scores) {
// Find the highest score from the scores array using the first highestScorers element
int maxScore = scores[highestScorers[0] - 1];
System.out.println("\nParticipant(s) with the highest score:");
for (int scorer : highestScorers)
{
// Display the participant number and the highest score
System.out.println("Participant " + scorer + " with a score of " + maxScore + ".");
}
}

public static void main(String[] args) {


// Using the default constructor
QuizCompetition competitionDefault = new QuizCompetition();
competitionDefault.runQuizCompetition();

// Using the parameterized constructor


Scanner sc = new Scanner(System.in);
int numParticipants = sc.nextInt();
QuizCompetition competitionParam = new QuizCompetition(numParticipants);
competitionParam.runQuizCompetition();

sc.close();
}
}
OUTPUT:
EXAMPLE 2
EXAMPLE 3:
EXAMPLE 4:
Question 11
Caesar Cipher is an encryption technique which is implemented as ROT13 (‘rotate by 13
places’).
It is a simple letter substitution cipher that replaces a letter with the letter 13 places after it in
the alphabets, with the other characters remaining unchanged.
ROT13
A/a B/b C/c D/d E/e F/f G/g H/h I/I J/j K/k L/l M/m
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/w X/x Y/y Z/z
Write a program to accept a plain text of length L, where L must be greater than 3 and less
than 100. Encrypt the text if valid as per the Caesar Cipher.
Test your program with the sample data and some random data.
Example 1: INPUT: Hello! How are you?
OUTPUT: The cipher text is: Uryyb! Ubj ner lbh?
Example 2: INPUT: Encryption helps to secure data.
OUTPUT: The cipher text is: Rapelcgvba urycf gb frpher qngn.
Example 3: INPUT: You
OUTPUT: INVALID LENGTH

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a new Scanner object to read input from the user.
STEP 3: Prompt the user to enter a plain text (L > 3 and L < 100).
STEP 4: Read the plain text input from the user.
STEP 5: Get the length of the plain text (L).
STEP 6: Check if the length (L) of the plain text is within the range of 4 to 100 (inclusive).
STEP 7: If the length is not within the valid range, display "INVALID LENGTH", close the
Scanner object, and terminate the program.
STEP 8: Call the "encrypt" method, passing the plain text as an argument, to get the cipher
text.
STEP 9: Print "The cipher text is:"
STEP 10: Print the cipher text obtained from the "encrypt" method.
STEP 11: Close the Scanner object to release resources.
STEP 12: End of the program.

VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

input Scanner A Scanner object to read input from the user.

plainText String Stores the plain text input by the user.

L int Stores the length of the plain text.

Stores the encrypted cipher text after using the Caesar


cipherText String cipher.

ch char Represents the current character during encryption.

base char Holds the base character ('A' or 'a') depending on case.

encryptedChar char Holds the encrypted character after applying Caesar cipher.

cipherChars char[] Array to store the encrypted characters of the plain text.

i int Loop counter used for iterating through characters.


SOURCE CODE:

import java.util.Scanner;

public class CaesarCipher


{
private String plainText;

// Default constructor
public CaesarCipher()
{
// Initialize with an empty string
plainText = "";
}

// Parameterized constructor
public CaesarCipher(String text)
{
plainText = text;
}

public void runCipher()


{
Scanner input = new Scanner(System.in);
int L = plainText.length();
if (L < 4 || L > 100)
{
System.out.println("INVALID LENGTH");
input.close();
return;
}
String cipherText = encrypt(plainText);
System.out.println("The cipher text is:");
System.out.println(cipherText);
input.close();

public static String encrypt(String plainText)


{
char[] cipherChars = new char[plainText.length()];
for (int i = 0; i < plainText.length(); i++)
{
char ch = plainText.charAt(i);
if (Character.isLetter(ch))
{
char base = Character.isUpperCase(ch) ? 'A' : 'a';
char encryptedChar = (char) ((ch - base + 13) % 26 + base);
cipherChars[i] = encryptedChar;
} else
{
cipherChars[i] = ch;
}
}
return new String(cipherChars);
}

public static void main(String[] args)


{
Scanner input = new Scanner(System.in);

System.out.print("Enter a plain text (L > 3 and L < 100): ");


String plainText = input.nextLine();

// Using the parameterized constructor


CaesarCipher cipher = new CaesarCipher(plainText);
cipher.runCipher();
input.close();
}
}
OUTPUT
EXAMPLE 1:

EXAMPLE 2:
EXAMPLE 3:

EXAMPLE 4
Question 12
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less
than 100. Find the smallest integer that is greater than M and whose digits add up to N. For
example, if M = 100 and N = 11, then the smallest integer greater than 100 whose digits add
up to 11 is 119.
Write a program to accept the numbers M and N from the user and print the smallest required
number whose sum of all its digits is equal to N. Also, print the total number of digits present
in the required number. The program should check for the validity of the inputs and display
an appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1: INPUT: M = 100 N = 11
OUTPUT: The required number = 119
Total number of digits = 3
Example 2: INPUT: M = 1500 N = 25
OUTPUT: The required number = 1699
Total number of digits = 4
Example 3: INPUT: M = 99 N = 11
OUTPUT: INVALID INPUT
Example 4: INPUT: M = 112 N = 130
OUTPUT: INVALID INPUT

ALGORITHM:
STEP 1: Start of the Program
STEP 2: Create a new Scanner object to read user input.
STEP 3: Prompt the user to enter a positive number M between 100 and 10000.
Read the value of M.
STEP 4: Check if M is within the valid range (between 100 and 10000). If not,
print "INVALID INPUT," close the Scanner, and return.
STEP 5: Prompt the user to enter a positive number N (less than 100).
Read the value of N.
STEP 6: Check if N is greater than or equal to 100. If so, print "INVALID
INPUT," close the Scanner, and return.
STEP 7 : Find the Smallest Integer with the Sum of Digits Equal to N

STEP 8: Call the findSmallestInteger method passing M and N as arguments to


find the smallest integer with the sum of digits equal to N.
STEP 9: Call the findSmallest method to find the smallest integer whose sum of
digits equals the targetSum.
STEP 10: Implement the findSmallest method using recursion:
a) Base case: If the sum of digits of the current number is equal to the
targetSum, return the current number.
b) Recursive case: Otherwise, call the findSmallest method with the next
number (num + 1) and the same targetSum.
c)Implement the sumOfDigits method to calculate the sum of digits of a number
using recursion:
STEP 11:
a). Base case: If the number is 0, return 0.
b). Recursive case: Otherwise, return the last digit of the number (num % 10)
plus the sumOfDigits of the remaining digits (num / 10).
c)Implement the countTotalDigits method to count the total number of digits in
a number using recursion:
STEP 12:
a). Base case: If the number is 0, return 1 (indicating the number has 1 digit).
b). Recursive case: Otherwise, return 1 plus the countTotalDigits of the
remaining digits (num / 10).
c)If a valid smallest integer is found (not -1), print the result along with the total
number of digits.
Otherwise, print that no number is found with the sum of digits equal to N.
STEP 13: Close the Scanner to release system resources.
STEP 14: End of the Program

VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

input Scanner A Scanner object used to read input from the user.

M int Stores the positive number entered by the user (between 100 and 10000).

N int Stores the positive number entered by the user (less than 100).

smallestInteger int Stores the smallest integer with the sum of digits equal to N.

totalDigits int Stores the total number of digits in the smallest integer found.
SOURCE CODE:
import java.util.Scanner;

public class SmallestInteger


{
private int M;
private int N;

// Parameterized constructor
public SmallestInteger(int m, int n)
{
M = m;
N = n;
}

public void printSmallestInteger()


{
int smallestInteger = findSmallest(M + 1, N);

if (smallestInteger != -1)
{
System.out.println("The required number = " + smallestInteger);
System.out.println("Total number of digits = " + countTotalDigits(smallestInteger));
} else {
System.out.println("No number found with the sum of digits equal to " + N);
}
}

public int findSmallest(int num, int targetSum)


{
if (sumOfDigits(num) == targetSum)
{
return num;
}
return findSmallest(num + 1, targetSum);
}

public int sumOfDigits(int num)


{
if (num == 0)
{
return 0;
}
return num % 10 + sumOfDigits(num / 10);
}

private int countTotalDigits(int num)


{
if (num == 0)
{
return 0;
}
return 1 + countTotalDigits(num / 10);
}

public static void main(String[] args)


{
Scanner input = new Scanner(System.in);

System.out.print("Enter a positive number M (between 100 and 10000): ");


int M = input.nextInt();
if (M < 100 || M > 10000)
{
System.out.println("INVALID INPUT");
input.close();
return;
}

System.out.print("Enter a positive number N (less than 100): ");


int N = input.nextInt();
if (N >= 100)
{
System.out.println("INVALID INPUT");
input.close();
return;
}

// Using the parameterized constructor


SmallestInteger smallestInteger = new SmallestInteger(M, N);
smallestInteger.printSmallestInteger();

input.close();
}
}
}
OUTPUT:
EXAMPLE 3:

EXAMPLE 4:
Question 13
A composite magic number is a positive integer which is composite as well as a magic
number. Composite number: A composite number is a number that has more than two factors.
For example: 10 Factors are: 1, 2, 5, 10. Magic number: A magic number is a number in
which the eventual sum of the digits is equal to 1.
For example: 28 2 + 8 = 10. 1 + 0 = 1.
Accept two positive integers ‘m’ and ‘n’, where m is less than n as user input. Display the
number of composite magic integers that are in the range between ‘m’ and ‘n’ (both inclusive)
and output them along with the frequency, in the format specified below.
Test your program with the sample data and some random data:
Example 1: INPUT: m = 10 n = 100
OUTPUT: THE COMPOSITE MAGIC INTEGERS ARE: 10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2: INPUT: m = 1200 n = 1300
OUTPUT: THE COMPOSITE MAGIC INTEGERS ARE: 1207, 1216, 1225, 1234, 1243,
1252, 1261, 1270, 1288
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9
Example 3: INPUT: m = 120 n = 99
OUTPUT: INVALID INPUT

ALGORITHM:

STEP 1: Start of the Program


STEP 2: Import the java.util.Scanner class to enable reading input from the user.
STEP 3: Define the CompositeMagicNumbers class and main method as the entry point of
the program.
STEP 4: Create a new Scanner object to read input from the user.
STEP 5: Input and Validation
STEP 6: Prompt the user to enter a positive integer m.
STEP 7: Read the input value m using the Scanner.
STEP 8: Prompt the user to enter a positive integer n.
STEP 9: Read the input value n using the Scanner.
STEP 10: Check if m is greater than or equal to n.
STEP 11: If m is greater than or equal to n, print "Invalid input. M should be less than n,"
close the Scanner, and terminate the program.
STEP 12: Find Composite Magic Integers
STEP 13: Initialize a variable count to 0 to keep track of the number of composite magic
integers found.
STEP 14: Print "THE COMPOSITE MAGIC INTEGERS ARE:" Use a loop starting from m
to n (inclusive) to iterate through the range of numbers.
STEP 15: For each number i in the range, check if it is both a composite number (using the
isComposite method) and a magic number (using the isMagic_Num method).
STEP 16: If i is a composite magic integer, print it and increment the count.
If no composite magic integers are found, print "No composite magic integers found in the
range." Otherwise, print the frequency of composite magic integers found.
STEP 17 : End of the Program.

VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

input Scanner Scanner object to read input from the user.

m int Holds the positive integer input m.

n int Holds the positive integer input n.

Keeps track of the number of composite magic integers


count int found.

Loop variable used to iterate through the range of


i int numbers.

Used in the isComposite and isMagic_Num methods to


num int represent the number being checked.

Used in the isComposite method to represent the current


divisor int divisor when checking if a number is composite.

Used in the isMagic_Num method to calculate the sum of


sum int digits of a number.
SOURCE CODE:
import java.util.Scanner;

public class CompositeMagicNumbers {


private int m;
private int n;

// Default constructor
public CompositeMagicNumbers()
{
m = 0;
n = 0;
}

// Parameterized constructor
public CompositeMagicNumbers(int start, int end)
{
m = start;
n = end;
}

public void CompositeMagic()


{
if (m >= n)
{
System.out.println("Invalid input. M should be less than n.");
return;
}

int count = 0;
System.out.println("THE COMPOSITE MAGIC INTEGERS ARE:");

for (int i = m; i <= n; i++)


{
if (isComposite(i, 2) && isMagicNum(i))
{
System.out.print(i + ", ");
count++;
}
}

if (count == 0)
{
System.out.println("No composite magic integers found in the range.");
} else
{
System.out.println();
System.out.println("FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: " +
count);
}
}

public static boolean isComposite(int num, int divisor) {


if (num < 4) {
return false;
}
if (divisor > Math.sqrt(num)) {
return false;
}
if (num % divisor == 0) {
return true;
}
return isComposite(num, divisor + 1);
}

public static boolean isMagicNum(int num) {


if (num <= 9) {
return num == 1;
}
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return isMagicNum(sum);
}

public static void main(String[] args)


{
Scanner input = new Scanner(System.in);

System.out.print("Enter a positive integer m: ");


int m = input.nextInt();
System.out.print("Enter a positive integer n: ");
int n = input.nextInt();

// Using the parameterized constructor


CompositeMagicNumbers compositeMagicNumbers = new
CompositeMagicNumbers(m, n);
compositeMagicNumbers.CompositeMagic();
input.close();
}
}
OUTPUT:
OUTPUT:
Question 14
A prime palindrome integer is a positive integer (without leading zeroes) which is prime as
well as a palindrome. Given two positive integers m and n, where m < n, write a program to
determine how many prime palindrome integers are there in the range between m and n (both
inclusive) and output them. The input contains two positive integers m and n where m < 3000
and n < 3000. Display the number of prime palindrome integers in the specified range along
with their values in the format specified below:
Test your program with the sample data and some random data:
Example 1:
INPUT: m = 100 n = 1000
OUTPUT: THE PRIME PALINDROME INTEGERS ARE: 101, 131, 151, 181, 191, 313,
353, 373, 383, 727, 757, 787, 919, 929
FREQUENCY OF PRIME PALINDROME INTEGERS: 15
Example 2:
INPUT: m = 100 n = 5000
OUTPUT: OUT OF RANGE.

ALGORITHM:

STEP 1: Start of the Program


Create a new Scanner object to read input from the user.
STEP 2: Prompt the user to enter a positive integer m.
Read the input value for m using the Scanner.
STEP 3: Prompt the user to enter a positive integer n.
Read the input value for n using the Scanner.
STEP 4: Check if m is greater than or equal to n.
If m is greater than or equal to n, print "Invalid input. m should be less than n."
STEP 5: Close the Scanner to release system resources and terminate the
program.
STEP 6: Print "THE PRIME PALINDROME INTEGERS ARE:"
STEP 7: Call the PrimePalindromes method with m and n as arguments to find
and print prime palindrome integers in the range [m, n].
STEP 8: The PrimePalindromes method recursively finds and prints prime
palindrome integers within the given range.
a. If m is greater than n, return 0 (base case).
b. Initialize a count variable to 0.
c. Check if m is both prime and palindrome using the isPrime and isPalindrome
methods.
d. If m is both prime and palindrome, print the prime palindrome integer and
increment the count.
e. Recursively call the PrimePalindromes method with the next number (m + 1)
in the range and add the result to the count.
f. Return the total count of prime palindrome integers found in the range [m, n].
STEP 9: Print the frequency of prime palindrome integers found in the range.
STEP 10: Close the Scanner to release system resources.
STEP 11: End of the Program.

VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

input Scanner Scanner object to read input from the user.

m int Stores the positive integer input m.

n int Stores the positive integer input n.

Keeps track of the number of prime palindrome integers found in


count int the range [m, n].

num int Used in various methods to store a number for processing.

i int Loop variable used in the isPrime method to check for divisibility.

Used in the isPalindrome method to store the original number for


originalNum int comparison.

Used in the isPalindrome method to store the reversed number for


reversedNum int comparison.
SOURCE CODE:
import java.util.Scanner;

public class PrimePalindrome


{
private int m;
private int n;

// Default constructor
public PrimePalindrome()
{
m = 0;
n = 0;
}

// Parameterized constructor
public PrimePalindrome(int start, int end)
{
m = start;
n = end;
}

public void PrimePalindromes()


{
if (m >= n) {
System.out.println("Invalid input. m should be less than n.");
return;
}
System.out.println("THE PRIME PALINDROME INTEGERS ARE:");

int count = findPrimePalindromes(m, n);

System.out.println("\nFREQUENCY OF PRIME PALINDROME INTEGERS: " +


count);
}

public static boolean isPrime(int num) {


if (num < 2) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

public static boolean isPalindrome(int num) {


int originalNum = num;
int reversedNum = 0;
while (num > 0) {
reversedNum = reversedNum * 10 + num % 10;
num /= 10;
}
return originalNum == reversedNum;
}

public static int findPrimePalindromes(int m, int n) {


if (m > n)
{
return 0;
}

int count = 0;
if (isPrime(m) && isPalindrome(m))
{
System.out.print(m + ", ");
count++;
}
count += findPrimePalindromes(m + 1, n);

return count;
}

public static void main(String[] args)


{
Scanner input = new Scanner(System.in);

System.out.print("Enter a positive integer m: ");


int m = input.nextInt();
System.out.print("Enter a positive integer n: ");
int n = input.nextInt();

// Using the parameterized constructor


PrimePalindrome primePalindrome = new PrimePalindrome(m, n);
primePalindrome.PrimePalindromes();
input.close();
}
}
OUTPUT:
Question 15
Write a program to declare a matrix a[][] of order (M × N) where ‘M’ is the number of rows
and ‘N’ is the number of columns such that both M and N must be greater than 2 and less
than 20. Allow the user to input integers into this matrix. Perform the following tasks on the
matrix: 1. Display the input matrix.
2. Find the maximum and minimum value in the matrix and display them along with their
position.
3. Sort the elements of the matrix in ascending order using any standard sorting technique and
rearrange them in the matrix.
4. Output the rearranged matrix.
Test your program with the sample data and some random data.
Example 1: INPUT: M = 3 N = 4
8793
-2 0 4 5
1 3 6 -1
OUTPUT: ORIGINAL MATRIX:
8793
-2 0 4 5
1 3 6 -1
LARGEST NUMBER: 9 ROW = 0 COLUMN = 3
REARRANGED MATRIX:
-4 -2 0 1
3345
6789
Example 2: INPUT: M = 3 N = 22
OUTPUT: SIZE OUT OF RANGE

ALGORITHM:

STEP 1: Start the program.


STEP 2: Create a new Scanner object to read input from the user.
STEP 3: Prompt the user to enter the number of rows (M > 2 and M < 20).
STEP 4: Read the input value for M using the Scanner.
STEP 5: Check if M is within the valid range (M > 2 and M < 20). If not, print "size out of
range!" and repeat STEP 3.
STEP 6: Prompt the user to enter the number of columns (N > 2 and N < 20).
STEP 7: Read the input value for N using the Scanner.
STEP 8: Check if N is within the valid range (N > 2 and N < 20). If not, print "size out of
range!" and repeat STEP 6.
STEP 9: Create a 2D array called matrix with M rows and N columns.
STEP 10: Prompt the user to enter the elements of the matrix and store them in the matrix
array.
STEP 11: Display the original matrix by calling the displayMatrix method.
STEP 12: Find the maximum value in the matrix and its position (row and column) using the
MaxPosition method.
STEP 13: Find the minimum value in the matrix and its position (row and column) using the
MinPosition method.
STEP 14: Display the largest number, its row, and its column.
STEP 15: Sort the elements of the matrix in ascending order using the sortMatrix method.
STEP 16: Display the rearranged matrix by calling the displayMatrix method.
STEP 17: Close the Scanner to release system resources.
STEP 18: End of the program.

VARIABLE DATA TABLE:

Variable Data Type Description

input Scanner A Scanner object to read input from the user.

M int An integer variable to store the number of rows in the matrix.

N int An integer variable to store the number of columns in the matrix.

matrix int[][] A 2D array of integers to store the elements of the matrix.

input Scanner A Scanner object used to read input from the user.

An array of integers to store the row and column position of the


maxPosition int[] maximum value in the matrix.

An array of integers to store the row and column position of the


minPosition int[] minimum value in the matrix.

maxValue int An integer variable to store the maximum value found in the matrix.

minValue int An integer variable to store the minimum value found in the matrix.
Variable Data
Name Type Description

An array used to temporarily store the elements of the matrix


tempArray int[] for sorting.

An integer used to keep track of the current index while


index int copying and rearranging elements.

SOURCE CODE:
import java.util.Scanner;

public class MatrixOperations


{
private int[][] matrix;

// Parameterized constructor
public MatrixOperations(int[][] inputMatrix)
{
matrix = inputMatrix;
}

public static void main(String[] args)


{
Scanner input = new Scanner(System.in);
int M, N;

// Prompt the user to enter the number of rows (M > 2 and M < 20).
// Read the input value for M using the Scanner.
do {
System.out.print("Enter the number of rows (M > 2 and M < 20): ");
M = input.nextInt();

// Check if M is within the valid range (M > 2 and M < 20).


// If not, print "size out of range!" and repeat the input prompt.
if (M <= 2 || M >= 20)
{
System.out.println("size out of range!");
}
} while (M <= 2 || M >= 20);

// Prompt the user to enter the number of columns (N > 2 and N < 20).
// Read the input value for N using the Scanner.
do {
System.out.print("Enter the number of columns (N > 2 and N < 20): ");
N = input.nextInt();

// Check if N is within the valid range (N > 2 and N < 20).


// If not, print "size out of range!" and repeat the input prompt.
if (N <= 2 || N >= 20)
{
System.out.println("size out of range!");
}
} while (N <= 2 || N >= 20);

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

// Input elements into the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = input.nextInt();
}
}

// Task 1: Display the input matrix


System.out.println("\nORIGINAL MATRIX:");
displayMatrix(matrix);

// Task 2: Find the maximum and minimum value in the matrix and display them along
with their position
int[] maxPosition = MaxPosition(matrix);
int[] minPosition = MinPosition(matrix);
int maxValue = matrix[maxPosition[0]][maxPosition[1]];
int minValue = matrix[minPosition[0]][minPosition[1]];
System.out.println("\nLARGEST NUMBER: " + maxValue);
System.out.println("ROW = " + maxPosition[0]);
System.out.println("COLUMN = " + maxPosition[1]);

// Task 3: Sort the elements of the matrix in ascending order using any standard sorting
technique
sortMatrix(matrix);

// Task 4: Output the rearranged matrix


System.out.println("\nREARRANGED MATRIX:");
displayMatrix(matrix);
input.close();
}

// Method to display the matrix


public static void displayMatrix(int[][] matrix)
{
for (int[] row : matrix)
{
for (int num : row)
{
System.out.print(num + " ");
}
System.out.println();
}
}

// Method to find the position of the maximum value in the matrix


public static int[] MaxPosition(int[][] matrix)
{
int max = Integer.MIN_VALUE;
int row = 0;
int col = 0;

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


{
for (int j = 0; j < matrix[0].length; j++)
{
if (matrix[i][j] > max)
{
max = matrix[i][j];
row = i;
col = j;
}
}
}

return new int[]{row, col};


}

// Method to find the position of the minimum value in the matrix


public static int[] MinPosition(int[][] matrix)
{
int min = Integer.MAX_VALUE;
int row = 0;
int col = 0;

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


{
for (int j = 0; j < matrix[0].length; j++)
{
if (matrix[i][j] < min)
{
min = matrix[i][j];
row = i;
col = j;
}
}
}
return new int[]{row, col};
}

// Method to sort the elements of the matrix in ascending order


public static void sortMatrix(int[][] matrix)
{
int[] tempArray = new int[matrix.length * matrix[0].length];
int index = 0;

// Copy all elements of the matrix to a temporary array


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

// Sort the temporary array in ascending order


java.util.Arrays.sort(tempArray);

index = 0;
// Rearrange the sorted elements back into the matrix
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++)
{
matrix[i][j] = tempArray[index++];
}
}
}
}
OUTPUT:
Question 16
Write a program to input a natural number less than 1000 and display it in words.
Test your program for the given sample data and some random data.
INPUT: 29
OUTPUT: TWENTY NINE
INPUT: 17001
OUTPUT: OUT OF RANGE
INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN
INPUT: 500
OUTPUT: FIVE HUNDRED

ALGORITHM:

STEP 1: Start the program.


STEP 2: Read an integer 'number' from the user.
STEP 3: If 'number' is less than 1 or greater than 999, print "OUT OF RANGE" and
end the program.
STEP 4: Define arrays 'units', 'teens', and 'tens' to store the corresponding words for
single-digit, teen, and tens values.
STEP 5: If 'number' is 0, print "ZERO" and end the program.
STEP 6: If 'number' is between 1 and 9 (inclusive), print the word corresponding to
the unit's place and end the program.
STEP 7: If 'number' is between 10 and 19 (inclusive), print the word corresponding to
the teen value and end the program.
STEP 8: If 'number' is between 20 and 99 (inclusive), print the word corresponding to
the tens digit and unit digit (if applicable) and end the program.
STEP 9: If 'number' is between 100 and 999 (inclusive), print the word corresponding
to the hundreds digit, "HUNDRED", and the remaining two digits (if applicable) and
end the program.
STEP 10: End the program.
VARIABLE DESCRIPTION TABLE:

Variable Data Type Description


Stores the input integer that needs to be
number int converted to words.
A Scanner object used to read input from the
scanner Scanner user.
Stores the output of the number-to-words
result String conversion.
An array containing word representations for
units String[] units (0-9).
An array containing word representations for
teens String[] teen values (10-19).
An array containing word representations for
tens String[] tens (20, 30, ..., 90).
tensDigit int Stores the tens digit of the input number.
unitsDigit int Stores the units digit of the input number.
hundredsDigit int Stores the hundreds digit of the input number.
Stores the remaining part of the input number
remainingNumber int after hundreds digit (for numbers >= 100).

SOURCE CODE:
import java.util.Scanner;

public class NumberToWordsConverter


{
private int number;

// Default constructor
public NumberToWordsConverter()
{
number = 0;
}

// Parameterized constructor
public NumberToWordsConverter(int num)
{
number = num;
}

// The main method where the program execution starts


public static void main(String[] args)
{
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("INPUT: ");

// Read the input integer from the user


int number = scanner.nextInt();

// Create an instance of NumberToWordsConverter using the parameterized constructor


NumberToWordsConverter converter = new NumberToWordsConverter(number);

// Call the Num_Words method to convert the number to words


String result = converter.Num_Words();

// Display the output of the conversion


System.out.println("OUTPUT: " + result);
}

// Method to convert the stored number to its word representation


public String Num_Words()
{
// Check if the number is out of range (less than 1 or greater than 999)
if (number < 1 || number > 999)
{
return "OUT OF RANGE";
}

// Arrays to store the word representations for units, teens, and tens
String[] units = {"", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
"EIGHT", "NINE"};
String[] teens = {"TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN",
"FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN", "NINETEEN"};
String[] tens = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY",
"SEVENTY", "EIGHTY", "NINETY"};

// If the number is 0, return "ZERO"


if (number == 0)
{
return "ZERO";
}
// If the number is between 1 and 9 (inclusive), return the word for the unit's place
if (number >= 1 && number <= 9)
{
return units[number];
}
// If the number is between 10 and 19 (inclusive), return the word for the teen value
if (number >= 10 && number <= 19)
{
return teens[number - 10];
}
// If the number is between 20 and 99 (inclusive), return the word for the tens digit and unit
digit (if applicable)
if (number >= 20 && number <= 99)
{
int tensDigit = number / 10;
int unitsDigit = number % 10;
return tens[tensDigit] + (unitsDigit > 0 ? " " + units[unitsDigit] : "");
}

// If the number is between 100 and 999 (inclusive), return the word for the hundreds digit,
"HUNDRED", and the remaining two digits (if applicable)
if (number >= 100 && number <= 999)
{
int hundredsDigit = number / 100;
int remainingNumber = number % 100;
return units[hundredsDigit] + " HUNDRED" + (remainingNumber > 0 ? " AND " + new
NumberToWordsConverter(remainingNumber).Num_Words() : "");
}
// If the number is not within the valid range, return "OUT OF RANGE"
return "OUT OF RANGE";
}
}
OUTPUT:
Question 17
Consider the sequence of natural numbers. 1, 2, 3, 4, 5, 6, 7 ………………………………….
Removing every second number produces the sequences 1, 3, 5, 7, 9, 11, 13, 15,
17………………………….
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 number N < 50.
SAMPLE INPUT : N = 10
OUTPUT : THE LUCKY NUMBERS LESS THAN 10 ARE: 1 3 7.
SAMPLE
INPUT : N = 25
OUTPUT :
THE LUCKY NUMBERS LESS THAN 10 ARE: 1 3 7 13 19

ALGORITHM:
STEP 1: Start the program.
STEP 2: Read an integer 'N' (less than 50) from the user.
STEP 3: Print a message indicating the lucky numbers less than N are going to
be displayed.
STEP 4: Initialize a loop with 'i' starting from 1 and incrementing by 2 (to
consider only odd numbers).
STEP 5: Inside the loop, check if the current 'i' is a lucky number by calling the
method 'isLuckyNumber(i).
a) Base case 1: If 'num' is less than 'step', return true (the number is considered
lucky as it is not divisible by any of its digits).
b) Base case 2: If 'num' is divisible by 'step', return false (the number is not
lucky).
c) Recursive case: Call the method 'isLuckyNumber' with the updated 'num'
and 'step + 1' to continue checking for lucky properties
STEP 6: If the 'i' is a lucky number (the method returns true), print 'i' as a lucky
number.
STEP 7: Continue the loop until 'i' is less than N.
STEP 8: Close the Scanner to release system resources.
STEP 9: End of the program.
VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

input Scanner A Scanner object used to read input from the user.

An instance of the LuckyNumbers class created using the


luckyNumbers LuckyNumbers parameterized constructor.

The user-provided input integer representing the upper limit for


N int finding lucky numbers.

num int The current number being checked for luckiness.

step int The step value used in the luckiness checking algorithm.

A loop counter variable for iterating through odd numbers to find


i int lucky numbers.

SOURCE CODE:
import java.util.Scanner;

public class LuckyNumbers


{
// Parameterized constructor
public LuckyNumbers(int n)
{
LuckyNumber(n);
}

public static void main(String[] args)


{
// Create a Scanner object to read input from the user.
Scanner input = new Scanner(System.in);
// Prompt the user to enter a number N (less than 50).
System.out.print("Enter a number N (less than 50): ");
int N = input.nextInt();

// Create an instance of LuckyNumbers using the parameterized constructor


LuckyNumbers luckyNumbers = new LuckyNumbers(N);

input.close();
}

public static boolean isLuckyNumber(int num)


{
// Call the overloaded isLuckyNumber method with initial step value of 2.
return isLuckyNumber(num, 2);
}

public static boolean isLuckyNumber(int num, int step)


{
// Base case - If the number is less than the current step, it is a lucky number.
if (num < step)
{
return true;
}
// If the number is divisible by the current step, it is not a lucky number.
if (num % step == 0)
{
return false;
}
// Recursively call the isLuckyNumber method with a reduced number and incremented
step.
return isLuckyNumber(num - num / step, step + 1);
}

public static void LuckyNumber(int n)


{
// Display the header for the lucky numbers less than N.
System.out.println("\nTHE LUCKY NUMBERS LESS THAN " + n + " ARE:");
// Iterate through odd numbers from 1 to N (exclusive) to find and print lucky numbers.
for (int i = 1; i < n; i += 2)
{
// Check if the current number (i) is a lucky number using the isLuckyNumber
method.
if (isLuckyNumber(i))
{
// If the current number is a lucky number, print it.
System.out.println(i);
}
}
}
}
OUTPUT:
Question 19
Write a program to declare a square matrix A [ ] [ ]of order N (N < 20). Allow
the user to input positive integers in to this matrix. Perform the following task
on the matrix:
(i) Output the original matrix. (ii) Fins the SADDLE POINT for the matrix such
that is the minimum element for the row to which it belongs and the maximum
element for the column to which it belongs. Saddle point for a given matrix is
always unique. If the matrix has no saddle point, output the message “ NO
SADDLE POINT ”.
Test your program for the following data and some random data :
SAMPLE DATA : INPUT : N = 4
ALGORITHM:
Step 1: Start the program.
Step 2: Create a 2D array "matrix" of size N x N to store the elements of the
matrix.
Step 3: Prompt the user to enter elements for the matrix and read them into the
"matrix" array.
Step 4: Display the entered matrix using the "printMatrix" method.
Step 5: Find saddle points in the matrix using the "SaddlePoint" method.
Step 6: Initialize two arrays "Row" and "Col" of size N to store row and column
indices of saddle points.
Step 7: Initialize a variable "Count" to keep track of the number of saddle points
found (initially set to 0).
Step 8: Loop through each row of the matrix and find the minimum value in that
row and its column index.
Step 9: For each minimum value found in Step 8, check if it is also the
maximum value in its respective column. If yes, it is a saddle point.
Step 10: If a saddle point is found, store its row index in the "Row" array and it
column index in the "Col" array, then increment "Count".
Step 11: If no saddle points are found (Count = 0), print "NO SADDLE
POINT". If saddle points are found (Count > 0), display each saddle point using
the "printMatrix" method.
Step 12: Sort the principal diagonal elements of the matrix using the
"PrincipalDiagonal" method.
Step 13: Create an array "diagonalElements" to store the diagonal elements of
the matrix.
Step 14: Loop through the matrix to extract the diagonal elements and store
them in "diagonalElements" array.
Step 15: Sort the "diagonalElements" array in ascending order.
Step 16: Update the diagonal elements in the "matrix" with the sorted
"diagonalElements" array.
Step 17: Display the matrix after sorting the principal diagonal using the
"printMatrix" method.
Step 18: End of the program.

VARIABLE DESCRIPTION TABLE:

Data
Variable Type Description

scanner Scanner A Scanner object to read user input from the console.

An integer variable to store the size of the square matrix (number of


n int rows/columns).

matrix int[][] A 2D integer array to store the elements of the square matrix.

Row int[] An integer array to store the row indices of saddle points.

Col int[] An integer array to store the column indices of saddle points.

Count int An integer variable to keep track of the number of saddle points found.

An integer variable to store the minimum value in the current row of


minRowValue int the matrix.

An integer variable to store the column index of the minimum value in


colIndex int the current row.

isSaddlePoint boolean A boolean variable to check if a point is a saddle point or not.

i, j, k int Loop control variables used in various for-loops.

An integer array to store the diagonal elements of the matrix for


diagonalElements int[] sorting.

An integer variable used as temporary storage during swapping in the


temp int sorting process.
SOURCE CODE:

import java.util.Scanner;

public class SaddlePoint


{
// Parameterized constructor
public SaddlePoint(int[][] matrix, int n)
{
// Call the SaddlePoint method with the provided matrix and size
SaddlePoint(matrix, n);
}

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);
System.out.print("INPUT : N = ");
int n = scanner.nextInt();
int[][] matrix = new int[n][n];

// Input matrix elements


System.out.println("Enter elements for MATRIX A: ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
matrix[i][j] = scanner.nextInt();
}
}

System.out.println("OUTPUT :");
printMatrix(matrix, n);
// Find and display saddle points
SaddlePoint(matrix, n);

scanner.close();
}

// Print the matrix


public static void printMatrix(int[][] matrix, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

// Find and display saddle points in the matrix


public static void SaddlePoint(int[][] matrix, int n)
{
int[] Row = new int[n];
int[] Col = new int[n];
int Count = 0;

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


{
int minRowValue = matrix[i][0];
int colIndex = 0;

// Find minimum value in the row


for (int j = 1; j < n; j++)
{
if (matrix[i][j] < minRowValue)
{
minRowValue = matrix[i][j];
colIndex = j;
}
}

boolean isSaddlePoint = true;


// Check if the minimum value in the row is maximum in its column
for (int k = 0; k < n; k++)
{
if (matrix[k][colIndex] > minRowValue)
{
isSaddlePoint = false;
break;
}
}

// Store saddle point information


if (isSaddlePoint)
{
Row[Count] = i;
Col[Count] = colIndex;
Count++;
}
}
// Display saddle points or a message if none exist
if (Count == 0)
{
System.out.println("NO SADDLE POINT");
} else
{
for (int i = 0; i < Count; i++)
{
int row = Row[i];
int col = Col[i];
System.out.println("SADDLE POINT = " + matrix[row][col]);
}
}

// Sort and update the principal diagonal elements in the matrix


System.out.println("MATRIX AFTER SORTING THE PRINCIPAL DIAGONAL");
PrincipalDiagonal(matrix, n);
printMatrix(matrix, n);
}

// Sort and update the principal diagonal elements in the matrix


public static void PrincipalDiagonal(int[][] matrix, int n)
{
int[] diagonalElements = new int[n];
for (int i = 0; i < n; i++)
{
diagonalElements[i] = matrix[i][i];
}

// Sort the diagonal elements


for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (diagonalElements[j] < diagonalElements[minIndex])
{
minIndex = j;
}
}

int temp = diagonalElements[i];


diagonalElements[i] = diagonalElements[minIndex];
diagonalElements[minIndex] = temp;
}

// Update the matrix with sorted diagonal elements


for (int i = 0; i < n; i++)
{
matrix[i][i] = diagonalElements[i];
}
}
}
OUTPUT:
Question 20
A simple encryption system uses a shifting process to hide a message. The value of the shift
can be in the range 1 to 26.
For example a shift of 7 means that A = U, B =V, C = W, etc. i e.
Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T
Fist an extra space is added to the end of the string. To make things little more difficult,
spaces within the original text are replaced with QQ before the text is encrypted. Double Q
(QQ) was selected because no English word ends in Q or contains QQ. Additionally the
coded message is printed in blocks of six characters separated by spaces. The last block might
not contain six characters. Write a program that takes the coded text (less than 100
characters), the shift value and prints the decoded original text. Your program must reject any
non-valid value for shift and display an error message “INVALID SHIFT VALUE)”.Assume
all characters are upper case.
Test your program for the following data and some data that you have coded, using the rules
given above:
SAMLE DATA:
INPUT: CODED TEXT : “UHINBY LKKQCH HYLKK”
SHIFT : 7
OUTPUT: DECODED TEXT : ANOTHER VALUE
INPUT:
CODED TEXT : “RUIJGG EVGGBK SAGG”
SHIFT : 11 OUTPUT: DECODED TEST : BEST OF LUCK INPUT:
CODED TEXT : “DKSMMW NAMMUK QMM” SHIFT : 29
OUTPUT: INVALID SHIFT VAULE

ALGORITHM:
STEP 1: Start the program.
STEP 2: Prompt the user to enter the coded text and the shift value.
STEP 3: Read the user input for coded text and shift value.
STEP 4: Check if the shift value is valid (between 1 to 26 inclusive). If not, print "INVALID
SHIFT VALUE" and exit the program.
STEP 5: Call the decodeCodedText method with the provided coded text and shift value.
STEP 6: The decodeCodedText method takes the coded text and shift value as inputs.
STEP 7: In the decodeCodedText method, call the getRawEncoded method with coded text
and shift value.
STEP 8: The getRawEncoded method takes coded text and shift value as inputs and returns
the raw encoded text without spaces.
STEP 9: In the getRawEncoded method, create a new string alphabetsShift that represents the
alphabets shifted according to the given shift value.
STEP 10:Iterate through each character of the coded text, remove spaces, and append the
characters to the sb StringBuilder.
STEP 11: Find the index of the letter 'Q' in the alphabets string.
STEP 12: Get the corresponding character at the found index from the alphabetsShift string
and store it in newIndex.
STEP 13: Create a string space by concatenating the newIndex character twice.
STEP 14: Replace all occurrences of the double space (Q) with a single space character in the
sb StringBuilder using the replace method.
STEP 15: Return the modified sb StringBuilder as a string, which is the raw encoded text
without spaces.
STEP 16: In the decodeCodedText method, iterate through each character of the raw encoded
text.
a)If the character is a space, print a space.
b)Otherwise, find the index of the character in the alphabetsShift string and print the
corresponding character from the original alphabets string.
STEP 17: End the program.

VARIABLE DESCRIPTION TABLE:

Variable Data Type Description

A constant string representing the English alphabets in


alphabets String uppercase (ABCDEFGHIJKLMNOPQRSTUVWXYZ).

codedText String Stores the input coded text provided by the user.
Variable Data Type Description

Stores the shift value provided by the user (between 1 and


shift int 26).

scanner Scanner Used to read input from the user.

Represents the alphabets shifted according to the given


alphabetsShift String shift value.

Used to build the characters of the coded text without


sb StringBuilder spaces.

Represents each word of the coded text obtained after


str String splitting the input by spaces.

index int Stores the index of the letter 'Q' in the alphabets string.

Stores the corresponding character at the found index


newIndex int from the alphabetsShift string.

Represents the 'newIndex' character concatenated twice to


space String represent double spaces (Q).

Represents each character of the raw encoded text during


ch char the decoding process.

Stores the raw encoded text without spaces obtained from


rawEncoded String the getRawEncoded method.
SOURCE CODE:
import java.util.Scanner;

public class DecryptionSystem


{
String codedText;
int shift;
// Parameterized constructor
public DecryptionSystem(String codedText, int shift)
{
this.codedText = codedText;
this.shift = shift;
}

private static String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the coded text: ");
String codedText = scanner.nextLine();
System.out.print("Enter the shift value (1 to 26): ");
int shift = scanner.nextInt();

// Check if the shift value is valid (between 1 and 26 inclusive)


if (shift < 1 || shift > 26)
{
System.out.println("INVALID SHIFT VALUE");
return;
}

// Create an instance of DecryptionSystem using the parameterized constructor


DecryptionSystem obj = new DecryptionSystem(codedText, shift);

// Decode the coded text using the provided shift value


obj.decodeCodedText();

scanner.close();
}

// Method to get the raw encoded text without spaces


public String getRawEncoded()
{
// Create a string 'alphabetsShift' representing the alphabets shifted according to the
given shift value
String alphabetsShift = alphabets.substring(26 - shift + 1) + alphabets.substring(0, 26 -
shift + 1);

// Create a StringBuilder to store the characters of the coded text without spaces
StringBuilder sb = new StringBuilder();
for (String str : codedText.split("\\s"))
sb.append(str);

// Find the index of the letter 'Q' in the alphabets string


int index = alphabets.indexOf('Q');
int newIndex = alphabetsShift.charAt(index);

// Create a string 'space' by concatenating the 'newIndex' character twice (to represent
double spaces)
String space = (char) newIndex + "" + (char) newIndex;
// Replace all occurrences of the double space (Q) with a single space character in the
StringBuilder 'sb'
return sb.toString().replace(space, " ");
}

// Method to decode the coded text using the given shift value
public void decodeCodedText()
{
if (codedText == null)
return;
// Create a string 'alphabetsShift' representing the alphabets shifted according to the
given shift value
String alphabetsShift = alphabets.substring(26 - shift + 1) + alphabets.substring(0, 26 -
shift + 1);
// Get the raw encoded text without spaces using the 'getRawEncoded' method
String rawEncoded = getRawEncoded();

// Iterate through each character of the raw encoded text


for (int i = 0; i < rawEncoded.length(); i++)
{
char ch = rawEncoded.charAt(i);
// If the character is a space, print a space
if (ch == ' ')
System.out.print(" ");
// Otherwise, find the index of the character in 'alphabetsShift' and print the
corresponding character from 'alphabets'
else
System.out.print(alphabets.charAt(alphabetsShift.indexOf(ch)));
}
System.out.println(); // Print a new line after decoding
}
}
OUTPUT:

You might also like