Q 1.
Wap in Java to enter a number and check whether it is a
prime number or not, using recursive function
with method prototype: isPrime(int, int). Write main ()
method as well, to create an object and call all the
required methods.
Program Specification:
Check whether a given number is prime using a recursive
function isPrime(int, int), and display the result.
Algorithm:
1 Start.
2 Input the number from the user.
3 If the number ≤ 1, print “not prime” and stop.
4 Call isPrime(number, number - 1).
5 In isPrime method:
If divisor == 1 → return true (prime).
If number % divisor == 0 → return false (not prime)
Else, recursively call isPrime(number, divisor - 1).
6 Print whether the number is prime or not.
7 End.
import java.util.Scanner;
public class PrimeCheck {
// Recursive method to check if number is prime
public boolean isPrime(int num, int divisor) {
if (divisor == 1) {
return true; // Prime
if (num % divisor == 0) {
return false; // Not prime
return isPrime(num, divisor - 1);
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrimeCheck obj = new PrimeCheck();
System.out.print("Enter a number: ");
int number = sc.nextInt();
if (number <= 1) {
System.out.println(number + " is not a prime number.");
} else {
if (obj.isPrime(number, number - 1)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
sc.close();
Output:
Enter a number: 7
7 is a prime number.
Enter a number: 12
12 is not a prime number.
Variable Listing:
· int number → stores the user-input number.
· Scanner sc → to read input.
· PrimeCheck obj → object to call methods.
· int divisor → recursion counter, starts from number - 1.
Q 2. Wap in Java to display the sum of all the even numbers
up to n, as follows: S = 2 + 4 + 6 + 8 + … up to
n. Use recursive function with method prototype: Sum_rate(int),
for this purpose. Write main () method as
well, to create an object and call all the required methods.
Program Specification:
Write a Java program to calculate and display the sum of all
even numbers up to n using recursion with method prototype
Sum_rate(int).
Algorithm:
1) Start.
2) Input the value of n.
3) In Sum_rate(int num) method:
If num <= 0 → return 0.
If num is even → return num + Sum_rate(num - 2).
If num is odd → call Sum_rate(num - 1) to skip the odd number.
4) Call Sum_rate(n) from main() method.
5) Display the sum.
6) End.
import java.util.Scanner;
public class SumEven {
// Recursive method to sum even numbers
public int Sum_rate(int num) {
if (num <= 0) {
return 0;
}
if (num % 2 == 0) {
return num + Sum_rate(num - 2); // Add even number
and recurse
} else {
return Sum_rate(num - 1); // Skip odd numbers
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SumEven obj = new SumEven();
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
int sum = obj.Sum_rate(n);
System.out.println("Sum of even numbers up to " + n + " is:
" + sum);
sc.close();
}
}
Output:
Enter the value of n: 10
Sum of even numbers up to 10 is: 30
Enter the value of n: 7
Sum of even numbers up to 7 is: 12
Variable Listing:
· int n → stores the limit number.
· Scanner sc → to read input.
· SumEven obj → object to call methods.
Q 3. Wap to perform the following tasks on a text file
“student.txt”.
(I) Input the name, class, section, roll number and percentage
of 50 students in your class. Calculate the
grade as follows:
Percentage
Grade
80 - 100
A
60 - < 80
B
40 - < 60
C
< 40
F
(II) Create the file called “student.txt” and store all these details
of each student in the file in tabular format.
(III) Copy the contents of “student.txt” into another text file
called “result.txt”.
(IV) Read the contents of “result.txt” and display on the screen
in tabular form.
Program Specification:
Write a Java program to:
1) Input details of 50 students: name, class, section, roll
number, percentage.
2 ) Assign grades according to percentage:
80–100 → A
60–<80 → B
40–<60 → C
<40 → F
3) Store all student details in student.txt in tabular form.
4) Copy student.txt into result.txt.
5) Read result.txt and display its contents in tabular format on
the screen.
Algorithm:
1) Start.
2) Open Scanner for input.
3) Loop for 50 students:
Input name, class, section, roll number, percentage.
Calculate grade based on percentage.
Store details in student.txt.
4) Close the file.
5) Open student.txt for reading, and create result.txt for
writing.
6) Copy all lines from student.txt to result.txt.
7) Read result.txt line by line and display in tabular form.
8) End
import java.io.*;
import java.util.Scanner;
public class StudentFileOperations {
// Method to get grade from percentage
public static char getGrade(double percentage) {
if (percentage >= 80) return 'A';
else if (percentage >= 60) return 'B';
else if (percentage >= 40) return 'C';
else return 'F';
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1 & 2: Input student details and write to student.txt
try (BufferedWriter bw = new BufferedWriter(new
FileWriter("student.txt"))) {
bw.write(String.format("%-15s %-6s %-7s %-10s %-12s
%-6s", "Name", "Class", "Section", "Roll No", "Percentage",
"Grade"));
bw.newLine();
bw.write("-------------------------------------------------------------------");
bw.newLine();
for (int i = 1; i <= 50; i++) {
System.out.println("Enter details for Student " + i +
":");
System.out.print("Name: ");
String name = sc.next();
System.out.print("Class: ");
int cls = sc.nextInt();
System.out.print("Section: ");
char section = sc.next().charAt(0);
System.out.print("Roll No: ");
int roll = sc.nextInt();
System.out.print("Percentage: ");
double percentage = sc.nextDouble();
char grade = getGrade(percentage);
bw.write(String.format("%-15s %-6d %-7c %-10d %-
12.2f %-6c", name, cls, section, roll, percentage, grade));
bw.newLine();
}
} catch (IOException e) {
System.out.println("Error writing to student.txt: " +
e.getMessage());
}
// Step 3: Copy student.txt to result.txt
try (BufferedReader br = new BufferedReader(new
FileReader("student.txt"));
BufferedWriter bw = new BufferedWriter(new
FileWriter("result.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
System.out.println("Error copying file: " +
e.getMessage());
}
// Step 4: Read result.txt and display
System.out.println("\nContents of result.txt:");
try (BufferedReader br = new BufferedReader(new
FileReader("result.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading result.txt: " +
e.getMessage());
}
sc.close();
}
}
Output:
Enter details for Student 1:
Name: John
Class: 10
Section: A
Roll No: 101
Percentage: 85
...
Contents of result.txt:
Name Class Section Roll No Percentage Grade
-------------------------------------------------------------------
John 10 A 101 85.00 A
...
Variable Listing:
String name → student’s name
int cls → class
char section → section
int roll → roll number
double percentage → percentage marks
char grade → grade assigned
Scanner sc → for user input
FileWriter, BufferedReader → for file operations
Variable Listing:
int n → stores the limit number.
Scanner sc → to read input.
SumEven obj → object to call methods.
Q 4. Wap in Java to create a function Sum (int) to display sum
of the given series recursively:
Sum = 1 + 8 + 27 + 64 + …+ n.
Write main () method as well, to create an object and call all
the required methods
Program Specification:
Write a Java program to recursively calculate and display the
sum of the series:
Sum=1+8+27+64+⋯+n\text{Sum} = 1 + 8 + 27 + 64 + \dots +
nSum=1+8+27+64+⋯+n
where each term is the cube of natural numbers from 1 to kkk,
and n is the last term’s base (not the cube value).
Use the method prototype Sum(int).
Algorithm:
1) Start.
2) Input the value of n.
In Sum(int num) method:
If num == 1 → return 1 (base case).
Else → return (num^3) + Sum(num - 1).
4) Call Sum(n) from main().
5) Display the sum.
6) End.
import java.util.Scanner;
public class SeriesSum {
// Recursive method to sum cubes
public int Sum(int num) {
if (num == 1) {
return 1;
}
return (num * num * num) + Sum(num - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SeriesSum obj = new SeriesSum();
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
int total = obj.Sum(n);
System.out.println("Sum of the series up to " + n + " is: " +
total);
sc.close();
}
}
Output:
Enter the value of n: 4
Sum of the series up to 4 is: 100
Variable Listing:
int n → the last term’s base number.
Scanner sc → to read user input.
SeriesSum obj → object to call methods.
Q 5. Wap in Java to input employee id, name and basic salary
from the user, of n number of employees.
Store these details of each employee in a binary file
“Employee.dat”.
Read the details of the employees from the file
“Employee.dat”.
Calculate his net pay as follows:
da (Dearness Allowance) = 12% of basic
hra (House Rent Allowance) = 5% of basic
ta (Travel Allowance) = 3% of basic
Medical = ₹ 500.
gp (Gross Pay) = basic + da + hra + ta + Medical.
it (Income Tax) = 10% of basic.
np (Net Pay) = gp – it.
Display the net pay of each employee along with all details on
the screen.
Program Specification:
1) Write a Java program to:
2) Input employee ID, name, and basic salary for n employees.
3) Store details in a binary file Employee.dat.
4) Read the employee details from the file.
Calculate:
da = 12% of basic
hra = 5% of basic
ta = 3% of basic
Medical = ₹500
gp = basic + da + hra + ta + Medical
it = 10% of basic
np = gp - it
5) Display all details along with net pay.
Algorithm:
1) Start.
2) Input n (number of employees).
3) Loop for n employees:
Read employee details.
Write each employee object into Employee.dat (binary file).
4) Close the file.
5) Open Employee.dat for reading.
6) For each employee read from file:
Calculate allowances, GP, IT, NP.
Display details in tabular format.
7) End.
import java.io.*;
import java.util.Scanner;
class Employee implements Serializable {
int empId;
String name;
double basic;
Employee(int empId, String name, double basic) {
this.empId = empId;
this.name = name;
this.basic = basic;
}
}
public class EmployeePay {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1: Write to Employee.dat
try (ObjectOutputStream oos = new
ObjectOutputStream(new FileOutputStream("Employee.dat")))
{
System.out.print("Enter number of employees: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("\nEnter details for Employee " + (i
+ 1) + ":");
System.out.print("Employee ID: ");
int id = sc.nextInt();
sc.nextLine(); // consume newline
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Basic Salary: ");
double basic = sc.nextDouble();
Employee emp = new Employee(id, name, basic);
oos.writeObject(emp);
}
} catch (IOException e) {
System.out.println("Error writing to file: " +
e.getMessage());
}
// Step 2: Read from Employee.dat and calculate pay
System.out.println("\nEMPLOYEE DETAILS WITH NET
PAY");
System.out.printf("%-10s %-15s %-10s %-10s %-10s %-10s
%-10s %-10s %-10s %-10s%n",
"EmpID", "Name", "Basic", "DA", "HRA", "TA",
"Medical", "GP", "IT", "NP");
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("Employee.dat"))) {
while (true) {
try {
Employee emp = (Employee) ois.readObject();
double da = 0.12 * emp.basic;
double hra = 0.05 * emp.basic;
double ta = 0.03 * emp.basic;
double medical = 500;
double gp = emp.basic + da + hra + ta + medical;
double it = 0.10 * emp.basic;
double np = gp - it;
System.out.printf("%-10d %-15s %-10.2f %-10.2f %-
10.2f %-10.2f %-10.2f %-10.2f %-10.2f %-10.2f%n",
emp.empId, emp.name, emp.basic, da, hra, ta,
medical, gp, it, np);
} catch (EOFException e) {
break; // End of file reached
}
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error reading file: " +
e.getMessage());
}
sc.close();
}
}
Output:
Enter number of employees: 2
Enter details for Employee 1:
Employee ID: 101
Name: John
Basic Salary: 20000
Enter details for Employee 2:
Employee ID: 102
Name: Alice
Basic Salary: 30000
EMPLOYEE DETAILS WITH NET PAY
EmpID Name Basic DA HRA TA Medical
GP IT NP
101 John 20000.00 2400.00 1000.00 600.00
500.00 24500.00 2000.00 22500.00
102 Alice 30000.00 3600.00 1500.00 900.00
500.00 36500.00 3000.00 33500.00
Variable Listing:
int empId → employee ID
String name → employee name
double basic → basic salary
double da → Dearness Allowance
double hra → House Rent Allowance
double ta → Travel Allowance
double medical → fixed at ₹500
double gp → Gross Pay
double it → Income Tax
double np → Net Pay
int n → number of employees
Scanner sc → for user input
ObjectOutputStream, ObjectInputStream → for binary file
operations
Program Specification:
Write a Java program to print the given symmetric star (*)
pattern, where the spacing between left and right star groups
increases until the middle row, then decreases symmetrically.
Algorithm:
1) Start.
2) Set n as half the total rows (excluding the middle row).
3) Upper Half:
Loop from i = 0 to n:
Print (n - i + 1) stars on the left.
Print (2 * i) spaces in the middle.
Print (n - i + 1) stars on the right.
4)Lower Half:
Loop from i = n - 1 down to 0:
Repeat the same star–space–star pattern.
5)End.
public class StarPattern {
public static void main(String[] args) {
int n = 4; // controls half height
// Upper half
for (int i = 0; i <= n; i++) {
// Left stars
for (int j = 0; j < n - i + 1; j++) {
System.out.print("* ");
}
// Middle spaces
for (int j = 0; j < i * 2; j++) {
System.out.print(" ");
}
// Right stars
for (int j = 0; j < n - i + 1; j++) {
System.out.print("* ");
}
System.out.println();
}
// Lower half
for (int i = n - 1; i >= 0; i--) {
// Left stars
for (int j = 0; j < n - i + 1; j++) {
System.out.print("* ");
}
// Middle spaces
for (int j = 0; j < i * 2; j++) {
System.out.print(" ");
}
// Right stars
for (int j = 0; j < n - i + 1; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*********
**** ****
*** ***
** **
* *
** **
*** ***
**** ****
*********
Variable Listing
int i, j → loop counters for rows and columns.
int n → number of rows in the top half before the center line.
Q 7. Consider the sequence of natural numbers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25.
Removing every second number produces the sequence:
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25.
Removing every third number produces the sequence:
1, 3, 7, 9, 13, 15, 19, 21, 25.
This process continues indefinitely. The numbers left in the
sequence after this number elimination process
has terminated, are called Lucky Numbers.
Program Specification:
Write a Java program to determine Lucky Numbers from a
given list of natural numbers using the number elimination
process:
1) Start with the sequence of natural numbers.
2) Remove every 2nd number.
3) From the resulting list, remove every 3rd number.
4)Continue this elimination process indefinitely until no
further removal is possible.
5)Display the remaining numbers (Lucky Numbers).
Algorithm:
1)Start.
2)Input the upper limit n.
3)Store numbers from 1 to n in an ArrayList.
4)Set step = 2.
5)While step <= numbers.size():
Remove every step-th number from the list.
Increment step by 1.
6)Print the remaining numbers.
7)End.
import java.util.ArrayList;
import java.util.Scanner;
public class LuckyNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the limit (n): ");
int n = sc.nextInt();
ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= n; i++) {
numbers.add(i);
}
int step = 2;
while (step <= numbers.size()) {
for (int i = step - 1; i < numbers.size(); i += step - 1) {
numbers.remove(i);
}
step++;
}
System.out.println("Lucky Numbers up to " + n + ": " +
numbers);
sc.close();
}
}
Output:
Enter the limit (n): 25
Lucky Numbers up to 25: [1, 3, 7, 9, 13, 15, 19, 21, 25]
Variable Listing:
int n → upper limit of numbers to consider.
ArrayList<Integer> numbers → stores the sequence of
numbers.
int step → elimination step (starts from 2 and increments).
Scanner sc → for user input.
int index → current index to remove during each elimination
step.
Q 8. Wap in Java to find and display all twin prime numbers in
a given range. Also create the main ()
method to create an object of the class and to call the
required methods.
Program Specification:
Write a Java program to find and display all twin prime
numbers in a given range.
Twin primes are pairs of prime numbers that differ by 2 (e.g.,
3 and 5, 11 and 13).
Input the range from the user.
Display each pair in the given range.
Algorithm:
1)Start.
2)Input start and end.
3)Loop from i = start to end - 2:
If i is prime and i + 2 is prime, print (i, i+2).
4)End.
import java.util.Scanner;
public class TwinPrimes {
// Method to check if a number is prime
public 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;
}
// Method to display twin primes in range
public void displayTwinPrimes(int start, int end) {
System.out.println("Twin prime numbers in range " +
start + " to " + end + ":");
for (int i = start; i <= end - 2; i++) {
if (isPrime(i) && isPrime(i + 2)) {
System.out.println("(" + i + ", " + (i + 2) + ")");
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TwinPrimes obj = new TwinPrimes();
System.out.print("Enter the start of the range: ");
int start = sc.nextInt();
System.out.print("Enter the end of the range: ");
int end = sc.nextInt();
obj.displayTwinPrimes(start, end);
sc.close();
}
}
Output:
Enter the start of the range: 1
Enter the end of the range: 20
Twin prime numbers in range 1 to 20:
(3, 5)
(5, 7)
(11, 13)
(17, 19)
Variable Listing:
int start → lower bound of the range.
int end → upper bound of the range.
int i → loop counter for numbers in range.
boolean isPrime → method to check primality.
Scanner sc → for user input.
Q 9. Wap in Java which inputs a positive natural number N and
prints the possible consecutive number
combinations which when added give N.
Program Specification:
Write a Java program to:
Input a positive natural number N.
Find and print all possible consecutive number combinations
whose sum equals N.
For example, if N = 15, possible combinations are:
1+2+3+4+5
4+5+6
7+8
Algorithm:
1)Start.
2)Input N.
3)Loop start from 1 to N/2:
Initialize sum = 0.
Loop i from start upwards, adding i to sum.
If sum == N, print the sequence from start to i.
If sum > N, break the inner loop.
4) End.
import java.util.Scanner;
public class ConsecutiveSum {
// Method to find consecutive sequences that sum to N
public void findSequences(int N) {
System.out.println("Consecutive number combinations for
" + N + ":");
for (int start = 1; start <= N / 2; start++) {
int sum = 0;
StringBuilder sequence = new StringBuilder();
for (int i = start; i < N; i++) {
sum += i;
sequence.append(i).append(" + ");
if (sum == N) {
// Remove trailing " + " and print
System.out.println(sequence.substring(0,
sequence.length() - 3));
break;
}
if (sum > N) {
break;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ConsecutiveSum obj = new ConsecutiveSum();
System.out.print("Enter a positive natural number: ");
int N = sc.nextInt();
obj.findSequences(N);
sc.close();
}
}
Output:
Enter a positive natural number: 15
Consecutive number combinations for 15:
1+2+3+4+5
4+5+6
7+8
Variable Listing:
int N → the input number.
int start → starting number of the sequence.
int sum → to store the sum of current sequence.
int i → iterator for sequence numbers.
Scanner sc → to take user input.
Q 10. Wap in Java to input a number and check whether it is a
Unique Number or NOT.
A Unique Number is a positive integer (without leading zeroes)
with no duplicate digits.
E.g. :
125, 135 etc. are Unique Numbers.
1321, 121 are NOT Unique Numbers.
Also create the main () method to create an object of the class
and to call the required methods
Program Specification:
Write a Java program to:
Input a positive integer from the user.
Check if it is a Unique Number (a number with no repeated
digits).
If it is unique, display "Unique Number".
Otherwise, display "Not a Unique Number".
Algorithm:
1)Start.
2)Input num.
3)Convert num to a string numStr.
4)Create a boolean array digitSeen[10] initialized to false.
5)For each digit in numStr:
Convert to integer digit.
If digitSeen[digit] is already true → number is not unique → exit
loop.
Else set digitSeen[digit] = true.
6)If loop finishes without finding duplicates → number is
unique.
7)Display result.
8)End.
import java.util.Scanner;
public class UniqueNumber {
// Method to check if number is unique
public boolean isUnique(int num) {
String numStr = Integer.toString(num);
boolean[] digitSeen = new boolean[10]; // index 0-9 for
each digit
for (int i = 0; i < numStr.length(); i++) {
int digit = numStr.charAt(i) - '0'; // convert char to int
if (digitSeen[digit]) {
return false; // duplicate found
}
digitSeen[digit] = true;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
UniqueNumber obj = new UniqueNumber();
System.out.print("Enter a positive integer: ");
int num = sc.nextInt();
if (obj.isUnique(num)) {
System.out.println(num + " is a Unique Number.");
} else {
System.out.println(num + " is NOT a Unique Number.");
}
sc.close();
}
}
Output:
Enter a positive integer: 125
125 is a Unique Number.
Variable Listing:
int num → the input number.
String numStr → string representation of the number.
boolean[] digitSeen → array to track if a digit has already
appeared.
boolean isUnique → flag to store the result.
Scanner sc → to take input from the user.
Q11) Wap in Java to check and print Smith Number.
A Smith Number is a composite number, the sum of whose
digits is equal to the sum of the digits of its
prime factors obtained as a result of prime factorisation.
Example: 666
Prime factors are 2, 3, 3, and 37.
Sum of all the digits is (6+6+6) = 18.
Sum of the digits of the factors is (2 + 3 + 3 + (3+7)) = 18.
666 is a Smith Number.
Program Specification:
Write a Java program to:
Input a number from the user.
Check if it is a Smith Number (a composite number whose sum
of digits equals the sum of the digits of its prime factors).
Display whether it is a Smith Number or not.
Compare digitSumNum with digitSumFactors.
1.
2.
If equal → Smith Number; else → Not a Smith Number.
Algorithm:
1)Start.
2)Input num.
3)Check if num is composite (not prime and > 1). If prime
→ not a Smith Number.
4)Find digitSumNum by summing the digits of num.
5)Perform prime factorization of num:
For each prime factor found, add the sum of its digits to
digitSumFactors.
6)Compare digitSumNum with digitSumFactors.
7)If equal → Smith Number; else → Not a Smith Number.
8) End.
import java.util.Scanner;
public class SmithNumber {
// Method to check if a number is prime
public boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
return true;
}
// Method to sum digits of a number
public int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
return sum;
// Method to check Smith Number
public boolean isSmith(int num) {
if (isPrime(num)) {
return false; // Smith numbers are composite
int digitSumNum = sumDigits(num);
int temp = num;
int digitSumFactors = 0;
// Prime factorization
for (int i = 2; i <= temp; i++) {
while (temp % i == 0) {
digitSumFactors += sumDigits(i);
temp /= i;
return digitSumNum == digitSumFactors;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SmithNumber obj = new SmithNumber();
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (obj.isSmith(num)) {
System.out.println(num + " is a Smith Number.");
} else {
System.out.println(num + " is NOT a Smith Number.");
sc.close();
Output:
Enter a number: 666
666 is a Smith Number.
Variable Listing:
int num → user input number.
int temp → temporary copy of num for factorization.
int digitSumNum → sum of digits of the original number.
int digitSumFactors → sum of digits of all prime factors.
Scanner sc → for user input.
Q 12. Wap in Java that reads all the employee names and
basic salaries from the text file “employee.txt.”
Calculate and display net salary of each of them as follows:
DA = 20% of basic
HRA = 8% of basic
Medical = Rs 1000
IT = 8% of basic
Gross salary = basic + DA + HRA + Medical.
Net salary = Gross salary – IT.
Program Specification:
Write a Java program to:
Read employee names and basic salaries from the text file
"employee.txt".
Calculate DA, HRA, Medical, IT, Gross salary, and Net salary
using:
DA = 20% of basic
HRA = 8% of basic
Medical = ₹ 1000
IT = 8% of basic
Gross = basic + DA + HRA + Medical
Net = Gross − IT
Display all details in tabular form.
import java.io.*;
public class EmployeeSalary {
public static void main(String[] args) {
String fileName = "employee.txt";
double medical = 1000.0;
try (BufferedReader br = new BufferedReader(new
FileReader(fileName))) {
System.out.printf("%-20s %-10s %-10s %-10s %-10s
%-10s %-10s %-10s%n",
"Name", "Basic", "DA", "HRA", "Medical",
"Gross", "IT", "Net");
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(",");
String name = parts[0].trim();
double basic =
Double.parseDouble(parts[1].trim());
double da = 0.2 * basic;
double hra = 0.08 * basic;
double gross = basic + da + hra + medical;
double it = 0.08 * basic;
double net = gross - it;
System.out.printf("%-20s %-10.2f %-10.2f %-10.2f
%-10.2f %-10.2f %-10.2f %-10.2f%n",
name, basic, da, hra, medical, gross, it, net);
} catch (IOException e) {
System.out.println("Error reading file: " +
e.getMessage());
OUTPUT:
John, 25000
Alice, 30000
Bob, 18000
Name Basic DA HRA Medical Gross
IT Net
John 25000.00 5000.00 2000.00 1000.00
33000.00 2000.00 31000.00
Alice 30000.00 6000.00 2400.00 1000.00
39400.00 2400.00 37000.00
Bob 18000.00 3600.00 1440.00 1000.00
24040.00 1440.00 22600.00
Program Specification:
Write a Java program to:
Read employee names and basic salaries from the text file
"employee.txt".
Calculate DA, HRA, Medical, IT, Gross salary, and Net salary
using:
DA = 20% of basic
HRA = 8% of basic
Medical = ₹ 1000
IT = 8% of basic
Gross = basic + DA + HRA + Medical
Net = Gross − IT
Display all details in tabular form.
Q 13. Wap in Java 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
task on the matrix:
a) Sort the elements of the single-dimensional array in
ascending order using any sorting technique and
display the sorted elements.
b) Fill the matrix b[][] in the following format.
If the array a[] = {5,2,8,1} then after sorting, a[] = {1,2,5,8}
then the matrix b[][] would fill as below:
1258
1251
1212
1125
c) Display the filled matrix in the above format. Also, create
the main() method to create the object of the
class and to call the required methods.
Program Specification:
Write a Java program to:
Accept N (where 2 < N < 10) and positive integers into a 1D array
a[].
Sort a[] in ascending order and display it.
Fill a square matrix b[N][N] with values from the sorted array
according to a specific filling pattern:
First row contains all sorted elements of a[].
For each subsequent row, fill elements from the start of the sorted
array until the previous row’s value is reached, then wrap around if
needed.
Display the filled matrix.
Algorithm:
Start.
Input N (check if 2 < N < 10).
Input N positive integers into array a[].
Sort a[] in ascending order.
Display sorted array.
Fill matrix b[][]:
First row = sorted array elements.
For each subsequent row, repeat filling from a[] in the given pattern.
Display the matrix.
End.
import java.util.*;
public class ArrayMatrix {
int N;
int[] a;
int[][] b;
// Method to input and sort array
void inputArray() {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter size of array (N) where 2 < N <
10: ");
N = sc.nextInt();
} while (N <= 2 || N >= 10);
a = new int[N];
b = new int[N][N];
System.out.println("Enter " + N + " positive integers:");
for (int i = 0; i < N; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a); // sort array
System.out.println("Sorted array: " + Arrays.toString(a));
}
// Method to fill the matrix
void fillMatrix() {
for (int i = 0; i < N; i++) {
int index = 0;
for (int j = 0; j < N; j++) {
b[i][j] = a[index];
index++;
if (index == N) index = 0;
}
}
}
// Method to display the matrix
void displayMatrix() {
System.out.println("Matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
// Main method
public static void main(String[] args) {
ArrayMatrix obj = new ArrayMatrix();
obj.inputArray();
obj.fillMatrix();
obj.displayMatrix();
}
}
OUTPUT:
Enter size of array (N) where 2 < N < 10: 4
Enter 4 positive integers:
5281
Variable Listing:
int N → size of the array and matrix.
int[] a → single-dimensional array of size N.
int[][] b → square matrix of size N x N.
int i, j, k → loop counters.
Scanner sc → for user input.
Algorithm:
1)Start.
2)Input N (check if 2 < N < 10).
3)Input N positive integers into array a[].
4)Sort a[] in ascending order.
5)Display sorted array.
6)Fill matrix b[][]:
First row = sorted array elements.
For each subsequent row, repeat filling from a[] in the given
pattern.
7)Display the matrix.
9) End.
import java.util.*;
public class ArrayMatrix {
int N;
int[] a;
int[][] b;
// Method to input and sort array
void inputArray() {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter size of array (N) where 2 < N
< 10: ");
N = sc.nextInt();
} while (N <= 2 || N >= 10);
a = new int[N];
b = new int[N][N];
System.out.println("Enter " + N + " positive integers:");
for (int i = 0; i < N; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a); // sort array
System.out.println("Sorted array: " +
Arrays.toString(a));
}
// Method to fill the matrix
void fillMatrix() {
for (int i = 0; i < N; i++) {
int index = 0;
for (int j = 0; j < N; j++) {
b[i][j] = a[index];
index++;
if (index == N) index = 0;
}
}
}
// Method to display the matrix
void displayMatrix() {
System.out.println("Matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
// Main method
public static void main(String[] args) {
ArrayMatrix obj = new ArrayMatrix();
obj.inputArray();
obj.fillMatrix();
obj.displayMatrix();
}
}
OUTPUT:
Enter size of array (N) where 2 < N < 10: 4
Enter 4 positive integers:
5281
Sorted array: [1, 2, 5, 8]
Matrix:
1258
1251
1212
1125
Variable Listing:
int N → size of the array and matrix.
int[] a → single-dimensional array of size N.
int[][] b → square matrix of size N x N.
int i, j, k → loop counters.
Scanner sc → for user input.
Q14) Wap in Java to input two binary
numbers. Calculate the sum of these two
binary numbers and display
the output on the screen.Also, create the
main() method to create the object of the
class and to call the
required methods.
Program Specification:
Write a Java program to:
1)Accept two binary numbers as strings from
the user.
2)Convert them to decimal values.
3)Add them together.
4)Convert the sum back into binary.
5) Display the binary sum on the screen.
Algorithm:
1)Start.
2)Input two binary numbers as strings.
3)Convert both binary strings to decimal
using Integer.parseInt(binaryString, 2).
4)Add the decimal values.
5)Convert the sum back to binary using
Integer.toBinaryString(sum).
6)Display the binary sum.
7)End.
import java.util.*;
public class BinaryAddition {
String bin1, bin2;
// Method to input two binary numbers
void inputBinaries() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first binary
number: ");
bin1 = sc.next();
System.out.print("Enter second binary
number: ");
bin2 = sc.next();
}
// Method to add the two binary numbers
void addBinaries() {
int dec1 = Integer.parseInt(bin1, 2);
int dec2 = Integer.parseInt(bin2, 2);
int sum = dec1 + dec2;
String binarySum =
Integer.toBinaryString(sum);
System.out.println("Sum of the two
binary numbers: " + binarySum);
}
// Main method
public static void main(String[] args) {
BinaryAddition obj = new
BinaryAddition();
obj.inputBinaries();
obj.addBinaries();
}
}
Output:
Enter first binary number: 1011
Enter second binary number: 1101
Sum of the two binary numbers: 11000
Variable Listing:
String bin1, bin2 → to store the input binary
numbers.
int dec1, dec2, sum → to store decimal
conversions and their sum.
Scanner sc → to take user input.
Q 15. An Abundant number is a number for
which the sum of its proper factors is greater
than the number
itself. Write a program to input a number and
check and print whether it is an Abundant
number or not.
Example:
Consider the number 12.
Factors of 12 = 1, 2, 3, 4, 6 Sum of factors = 1
+ 2 + 3 + 4 + 6 = 16 As 16 > 12 so 12 is an
Abundant number.
Write a program in java to accept a number.
Check and display whether it is a Rouney
number or not. Also,
create the main () method to create the
object of the class and to call the required
methods.
Program Specification:
Create a Java program to:
1)Accept a number from the user.
2)Find all its proper factors (excluding the
number itself).
3)Sum those factors.
4)Compare the sum to the number.
5)If the sum is greater than the number, it’s
an Abundant Number; otherwise, it’s not.
ALGORITHM:
1)Start.
2)Input a positive integer.
3)Initialize sum = 0.
4)Loop from 1 to num/2:
If num % i == 0, add i to sum.
5)If sum > num, print that it’s an Abundant
Number.
6)Else, print that it’s not.
7)End.
import java.util.*;
public class AbundantNumber {
int num;
// Method to take input
void inputNumber() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive
number: ");
num = sc.nextInt();
}
// Method to check if the number is
abundant
void checkAbundant() {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
if (sum > num) {
System.out.println(num + " is an
Abundant Number.");
} else {
System.out.println(num + " is NOT an
Abundant Number.");
}
}
// Main method
public static void main(String[] args) {
AbundantNumber obj = new
AbundantNumber();
obj.inputNumber();
obj.checkAbundant();
}
}
Output:
Enter a positive number: 12
12 is an Abundant Number.
Variable Listing:
int num → the input number.
int sum → sum of proper factors.
Scanner sc → for input.
Q 16. A class Rearrange has been defined to
modify a word by bringing all the vowels in
the word at the
beginning followed by the consonants.
Example:
ORIGINAL becomes OIHARGNL
Some of the members of the class are given
below:
Class name: Rearrange
Data Member/instance variable:
wrd: to store a word
newwrd: to store the rearranged word
Member functions/methods:
Rearrange(): default constructor
void readword(): to accept the word in UPPER
case
vow freq_vow_con(): finds the frequency of
vowels and consonants in the word and
displays them with an
appropriate message
void arrange(); rearranges the word by
bringing the vowels at the beginning followed
by consonants
void display(): displays the original word
along with the rearranged word
Specify the class Rearrange, giving the
details of the constructor(), void readword(),
void freq_vow_con().
void arrange() and void display(). Define the
main() function to create an object and call
the functions
accordingly to enable the task.
Program Specification:
We need to create a class Rearrange that:
1)Accepts a word in uppercase.
2)Counts the frequency of vowels and
consonants in the word and displays them.
3)Rearranges the word so all vowels come
first (in order of occurrence) followed by
consonants.
4) Displays both the original and rearranged
words.
Algorithm:
1)Start.
2)Use readword() to take an uppercase word
as input.
3)In freq_vow_con():
Initialize vowel and consonant counters to
zero.
Loop through each character:
If vowel, increment vowCount.
Else if alphabetic and consonant, increment
conCount.
Display counts.
4)In arrange():
Loop through the word to collect vowels first.
Loop again to collect consonants.
Concatenate results into newwrd.
5)In display():
Show original and rearranged words.
6)In main():
Create an object, call methods in order.
7)End.
import java.util.*;
public class Rearrange {
String wrd;
String newwrd;
// Default constructor
Rearrange() {
wrd = "";
newwrd = "";
}
// Method to read the word in uppercase
void readword() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word in
uppercase: ");
wrd = sc.nextLine().toUpperCase();
}
// Method to find and display frequency of
vowels and consonants
void freq_vow_con() {
int vowCount = 0, conCount = 0;
for (int i = 0; i < wrd.length(); i++) {
char ch = wrd.charAt(i);
if ("AEIOU".indexOf(ch) != -1) {
vowCount++;
} else if (Character.isLetter(ch)) {
conCount++;
}
}
System.out.println("Number of vowels: "
+ vowCount);
System.out.println("Number of
consonants: " + conCount);
}
// Method to rearrange vowels first, then
consonants
void arrange() {
String vowels = "", consonants = "";
for (int i = 0; i < wrd.length(); i++) {
char ch = wrd.charAt(i);
if ("AEIOU".indexOf(ch) != -1) {
vowels += ch;
} else if (Character.isLetter(ch)) {
consonants += ch;
}
}
newwrd = vowels + consonants;
}
// Method to display original and
rearranged word
void display() {
System.out.println("Original word: " +
wrd);
System.out.println("Rearranged word: "
+ newwrd);
}
// Main method
public static void main(String[] args) {
Rearrange obj = new Rearrange();
obj.readword();
obj.freq_vow_con();
obj.arrange();
obj.display();
}
}
import java.util.*;
public class Rearrange {
String wrd;
String newwrd;
// Default constructor
Rearrange() {
wrd = "";
newwrd = "";
}
// Method to read the word in uppercase
void readword() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word in
uppercase: ");
wrd = sc.nextLine().toUpperCase();
}
// Method to find and display frequency of
vowels and consonants
void freq_vow_con() {
int vowCount = 0, conCount = 0;
for (int i = 0; i < wrd.length(); i++) {
char ch = wrd.charAt(i);
if ("AEIOU".indexOf(ch) != -1) {
vowCount++;
} else if (Character.isLetter(ch)) {
conCount++;
}
}
System.out.println("Number of vowels: "
+ vowCount);
System.out.println("Number of
consonants: " + conCount);
}
// Method to rearrange vowels first, then
consonants
void arrange() {
String vowels = "", consonants = "";
for (int i = 0; i < wrd.length(); i++) {
char ch = wrd.charAt(i);
if ("AEIOU".indexOf(ch) != -1) {
vowels += ch;
} else if (Character.isLetter(ch)) {
consonants += ch;
}
}
newwrd = vowels + consonants;
}
// Method to display original and
rearranged word
void display() {
System.out.println("Original word: " +
wrd);
System.out.println("Rearranged word: "
+ newwrd);
}
// Main method
public static void main(String[] args) {
Rearrange obj = new Rearrange();
obj.readword();
obj.freq_vow_con();
obj.arrange();
obj.display();
}
}
Output:
Enter a word in uppercase: ORIGINAL
Number of vowels: 3
Number of consonants: 5
Original word: ORIGINAL
Rearranged word: OIA RGNAL
Variable Listing:
String wrd → to store the original word.
String newwrd → to store the rearranged
word.
int vowCount → number of vowels.
int conCount → number of consonants.
Q 17. Write a program to declare a matrix A
[][] of order (MN) 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 x 82 + 3 x 81 + 1 x 80
)
4 0 5 (decimal equivalent of 1st row = 261 i.e.
4 x 82 + 0 x 81 + 5 x 80
)
1 5 6 (decimal equivalent of 1st row = 110 i.e.
1 x 82 + 5 x 81 + 6 x 80
)
Perform the following tasks on the matrix:
1. Display the original matrix,
2. Calculate the decimal equivalent for each
row and display it at the end row-wise.
Also, create the main() method to create the
object of the class and to call the required
methods.
Program Specification:
We need to:
1)Declare a matrix A[M][N] where:
0 < M < 10 (rows)
2 < N < 6 (columns)
2)Allow only digits 0–7 in each cell (valid
octal digits).
3)Treat each row as an octal number and
convert it to its decimal equivalent.
4)Display:
Original matrix.
Decimal equivalent for each row.
Algorithm:
1)Start.
2)Read M and N ensuring constraints:
0 < M < 10
2<N<6
3)Create matrix A[M][N].
4)For each element:
Accept an integer between 0 and 7.
Reject and re-enter if invalid.
Display original matrix.
For each row:
5)Initialize decimalValue = 0.
6)For column index j from 0 to N-1:
decimalValue += A[row][j] * Math.pow(8, N -
1 - j).
Print decimal value for that row.
6) End.
import java.util.*;
public class OctalMatrix {
int M, N;
int[][] A;
// Method to read matrix dimensions and
elements
void readMatrix() {
Scanner sc = new Scanner(System.in);
// Read M and N with constraints
do {
System.out.print("Enter number of
rows (M) [1-9]: ");
M = sc.nextInt();
} while (M <= 0 || M >= 10);
do {
System.out.print("Enter number of
columns (N) [3-5]: ");
N = sc.nextInt();
} while (N <= 2 || N >= 6);
A = new int[M][N];
// Input only 0-7
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
int val;
do {
System.out.print("Enter octal
digit (0-7) for A[" + i + "][" + j + "]: ");
val = sc.nextInt();
} while (val < 0 || val > 7);
A[i][j] = val;
}
}
}
// Method to display original matrix
void displayMatrix() {
System.out.println("\nOriginal Matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
}
// Method to calculate and display decimal
equivalents
void displayDecimalEquivalents() {
System.out.println("\nDecimal
equivalents of each row:");
for (int i = 0; i < M; i++) {
int decimalValue = 0;
for (int j = 0; j < N; j++) {
decimalValue += A[i][j] *
Math.pow(8, N - 1 - j);
}
System.out.println("Row " + (i + 1) +
": " + decimalValue);
}
}
// Main method
public static void main(String[] args) {
OctalMatrix obj = new OctalMatrix();
obj.readMatrix();
obj.displayMatrix();
obj.displayDecimalEquivalents();
}
}
OUTPUT:
Enter number of rows (M) [1-9]: 3
Enter number of columns (N) [3-5]: 3
Enter octal digit (0-7) for A[0][0]: 2
Enter octal digit (0-7) for A[0][1]: 3
Enter octal digit (0-7) for A[0][2]: 1
Enter octal digit (0-7) for A[1][0]: 4
Enter octal digit (0-7) for A[1][1]: 0
Enter octal digit (0-7) for A[1][2]: 5
Enter octal digit (0-7) for A[2][0]: 1
Enter octal digit (0-7) for A[2][1]: 5
Enter octal digit (0-7) for A[2][2]: 6
Original Matrix:
231
405
156
Decimal equivalents of each row:
Row 1: 153
Row 2: 261
Row 3: 110
Variable Listing:
int M → number of rows.
int N → number of columns.
int[][] A → matrix to store octal digits.
Scanner sc → for user input.
int decimalValue → stores decimal equivalent
of each row temporarily.
Q 18. Write a program to find the reverse of
all the numbers in the range A to B (A and B
both are positive
integers > 0, entered by the user) and store
in the binary file "REVERSE.DAT" in a tabular
form as follows:
Number: 123. Reverse: 321
Number: 124. Reverse: 421
Number: 125. Reverse: 521
...and so on.
Also, create the main() method to create the
object of the class and to call the required
methods.
Program Specification:
We need to:
Input two positive integers A and B (both >
0).
For each number from A to B, find its reverse.
Store the data in a binary file named
"REVERSE.DAT" in this tabular form:
Number: 123 Reverse: 321
Number: 124 Reverse: 421
...
Display a confirmation message after writing
to the file.
Algorithm:
1)Start.
2)Read A and B ensuring both > 0 and A ≤ B.
3)Open REVERSE.DAT in binary write mode
(DataOutputStream).
4)For each number num from A to B:
Find its reverse by:
Set rev = 0.
While numCopy > 0:
digit = numCopy % 10
rev = rev * 10 + digit
numCopy = numCopy / 10
Write "Number: X Reverse: Y" to file using
writeUTF().
5)Close file.
6)End.
import java.io.*;
import java.util.*;
public class ReverseNumbers {
int A, B;
// Method to read input range
void readRange() {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter starting
number A (>0): ");
A = sc.nextInt();
} while (A <= 0);
do {
System.out.print("Enter ending
number B (>0 and >= A): ");
B = sc.nextInt();
} while (B <= 0 || B < A);
}
// Method to reverse a number
int reverseNumber(int num) {
int rev = 0;
while (num > 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
return rev;
}
// Method to write numbers and reverses to
a binary file
void writeToFile() {
try (DataOutputStream dos = new
DataOutputStream(new
FileOutputStream("REVERSE.DAT"))) {
for (int i = A; i <= B; i++) {
int rev = reverseNumber(i);
String line = "Number: " + i + "
Reverse: " + rev;
dos.writeUTF(line);
}
System.out.println("Data written to
REVERSE.DAT successfully.");
} catch (IOException e) {
System.out.println("Error writing to
file: " + e.getMessage());
}
}
// Main method
public static void main(String[] args) {
ReverseNumbers obj = new
ReverseNumbers();
obj.readRange();
obj.writeToFile();
}
}
Output:
Enter starting number A (>0): 123
Enter ending number B (>0 and >= A): 126
Data written to REVERSE.DAT successfully.
Number: 123 Reverse: 321
Number: 124 Reverse: 421
Number: 125 Reverse: 521
Number: 126 Reverse: 621
Variable Listing:
int A, B → range start and end values.
int num, rev → to hold the number and its
reversed value.
Scanner sc → for user input.
FileOutputStream fos → binary file output
stream.
DataOutputStream dos → to write primitive
values to the file.
Q 19. Write a Program in Java to input a
number and check whether it is a Fascinating
Number or not.
Fascinating Numbers: Some numbers of 3
digits or more exhibit a very interesting
property. The property is
such that, when the number is multiplied by 2
and 3, and both these products are
concatenated with the
original number, all digits from 1 to 9 are
present exactly once, regardless of the
number of zeroes.
Let's understand the concept of a Fascinating
Number through the following example:
Consider the number 192
192 x 1 = 192
192x2 = 384
192 x3 = 576
Concatenating the results: 192 384 576
It could be observed that '192384576'
consists of all digits from 1 to 9 exactly once.
Hence, it could be
concluded that 192 is a Fascinating Number.
Some examples of fascinating Numbers are:
192, 219, 273 327,
1902, 1920, 2019 etc.
Program Specification:
1)Input a number n (must have at least 3
digits).
2)Multiply it by 2 and 3.
3)Concatenate the original number, the
result of n × 2, and the result of n × 3.
4)Check if the concatenated string contains
all digits 1–9 exactly once (ignoring zeros).
5)Display whether the number is Fascinating
or Not Fascinating.
ALGORITHM:
1)Start.
2)Input n ensuring it has at least 3 digits.
3)Calculate n2 = n × 2 and n3 = n × 3.
4)Concatenate: concat = n + "" + n2 + n3.
5)Check if:
All digits 1 to 9 appear exactly once in
concat.
Ignore zeros.
6)If the condition is satisfied, print
"Fascinating Number", else print "Not
Fascinating".
7)End.
import java.util.*;
public class FascinatingNumber {
long n;
// Method to read input
void readNumber() {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a number (at
least 3 digits): ");
n = sc.nextLong();
} while (n < 100); // ensures at least 3
digits
}
// Method to check fascinating number
boolean isFascinating() {
long n2 = n * 2;
long n3 = n * 3;
String concat = n + "" + n2 + n3;
// Check digits 1-9 appear exactly once
for (char digit = '1'; digit <= '9'; digit+
+) {
int count = 0;
for (int i = 0; i < concat.length(); i++)
{
if (concat.charAt(i) == digit)
count++;
}
if (count != 1) return false;
}
return true;
}
// Main method
public static void main(String[] args) {
FascinatingNumber obj = new
FascinatingNumber();
obj.readNumber();
if (obj.isFascinating())
System.out.println(obj.n + " is a
Fascinating Number.");
else
System.out.println(obj.n + " is NOT a
Fascinating Number.");
}
}
OUTPUT:
Enter a number (at least 3 digits): 192
192 is a Fascinating Number.
Variable Listing:
long n → input number.
String concat → concatenated string of n, n ×
2, and n × 3.
boolean isFascinating → to store the check
result.
Scanner sc → to read input.
Q 20. 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 (ie, eight
spaces).
Define the main() function to create an object
and call the functions accordingly to enable
the task. Test your
program for the following data and some
random data:
Example 1
INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote
OUTPUT:
ERC
moo
uay
sdo
t
Re
o
l
s
Example 2
INPUT:
N=4
Team 1: Royal
Team 2: Mars
Team 3: De Rose
Team 4: Kings
OUTPUT:
RMDK
oaei
yrn
asRg
los
s
e
Example 3
INPUT:
N = 10
OUTPUT:
INVALID INPUT
Program Specification:
We need to:
Input N team names, where 2 < N < 9.
Display the names vertically side-by-side,
separated by a tab (or spaces).
If N is outside the range, display "INVALID
INPUT".
Algorithm:
1)Start.
2)Input N.
3)If N ≤ 2 or N ≥ 9, print "INVALID INPUT" and
stop.
4)Input N team names into teams[].
5)Find the length of the longest team name and
store in maxLen.
6)For row from 0 to maxLen - 1:
For each team col from 0 to N - 1:
If the current team name length is greater than
row, print the row-th character.
Else, print a space.
Print a tab (or 8 spaces) after each column except
last.
Move to next line.
7) End.
import java.util.*;
public class BannerDisplay {
int N;
String[] teams;
// Method to read team names
void readTeams() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of teams (3-
8): ");
N = sc.nextInt();
sc.nextLine(); // consume newline
if (N <= 2 || N >= 9) {
System.out.println("INVALID INPUT");
System.exit(0);
}
teams = new String[N];
for (int i = 0; i < N; i++) {
System.out.print("Team " + (i + 1) + ": ");
teams[i] = sc.nextLine();
}
}
// Method to display names vertically
void displayBanner() {
// Find max length
int maxLen = 0;
for (String team : teams) {
if (team.length() > maxLen) maxLen =
team.length();
}
// Print vertically
for (int row = 0; row < maxLen; row++) {
for (int col = 0; col < N; col++) {
if (row < teams[col].length())
System.out.print(teams[col].charAt(row));
else
System.out.print(" ");
if (col < N - 1) System.out.print("\t");
}
System.out.println();
}
}
// Main method
public static void main(String[] args) {
BannerDisplay obj = new BannerDisplay();
obj.readTeams();
obj.displayBanner();
}
}
Output:
Enter number of teams (3-8): 3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote
E R C
m o o
u a y
s d o
R t
o e
l
s
Variable Listing:
int N → number of teams.
String[] teams → array to store team names.
int maxLen → length of the longest team name.
Scanner sc → for user input.
int i, j → loop counters.
Q 21. 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
stark 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 (Nx5) 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
participant(s) having
the highest score.
Example: If the value of N = 4 then the array
would be:
Q1 Q2 Q3 Q4 Q5
Participant 1 A B B C A
Participant 2 D A D C B
Participant 3 A A B A C
Participant 4 D C C A B
Key to the question: D C C B A
Note: Array entries are line fed (i.e. one entry per
line)
Test your program for the following data and some
random data.
Example 1
INPUT:
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 AA
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
Program Specification:
We need to:
1)Accept N (number of participants), where 3 < N
< 11.
2)Store each participant’s answers for 5 questions
in a 2D array.
3)Store the correct answers in a 1D array.
4)Compare participant answers with the key to
compute scores.
5)Display:
Scores for each participant.
Highest score and participant(s) achieving it.
6)If N is out of range, show "INPUT SIZE OUT OF
RANGE" and stop.
Algorithm:
1)Start.
2)Input N.
3)If N ≤ 3 or N ≥ 11, print "INPUT SIZE OUT OF
RANGE" and stop.
4)Create answers[N][5].
5)For each participant, read answers to all 5
questions.
6)Read correct answers into key[5].
7)For each participant:
Compare each answer with the key.
Increment score for matches.
8)Display scores for all participants.
9)Find the highest score.
10)Display all participants whose score equals the
highest score.
10) End.
import java.util.*;
public class QuizResult {
int N;
char[][] answers;
char[] key;
int[] scores;
void readData() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of
participants (4-10): ");
N = sc.nextInt();
sc.nextLine(); // consume newline
if (N <= 3 || N >= 11) {
System.out.println("INPUT SIZE OUT OF
RANGE");
System.exit(0);
answers = new char[N][5];
scores = new int[N];
key = new char[5];
// Read answers
for (int i = 0; i < N; i++) {
System.out.println("Enter answers for
Participant " + (i + 1) + " (A/B/C/D):");
for (int j = 0; j < 5; j++) {
answers[i][j] =
sc.next().toUpperCase().charAt(0);
// Read key
System.out.println("Enter correct key
(A/B/C/D):");
for (int j = 0; j < 5; j++) {
key[j] = sc.next().toUpperCase().charAt(0);
void calculateScores() {
for (int i = 0; i < N; i++) {
int score = 0;
for (int j = 0; j < 5; j++) {
if (answers[i][j] == key[j]) {
score++;
scores[i] = score;
void displayResults() {
System.out.println("Scores:");
int highest = 0;
for (int i = 0; i < N; i++) {
System.out.println("Participant " + (i + 1)
+ " = " + scores[i]);
if (scores[i] > highest) {
highest = scores[i];
// Display highest scorers
System.out.println("Highest Score:");
for (int i = 0; i < N; i++) {
if (scores[i] == highest) {
System.out.println("Participant " + (i +
1));
public static void main(String[] args) {
QuizResult obj = new QuizResult();
obj.readData();
obj.calculateScores();
obj.displayResults();
OUTPUT:
Enter number of participants (4-10): 5
Enter answers for Participant 1 (A/B/C/D):
DABCC
Enter answers for Participant 2 (A/B/C/D):
AADCB
Enter answers for Participant 3 (A/B/C/D):
BACDB
Enter answers for Participant 4 (A/B/C/D):
DADCB
Enter answers for Participant 5 (A/B/C/D):
BCADD
Enter correct key (A/B/C/D):
BCDAA
Scores:
Participant 1 = 0
Participant 2 = 1
Participant 3 = 1
Participant 4 = 1
Participant 5 = 2
Highest Score:
Participant 5
Variable Listing:
int N → number of participants.
char[][] answers → answers of each
participant.
char[] key → correct answers to the quiz.
int[] scores → score for each participant.
int highest → highest score found.
Scanner sc → for user input.
Loop counters i, j.
Q22. Write a menu-driven program in Java to
check whether a given string is a palindrome
using recursion.
Define and use a recursive function:
String Reverse(String str) – This function
should return the reverse of the string using
recursion.
Menu Options (using switch-case):
1 → Input a string and check if it is a
palindrome (ignoring case).
2 → Prompt the user: “Do you want to
continue with another string?”
If the response is “Yes”, allow repetition.
Otherwise, exit the program.
• A string is said to be a palindrome if it
reads the same forward and backwards.
Example: "Madam", "RaceCar" are
palindromes; "Java" is not.
• Note: Do not use iterative constructs (for or
while) in the Reverse function.
Program Specification:
We need to:
1)Create a menu-driven program with switch-
case.
2)Implement recursive method String
Reverse(String str) to reverse a string
without loops.
3)Menu options:
Option 1: Input a string, reverse it using
recursion, and check for palindrome (ignore
case).
Option 2: Ask if the user wants to continue; if
"Yes" (case-insensitive), allow another run,
otherwise exit.
4)Palindrome check is case-insensitive.
5)Repeat until the user chooses to exit.
Algorithm:
1)Start program.
2)Use a loop to display menu options:
Option 1:
Accept a string.
Call Reverse(str) recursively to get rev.
Compare rev and str ignoring case.
Print whether it’s a palindrome.
Option 2:
Ask user "Do you want to continue with
another string?".
If answer is "Yes" (any case), continue; else
exit.
3)Recursive function Reverse(str):
If str length is 0 or 1, return str.
Else return Reverse(str.substring(1)) +
str.charAt(0).
4)End.
import java.util.*;
public class PalindromeRecursion {
// Recursive method to reverse a string
String Reverse(String str) {
if (str.length() <= 1) {
return str;
return Reverse(str.substring(1)) +
str.charAt(0);
void checkPalindrome() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String rev = Reverse(str);
if (rev.equalsIgnoreCase(str)) {
System.out.println(str + " is a
Palindrome.");
} else {
System.out.println(str + " is NOT a
Palindrome.");
public static void main(String[] args) {
PalindromeRecursion obj = new
PalindromeRecursion();
Scanner sc = new Scanner(System.in);
String ans = "Yes";
while (ans.equalsIgnoreCase("Yes")) {
System.out.println("\nMENU");
System.out.println("1 → Input a string
and check palindrome");
System.out.println("2 → Exit");
System.out.print("Enter your choice:
");
int choice = sc.nextInt();
sc.nextLine(); // consume newline
switch (choice) {
case 1:
obj.checkPalindrome();
System.out.print("Do you want to
continue with another string? ");
ans = sc.nextLine();
break;
case 2:
ans = "No";
break;
default:
System.out.println("Invalid
choice!");
System.out.println("Program
terminated.");
Output:
MENU
1 → Input a string and check palindrome
2 → Exit
Enter your choice: 1
Enter a string: RaceCar
RaceCar is a Palindrome.
Do you want to continue with another string?
Yes
MENU
1 → Input a string and check palindrome
2 → Exit
Enter your choice: 1
Enter a string: Java
Java is NOT a Palindrome.
Do you want to continue with another string?
No
Program terminated.
Variable Listing:
String str → input string.
String rev → reversed string.
int choice → menu choice.
Scanner sc → to read input.
String ans → user’s response for continuing.
Q 23. A triangular number is formed by the
addition of consecutive integers, starting
from 1.
E.g. 3 = 1 + 2
6=1+2+3
10= 1 + 2 + 3 + 4.
Wap in Java to display all the triangular
numbers starting from 3 to n (where n is user
input).
Use the method: int Triangle(int), which
receives an integer and returns 1 if it is a
triangular number
otherwise 0 ,recursively
Program Specification:
We need to:
1)Input an integer n (upper limit).
2)Display all triangular numbers from 3 to n.
3)Define a recursive method:
int Triangle(int num) → returns 1 if num is
triangular, else 0.
4)A triangular number is a sum of
consecutive integers starting from 1.
Example:
3 → 1+2
6 → 1+2+3
10 → 1+2+3+4
5)No loops allowed inside the recursive check
function (loops can be used in main to test
range).
Algorithm:
1)Start.
2)Accept n from the user.
3)Loop through numbers from 3 to n:
Call Triangle(num) to check if it is triangular.
If function returns 1, display it.
4)Recursive Triangle(int num) logic:
Start with helper method isTriangular(num,
current, sum) →
Base case 1: if sum == num, return 1 (true).
Base case 2: if sum > num, return 0 (false).
Else call recursively with current+1 and
sum+current+1.
5) End.
import java.util.*;
public class TriangularNumbers {
// Recursive check for triangular number
int isTriangular(int num, int current, int
sum) {
if (sum == num) {
return 1; // Triangular
if (sum > num) {
return 0; // Not triangular
return isTriangular(num, current + 1,
sum + current + 1);
// Main Triangle method as per question
int Triangle(int num) {
return isTriangular(num, 1, 1); // start
from 1 with sum=1
}
public static void main(String[] args) {
TriangularNumbers obj = new
TriangularNumbers();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the upper limit
(n): ");
int n = sc.nextInt();
System.out.println("Triangular numbers
from 3 to " + n + ":");
for (int i = 3; i <= n; i++) {
if (obj.Triangle(i) == 1) {
System.out.print(i + " ");
Output:
Enter the upper limit (n): 15
Triangular numbers from 3 to 15:
3 6 10 15
Variable Listing:
int n → upper limit input.
int i → loop index for checking numbers from
3 to n.
int sum → used in recursion to check if a
number is triangular.
Scanner sc → for user input.
Q 24. A class Shift in Java contains a 2D array
of order (m*n), where the maximum values of
both m and n
are 5. Design the class Shift to shuffle the
matrix.
[The first row becomes the last, the second
row becomes the first, and so on. Or/and the
first column
becomes the last, the second column becomes
the first, and so on.]
Class name: Shift
Data Members: int mat[][], m, n .
Member functions:
Shift(int mn, int nn): A constructor to
initialise the data members m equals mn and
n equals nn.
void input(): Enters the elements of the array.
void cyclic1(Shift P): Enables the matrix of
the object P to shift each row upwards in a
cyclic manner and
store the resultant matrix in the current
object.
void cyclic2(Shift Q): Enables the matrix of
the object Q to shift each column leftwards in
a cyclic manner
and store the resultant matrix in the current
object.
void display(): Displays the matrix elements.
Define the main method to create an object
and call the method accordingly to enable the
task of shifting the
array elements.
Program Specification:
We need to create a class Shift to perform
cyclic shuffling of a matrix.
Data members: int mat[][], int m, int n
(where max m = 5, max n = 5).
Constructor: Shift(int mn, int nn) → initializes
m and n.
Methods:
1)void input() → enter elements into mat.
2)void cyclic1(Shift P) → cyclic shift of rows
upwards:
The first row becomes last, the second
becomes first, etc.
3)void cyclic2(Shift Q) → cyclic shift of
columns leftwards:
The first column becomes last, the second
becomes first, etc.
4)void display() → display mat.
Main method tasks:
Create objects of Shift.
Input matrix data.
Use cyclic1 or cyclic2 to perform shifts.
Display results.
Algorithm:
1)Start.
2)Create object of Shift with given m and n.
3)Call input() to read matrix elements.
4)For cyclic1 (row shift up):
Copy rows from P.mat to this.mat so that row
1 → last, others move up.
5)For cyclic2 (column shift left):
Copy columns from Q.mat to this.mat so that
col 1 → last, others move left.
6)Display original and shifted matrices.
7)End.
import java.util.*;
class Shift {
int mat[][];
int m, n;
// Constructor
Shift(int mn, int nn) {
m = mn;
n = nn;
mat = new int[m][n];
}
// Input method
void input() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements
of the matrix (" + m + "x" + n + "):");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
// Shift rows upwards cyclically
void cyclic1(Shift P) {
for (int i = 0; i < m - 1; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = P.mat[i + 1][j];
// Last row becomes first row of P
for (int j = 0; j < n; j++) {
mat[m - 1][j] = P.mat[0][j];
}
// Shift columns leftwards cyclically
void cyclic2(Shift Q) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - 1; j++) {
mat[i][j] = Q.mat[i][j + 1];
// Last column becomes first column of
Q
mat[i][n - 1] = Q.mat[i][0];
// Display matrix
void display() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + "\t");
System.out.println();
}
// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows (max 5): ");
int m = sc.nextInt();
System.out.print("Enter cols (max 5): ");
int n = sc.nextInt();
if (m > 5 || n > 5 || m <= 0 || n <= 0) {
System.out.println("Invalid matrix
size!");
return;
Shift original = new Shift(m, n);
original.input();
System.out.println("\nOriginal Matrix:");
original.display();
Shift rowShifted = new Shift(m, n);
rowShifted.cyclic1(original);
System.out.println("\nAfter Cyclic Row
Shift Upwards:");
rowShifted.display();
Shift colShifted = new Shift(m, n);
colShifted.cyclic2(original);
System.out.println("\nAfter Cyclic
Column Shift Leftwards:");
colShifted.display();
Variable Listing:
int m → number of rows.
int n → number of columns.
int mat[][] → 2D array to store matrix.
int i, j → loop counters.
Scanner sc → for input.