0% found this document useful (0 votes)
45 views

com_pra[1]000[1]

Uploaded by

dasrozalin3
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)
45 views

com_pra[1]000[1]

Uploaded by

dasrozalin3
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/ 44

SI.

Question Page
No. No.
1.

2. 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'.
3. 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.

4. Given two positive integers m and n, where m < n, write a program to determine how many unique- digit integers
are there in the range between m and n (both inclusive) and output them. The input contains two positive integers
m and n. Assume m < 30000 and n < 30000 You are to output the number of unique- digit integers in the specified
range along with their values in the format specified below:

5. Write a program in Java to display all the triangular numbers from 3 to n, taking the value of n as an input.

6. .WAP in java to accept a positive no. and check whether it is circular prime or not.Example of circular prime no 131,
197, 1193

7. Write a program in java to accept a number. Check and display whether it is a Bouncy number or not.

8. Write a program in Java to enter a number and check whether it is a Smith number or not.

9. WAP in java to find the sum of border (4X4) elements and sum for non-border elements.
10. WAP in Bluej to accept 4x4 array elements. Sort the elements and display them in clockwise direction.
11. Write a program in java to accept two number and check whether it is amicable number or not.
Amicable number: A pair of numbers, each of which is the sum of the factors of the other (e.g. 220 and 284).
12. Write a Program in Java to input a number and check whether it is a Fascinating Number or not.Fascinating
Numbers
13. Design a program to accept a positive whole number and find the binary equivalent of the number and count the
number of 1's in it and display whether it is a Evil number or not with an appropriate message.
Output: Evil Number

14. Write a program in Bluej to accept a sentence from the user. Display the longest palindrome word in the sentence.

15. Write a program to declare a square matrix A[][] of order (M x M) where 'M' is the number of rows and the number
of columns such that M must be greater than 2 and less than 20. Allow the user to input integers into this matrix.
16. 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.

17. Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or ‘!’ only.
18. Write a main method to create an object of a class and call the above member methods

19. Write the program in Java what the teacher would write to solve the purpose.

20. Define the class NumSort giving details of the constructor (int), void extract_digit(), void sort() and void display().
Define the main () function to create an object and call the functions accordingly to enable the task
Program 1
Question:

algorithm:
1. **Start**

2. Declare an array `arr[]` of size 10.

3. Use a loop to take 10 integer inputs from the user and store them in the array.

4. For each element in the array:

- Check if it is a prime number using a helper method `isPrime()`.

- If the number is prime, replace it with 0.

5. Print the modified array.

6. **End**

Java Program:
import java.util.Scanner;

public class PrimeReplacement {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int[] arr = new int[10];

// Input 10 numbers into the array

System.out.println("Enter 10 numbers:");

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

arr[i] = sc.nextInt(); }

// Replace prime numbers with 0

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

if (isPrime(arr[i])) {

arr[i] = 0; } }

// Print the modified array

System.out.println("Modified array:");

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

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

// Method to check if a number is prime

public static boolean isPrime(int n) {

if (n < 2) {

return false; }

for (int i = 2; i <= Math.sqrt(n); i++) {


if (n % i == 0) {

return false; } }

return true; }}

variable DescriPtion table:


Variable Data type Descriptiuon
arr[] Int Array to store 10 integer no.
Sc Scanner Object of scanner class
I Int Loop variable for iteration
N Int To check if no. is prime or not
outPut:
Program 2:
Question:
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 and 7, 5 and 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’.

algorithm
1. **Start**

2. Accept an even integer `N` from the user such that `N > 9` and `N < 50`.

3. Initialize an array of odd primes below 50.

4. Loop through the array to find all pairs of odd primes whose sum equals `N`.

5. If a valid pair is found, display the pair.

6. If no pair is found, display a message saying there are no pairs.

7. **End**

Java Program
import java.util.*;

public class GoldbachNumber {

// Method 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; }

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input: Accepting the even integer N

System.out.print("enter an integer more than 10 and less than 50");

int N = sc.nextInt();

// Check if N is valid

if (N <= 9 || N >= 50 || N % 2 != 0) {

System.out.println("invalid input");
return; }

// Array of odd prime numbers below 50

int[] oddPrimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};

Boolean foundPair = false;

// Loop to find pairs whose sum equals N

for (int I = 0; I < oddPrimes.length; I++) {

for (int j = I; j < oddPrimes.length; j++) {

if (oddPrimes[I] + oddPrimes[j] == N) {

System.out.println(N + "+" + oddPrimes[I] + "+" + oddPrimes[j]);

foundPair = true; } } }

// If no pair was found

if (!foundPair) {

System.out.println("no pair for odd prime no. found for"+N); }

sc.close(); }}

variable DescriPtion table


Variable Data type Description
N int Even integer input by user
oddPrime int Array to hold odd prime no.
foundPair boolean Flag to check if odd prime no. is found
I, j int To iterate the loop
Sc Scanner An object

outPut:
Program 3
Question:
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 OllARGNL

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 changed word

Member functions/methods:

Rearrange():default constructor

Void readword():to store the rearranged word

Void freq_vow_con():to accept the word in UPPER case

Finds the frequency of vowels and consonants

In the word and displays then 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.

Here is a detailed explanation and the Java program for the class `Rearrange`, with algorithms and a variable description
table suitable for an ICSE student level:

algorithm:
1. **Start**

2. **Create Class Rearrange**

- Define instance variables `wrd` and `newwrd`.

- Create the default constructor.

3. **Define Method readword()**:

- Read and accept the word from the user, convert it to uppercase and store it in `wrd`.

4. **Define Method freq_vow_con()**:

- Count the number of vowels and consonants in the word and display the counts.

5. **Define Method arrange()**:

- Rearrange the word by placing all vowels at the beginning, followed by consonants. Store this new arrangement in
`newwrd`.

6. **Define Method display()**:

- Display the original word and the rearranged word.

7. **Create Main Method**:

- Create an object of the class `Rearrange`.

- Call the methods `readword()`, `freq_vow_con()`, `arrange()`, and `display()`.


8. **End**

Java Program:
import java.util.Scanner;

public class Rearrange {

// Instance variables

private String wrd;

private String newwrd;

// Default constructor

public Rearrange() {

wrd = "";

newwrd = ""; }

// Method to accept the word from the user

public void readword() {

Scanner sc = new Scanner(System.in);

System.out.println("enter a new word");

wrd = sc.next().toUpperCase(); // Convert to uppercase }

// Method to find and display frequency of vowels and consonants

public void freq_vow_con() {

int vowelCount = 0;

int consonantCount = 0;

for (int I = 0; I < wrd.length(); I++) {

char ch = wrd.charAt(I);

if ("AEIOU".indexOf(ch)!= -1) {

vowelCount++;

} else if (Character.isLetter(ch)) {

consonantCount++; } }

System.out.println("frequency of vowel:"+vowelCount);

System.out.println("frequency of consonent"+consonantCount); }

// Method to rearrange the word (vowels first, consonants later)

public void arrange() {

String vowels = "";

String 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 the original and rearranged words

public void display() {

System.out.println("original word="+wrd);

System.out.println("rearranged word="+newwrd); }

// Main method

public static void main(String[] args) {

// Create an object of the Rearrange class

Rearrange Obj = new Rearrange();

// Call methods to perform the task

Obj.readword();

Obj.freq_vow_con();

Obj.arrange();

Obj.display(); }}

variable DescriPtion table:


Variable Data type Description
Wrd String To store the original word entered by
the user.
Newwrd String | To store the rearranged word
(vowels first, then consonants).
vowelCount Int To store the count of vowels in the
word.
consonentCount int To store the count of consonants in
the word
Vowels String To store the vowels while rearranging
the word
Consonant String To store the consonants while
rearranging the word.

outPut:
Program 4
Question:
A unique-digit integer is a positive integer (without leading zeros) with no duplicates digits. For example 7, 135, 214 are all
unique-digit integers whereas 33, 3121, 300 are not. Given two positive integers m and n, where m < n, write a program to
determine how many unique- digit integers are there in the range between m and n (both inclusive) and output them. The
input contains two positive integers m and n. Assume m < 30000 and n < 30000 You are to output the number of unique-
digit integers in the specified range along with their values in the format specified below:

Sample Input: m = 100 n = 120

Sample Output: The Unique-Digit integers are: 102, 103, 104, 105, 106, 107, 108, 109, 120.

Frequency of unique-digit integers is:9

algorithm:
1. **Start**

2. **Input** the values of `m` and `n` (where `m < n` and `m < 30000`, `n < 30000`).

3. **Initialize** a counter variable for counting unique-digit integers.

4. **Loop** through all integers from `m` to `n`:

- **Check** if the current number is a unique-digit integer by ensuring no digit is repeated.

- If the number is unique, store it in the list and increment the counter.

5. **Print** the unique-digit integers.

6. **Print** the total count of unique-digit integers.

7. **End**

Java Program:
import java.util.Scanner;

public class UniqueDigitIntegers {

// Method to check if a number has unique digits

public static boolean isUniqueDigit(int num) {

boolean[] digitSeen = new boolean[10]; // To track the digits

while (num > 0) {

int digit = num % 10;

if (digitSeen[digit]) {

return false; // Digit already seen, not unique }

digitSeen[digit] = true;

num /= 10; }

return true; // All digits are unique }

// Main method

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input the range values m and n

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

int m = sc.nextInt();
System.out.print("enter value of n");

int n = sc.nextInt();

// Variables to store the count of unique digit integers

int counter = 0;

StringBuilder uniqueNumbers = new StringBuilder("the unique didgit integer are:");

// Loop through the range and find unique digit integers

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

if (isUniqueDigit(i)) {

uniqueNumbers.append(i).append(", ");

counter++; } }

// Removing the last comma and space

if (counter > 0) {

uniqueNumbers.setLength(uniqueNumbers.length()-2); }

// Print the result

System.out.println(uniqueNumbers);

System.out.println("frequency ="+counter); }}

variable DescriPtion table:


variable Data type Description
M int | The starting number of the range
(inclusive).
N int The ending number of the range
(inclusive).
I int Loop variable to iterate through
numbers from m to n
counter int | Counter to count the number of
unique-digit integers.
isUnique Boolean Flag to indicate whether a number is
unique.
Digit Int Temporary variable to store each digit
of the number.
Num Int Temporary variable to hold the value
of the number for digit comparison.
uniqueNumber String To store the unique-digit integers as a
single string for output.

outPut:
Program 5
Question:
A triangular number is formed by the addition of consecutive integers starting with 1. For example, 1+2=3 1 + 2 + 3 = 6 1 + 2
+ 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15 Thus, 3, 6, 10, 15, are triangular numbers.

Write a program in Java to display all the triangular numbers from 3 to n, taking the value of n as an input.

algorithm
1. Start

2. Input the value of `n`.

3. Initialize a variable `triangularNumber` to 0 and `i` to 1.

4. Loop while `triangularNumber` is less than or equal to `n`:

- Calculate the triangular number using the formula `triangularNumber = I * (I + 1) / 2`.

- If the triangular number is greater than or equal to 3 and less than or equal to `n`, print the triangular number.

- Increment `i` by 1.

5. End

Java Program:
import java.util.Scanner;

public class TriangularNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input the value of n

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

int n = sc.nextInt();

// Initialize variables

int triangularNumber = 0;

int I = 1;

System.out.println("traingular from 3 to"+n+":");

// Loop to calculate triangular numbers until it exceeds n

while (triangularNumber <= n) {

triangularNumber = I * (I + 1) / 2; // Calculate the triangular number

// Check if triangular number is within the range

if (triangularNumber >= 3 && triangularNumber <= n) {

System.out.println(triangularNumber); }

// Increment I for the next triangular number

I++;

} }}
variable DescriPtion table:
variable Data type Description
N int The upper limit to display triangular
numbers
I int Loop variable used to generate the
next triangular number
triangularNumber int | Stores the current triangular number

outPut:
Program 6
Question:
A circular prime no is a prime number that remains prime under cyclic shift

Example

131

311

113

Hence, 131 is a prime circular prime.

WAP in java to accept a positive no. and check whether it is circular prime or not.

Example of circular prime no 131, 197, 1193

algorithm:
1. **Input** the number `n`.

2. **Check Prime**: Write a helper function `isPrime()` to check if a number is prime.

3. **Generate Cyclic Permutations**: Create a helper function `getCyclicPermutations()` to generate all cyclic permutations
of `n`.

4. **Check Circular Prime**:

- For each cyclic permutation of the number, check if it is prime.

- If all permutations are prime, the number is a circular prime.

5. **Display Result**:

- If all permutations are prime, print "Circular Prime".

- Otherwise, print "Not a Circular Prime".

Java coDe:
import java.util.Scanner;

public class CircularPrimeChecker {

// 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 generate cyclic permutations of the number

public static String[] getCyclicPermutations(String numStr) {

int length = numStr.length();

String[] permutations = new String[length];

permutations[0] = numStr; // Generate permutations by rotating the digits

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

numStr = numStr.substring(1) + numStr.charAt(0);

permutations[i] = numStr; }
return permutations; } // Main function to check if a number is a circular prime

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input number from the user

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

int num = sc.nextInt();

sc.close();

// Convert the number to string for permutation generation

String numStr = Integer.toString(num);

// Generate all cyclic permutations

String[] permutations = getCyclicPermutations(numStr); // Check if all permutations are prime

boolean isCircularPrime = true;

for (String perm : permutations) {

if (!isPrime(Integer.parseInt(perm))) {

isCircularPrime = false;

break; } } // Output the result

if (isCircularPrime) {

System.out.println(num + " is a Circular Prime.");

} else {

System.out.println(num + " is not a Circular Prime."); } }}

variable DescriPtion table:


| **Variable Name** | Data type **Description**

| `num` | `int` | Stores the positive number entered


by the user|
| `numStr` | `String` | Stores the string version of the input
number |
| `permutations` | `String[]` | Stores all cyclic permutations of the
number |
| `isCircularPrime` | `boolean` | Indicates if the number is a circular
prime |
| `sc` | `Scanner` | Object for accepting user input
|
| `perm` | `String` | Used to iterate through each cyclic
permutation|

outPut:
Program 7:
Question:
A number is said to Bouncy number if the digits of the number are unsorted.

For example, 22344 – It is not a Bouncy number because the digits are sorted in ascending order. 774410 – It is not a
Bouncy number because the digits are sorted in descending order. 155349 – It is a Bouncy number because the digits are
unsorted. A number below 100 can never be a Bouncy number.

Write a program in java to accept a number. Check and display whether it is a Bouncy number or not.

algorithm:
1. **Start**

2. Accept a number from the user.

3. If the number is less than 100, output “Not a Bouncy number” because no number less than 100 can be bouncy.

4. Convert the number into a string to extract each digit.

5. Initialize two flags: `isAscending` and `isDescending` as true.

6. Loop through the digits of the number:

- If any digit is greater than the next digit, set `isAscending` to false.

- If any digit is less than the next digit, set `isDescending` to false.

7. If both `isAscending` and `isDescending` are false, the number is a Bouncy number.

8. Display the appropriate result.

9. **End**

Java coDe:
import java.util.Scanner;

public class BouncyNumberChecker {

public static void main(String[] args) {

// Step 1: Accept number from the user

Scanner scanner = new Scanner(System.in);

System.out.print("enter a no.");

int number = scanner.nextInt();

// Step 2: Check if the number is less than 100

if (number < 100) {

System.out.println("not a bouncy no.");

} else {

// Step 3: Convert the number to a string

String numberStr = Integer.toString(number);

// Step 4: Initialize flags

boolean isAscending = true;

boolean isDescending = true;

// Step 5: Check each digit in the number

for (int i = 0; i < numberStr.length()-1; i++) {

if (numberStr.charAt(i) > numberStr.charAt(i + 1)) {


isAscending = false; }

if (numberStr.charAt(i) < numberStr.charAt(i + 1)) {

isDescending = false; } }

// Step 6: Determine if it’s a Bouncy number

if (!isAscending && !isDescending) {

System.out.println("it is a bouncy no.");

} else {

System.out.println("not a bouncy no."); } } }}

variable DescriPtion table:


| Variable Name | Data Type | Description |
| `scanner` | `Scanner` | Used to accept input from the user. |
| `number` | `int` | The number entered by the user to
be checked. |
| `numberStr` | `String` | The string representation of the
entered number. |
| `isAscending` | `boolean` | Flag to check if digits are in
ascending order. |
| `isDescending` | `boolean` | Flag to check if digits are in
descending order. |
| `i` | `int` | Loop variable used to traverse the
digits of the number. |

outPut:
Program 8
Question:
A Smith number is a composite number, whose sum of the digits is equal to the sum of its prime factors. For example: 4, 22,
27, 58, 85, 94, 121 Smith numbers.

Write a program in Java to enter a number and check whether it is a Smith number or not.

Sample Input: 666 Sum of the digits: 6 + 6 + 6 = 18 Prime factors are: 2, 3, 3, 37 Sum of the digits of the prime factors: 2 + 3
+ 3+ (3+7) = 18 Thus, 666 is a Smith Number.

Here’s a Java program, written at the ICSE level, to check whether a number is a Smith number or not. Along with it, you will
also find the algorithm and the variable description table.

algorithm:
1. **Start**

2. Accept the number from the user.

3. If the number is a prime number, output "Not a Smith number" (since Smith numbers are composite).

4. Find the sum of the digits of the number.

5. Find all prime factors of the number and calculate the sum of the digits of those prime factors.

6. If the sum of the digits of the number is equal to the sum of the digits of its prime factors, it is a Smith number.

7. Display the appropriate result.

8. **End**

Java coDe:
import java.util.Scanner;

public class SmithNumberChecker {

// Helper function to check if a number is prime

public static 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; }

// Helper function to calculate sum of digits of a number

public static int sumOfDigits(int n) {

int sum = 0;

while (n > 0) {

sum += n % 10;

n /= 10; }

return sum; }

// Helper function to find sum of the digits of prime factors

public static int primeFactorsSum(int n) {

int sum = 0;

// Divide by 2 while even


while (n % 2 == 0) {

sum += sumOfDigits(2);

n /= 2; }

// Check for odd factors

for (int i = 3; i <= Math.sqrt(n); i += 2) {

while (n % i == 0) {

sum += sumOfDigits(i);

n /= i; } }

// If n is a prime number and greater than 2

if (n > 2) {

sum += sumOfDigits(n); }

return sum; }

public static void main(String[] args) {

// Step 1: Accept number from the user

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

// Step 2: Check if the number is prime

if (isPrime(number)) {

System.out.println("Not a Smith number.");

} else {

// Step 3: Calculate sum of the digits of the number

int sumDigits = sumOfDigits(number);

// Step 4: Calculate sum of the digits of prime factors

int sumPrimeFactorsDigits = primeFactorsSum(number);

// Step 5: Check if both sums are equal

if (sumDigits == sumPrimeFactorsDigits) {

System.out.println("It is a Smith number.");

} else {

System.out.println("Not a Smith number.");

}
variable DescriPtion table:
| Variable Name | Data Type | Description |
| `scanner` | `Scanner` | Used to accept input from the user. |
| `number` | `int` | The number entered by the user to
check for Smith number property. |
| `sumDigits` | `int` | Stores the sum of the digits of the
input number. |
| `sumPrimeFactorsDigits` | `int` | Stores the sum of the digits of the
prime factors of the input number. |
| `i` | `int` | Loop variable used to check prime
factors and traverse the digits. |
| `sum` | `int` | Temporary variable used to store
the sum of digits and prime factor
digits. |
| `n` | `int` | Used to break down the number
during factorization. |

outPut:
Program 9
Question:
WAP in java to find the sum of border (4X4) elements and sum for non-border elements.

algorithm
1. **Start**

2. **Initialize** a 4x4 matrix (2D array).

3. **Declare variables** to hold the sums: `borderSum` and `nonBorderSum`.

4. **Loop through** each element of the matrix:

- If the element is on the border, add it to `borderSum`.

- Otherwise, add it to `nonBorderSum`.

5. **Print** the values of `borderSum` and `nonBorderSum`.

6. **End**

Java Program
import java.util.Scanner;

public class MatrixSum {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int[][] matrix = new int[4][4];

int borderSum = 0;

int nonBorderSum = 0;

// Input elements in the 4x4 matrix

System.out.println("enter element for 4X4 matrix");

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

for (int j = 0; j < 4; j++) {

matrix[i][j] = sc.nextInt(); } }

// Calculate sums

for (int I = 0; I < 4; I++) {

for (int j = 0; j < 4; j++) {

// Check if element is at border

if (I == 0 || I == 3 || j == 0 || j == 3) {

borderSum += matrix[I][j];

} else {

nonBorderSum += matrix[I][j]; } } }

// Display the results

System.out.println("sum of border element" + borderSum);

System.out.println("sum of no border element="+nonBorderSum);

} }
variable DescriPtion table
| **Variable Name** | **Data Type| **Description**
| `matrix` | `int[][]` | 4x4 array storing matrix elements
|
| `borderSum` | `int` | Sum of all border elements of the
matrix |
| `nonBorderSum` | `int` | Sum of all non-border elements of
the matrix |
| `i` | `int` | Loop variable for rows |
| `j` | `int` | Loop variable for columns |

outPut:
Program 10
Question:
WAP in Bluej to accept 4x4 array elements. Sort the elements and display them in clockwise direction.

algorithm:
1. **Start**

2. **Initialize** a 4x4 matrix (2D array).

3. **Input** elements into the matrix.

4. **Flatten** the 2D array into a 1D array.

5. **Sort** the 1D array.

6. **Insert** the sorted elements back into the matrix in a clockwise spiral pattern.

7. **Display** the matrix in a clockwise direction.

8. **End**

Java Program
import java.util.Scanner;

public class ClockwiseMatrix {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int[][] matrix = new int[4][4];

int[] sortedArray = new int[16]; // Input elements into the 4x4 matrix

System.out.println("enter element fof 4X4 array");

int k = 0;

for (int I = 0; I < 4; I++) {

for (int j = 0; j < 4; j++) {

matrix[I][j] = sc.nextInt();

sortedArray[k++] = matrix[I][j]; } } // Sort the array

for (int I = 0; I < 16 - 1; I++) {

for (int j = 0; j < 16-1-I; j++) {

if (sortedArray[j] > sortedArray[j + 1]) {

int temp = sortedArray[j];

sortedArray[j] = sortedArray[j + 1];

sortedArray[j + 1] = temp; } } } // Fill the matrix in clockwise order with sorted elements

int index = 0;

int top = 0, bottom = 3, left = 0, right = 3;

while (top <= bottom && left <= right) { // Traverse from left to right across the top row

for (int i = left; i<= right; i++) {

matrix[top][i] = sortedArray[index++]; }

top++; // Traverse down the right column

for (int i = top; i <= bottom; i++) {


matrix[i][right] = sortedArray[index++]; }

right--; // Traverse from right to left across the bottom row

if (top <= bottom) {

for (int i = right; i >= left; i--) {

matrix[bottom][i] = sortedArray[index++]; }

bottom--; } // Traverse up the left column

if (left <= right) {

for (int i= bottom; i >= top; i--) {

matrix[i][left] = sortedArray[index++]; }

left++; } } // Display the matrix

System.out.println("sorted matrix in clockwise order");

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

for (int j = 0; j < 4; j++) {

System.out.print(matrix[i][j] +"\t"); }

System.out.println(); } }}

variable DescriPtion table


| **Variable Name** | **Data Type** | **Description**
|
| `matrix` | `int[][]` | 4x4 array storing the matrix
elements |
| `sortedArray` | `int[]` | 1D array for sorting elements
|
| `index` | `int` | Index for placing sorted elements in
a clockwise order|
| `i` | `int` | Loop variable for rows
|
| `j` | `int` | Loop variable for columns
|
| `temp` | `int` | Temporary variable for swapping
during sorting |
outPut:
Program 11
Question!:
Write a program in java to accept two number and check whether it is amicable number or not.

Amicable number: A pair of numbers, each of which is the sum of the factors of the other (e.g. 220 and 284).

algorithm:
1. **Start**

2. **Input** two numbers `num1` and `num2`.

3. **Calculate** the sum of the factors (proper divisors) of `num1`, store the sum in `sum1`.

4. **Calculate** the sum of the factors (proper divisors) of `num2`, store the sum in `sum2`.

5. **Check** if `sum1` is equal to `num2` and `sum2` is equal to `num1`.

6. If both conditions are true, the numbers are amicable. Otherwise, they are not.

7. **Display** the result.

8. **End**

Java Program
import java.util.Scanner;

public class AmicableNumbers {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input two numbers

System.out.print("enter 1st no.");

int num1 = sc.nextInt();

System.out.print("enter 2nd no.");

int num2 = sc.nextInt();

// Find sum of divisors of num1 and num2

int sum1 = findDivisorSum(num1);

int sum2 = findDivisorSum(num2);

// Check if the numbers are amicable

if (sum1 == num2 && sum2 == num1) {

System.out.println(num1 + " and " + num2 + "are amicable no."); } else {

System.out.println(num1 + " and " + num2 + "are not amicable no."); } }

// Method to find the sum of divisors of a number

public static int findDivisorSum(int num) {

int sum = 0;

for (int I = 1; I <= num / 2; I++) {

if (num % I == 0) {

sum += I; } }

return sum; } }
variable DescriPtion table
| **Variable Name** | **Data Type** | **Description**
|
| `num1` | `int` | First number to check
|
| `num2` | `int` | Second number to check
|
| `sum1` | `int` | Sum of proper divisors of `num1`
|
| `sum2` | `int` | Sum of proper divisors of `num2`
|
| `i` | `int` | Loop variable for calculating divisors
|

outPut:
Program 12
Question:
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 Fascinating Number through the following example:

Consider the number 192

192 x 1 = 192

192 x 2 = 384

192 x 3 = 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.

algorithm:
1. **Start**

2. **Input** a number `num`.

3. **Check** if the number has 3 or more digits. If not, print “Not a Fascinating Number” and terminate.

4. **Multiply** the number by 2 and 3 to get two new numbers: `num2` and `num3`.

5. **Concatenate** the original number, `num2`, and `num3` to form a single string `concatResult`.

6. **Check** if the concatenated result contains all digits from 1 to 9 exactly once, regardless of zeros.

7. If yes, print that the number is a Fascinating Number. Otherwise, print that it is not.

8. **End**

Java Program
import java.util.Scanner;

public class FascinatingNumber {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Input a number

System.out.print("enter a no.");

int num = sc.nextInt();

// Check if the number has at least 3 digits

if (num < 100) {

System.out.println(num + "is not a fascinating no.");

return; // Exit the program }

// Multiply the number by 2 and 3

int num2 = num * 2;

int num3 = num * 3;

// Concatenate the original number, num2, and num3


String concatResult = Integer.toString(num) + Integer.toString(num2) + Integer.toString(num3);

// Check if concatenated string contains all digits 1 to 9 exactly once

boolean isFascinating = true;

for (int I = 1; I <= 9; I++) {

String digit = Integer.toString(I);

if (concatResult.indexOf(digit) == -1 || concatResult.indexOf(digit) != concatResult.lastIndexOf(digit)) {

isFascinating = false;

break; } }

// Output the result

if (isFascinating) {

System.out.println(num + "is a fascinating no.");

} else {

System.out.println(num + "is not a fascinating no."); } }}

variable DescriPtion table


| **Variable Name** | **Data Type** | **Description** |
| `num` | `int` | The input number |
| `num2` | `int` | The number obtained by multiplying
`num` by 2 |
| `num3` | `int` | The number obtained by multiplying
`num` by 3 |
| `concatResult` | `String` | Concatenation of `num`, `num2`, and
`num3` |
| `i` | `int` | Loop variable to check the presence
of digits |

`outPut:
Program 13
Question:
An Evil number is a positive whole number which has even number of 1’s in its binary equivalent. Example: Binary
equivalent of 9 is 1001, which contains even number of 1’s. A few evil numbers are 3, 5, 6, 9…. Design a program to accept a
positive whole number and find the binary equivalent of the number and count the number of 1’s in it and display whether
it is a Evil number or not with an appropriate message. Output the result in format given below:

Example 1

Input: 15

Binary Equivalent: 1111

No. of 1’s: 4

Output: Evil Number

algorithm:
1. **Start**

2. Accept a positive integer `n` as input.

3. Convert the number `n` to its binary equivalent and store it in a string.

4. Count the number of 1’s in the binary string.

5. If the number of 1’s is even, print “Evil Number”.

6. Otherwise, print “Not an Evil Number”.

7. **End**

Java Program:
import java.util.Scanner;

public class EvilNumber {

public static void main(String[] args) {

// Step 1: Create Scanner object to accept input

Scanner sc = new Scanner(System.in);

// Step 2: Accept the positive whole number

System.out.print("input:");

int n = sc.nextInt();

// Step 3: Convert the number to binary

String binary = Integer.toBinaryString(n);

// Step 4: Count the number of 1’s in the binary equivalent

int countOnes = 0;

for (char c : binary.toCharArray()) {

if (c =='1') {

countOnes++; } }

// Step 5: Print the Binary Equivalent

System.out.println("binary equivalent:" + binary);

// Step 6: Print the number of 1’s

System.out.println("no. of 1s" + countOnes);


// Step 7: Determine and display if it is an Evil Number

if (countOnes % 2 == 0) {

System.out.println("Output: evil no.");

} else {

System.out.println("output: not evil no."); }

// Close the scanner

sc.close(); }}

variable DescriPtion table:

variable Data type Description


| `n` | int | Stores the positive whole number
input by the user. |
| `binary` | String | Stores the binary equivalent of the
number `n`. |
| `countOnes` | int | Counts the number of 1’s in the
binary equivalent. |
| `sc` | Scanner | Used for accepting input from the
user. |

outPut:
Program 14
Question:
Write a program in Bluej to accept a sentence from the user. Display the longest palindrome word in the sentence.

I/P – MOM AND DAD WENT TO FIND NITIN

O/P – NITIN

algorithm:
1. **Start**

2. Accept a sentence as input from the user.

3. Split the sentence into individual words.

4. For each word, check if the word is a palindrome.

5. Keep track of the longest palindrome encountered.

6. After checking all words, display the longest palindrome.

7. **End**

Java Program:
import java.util.Scanner;

public class LongestPalindrome {

public static void main(String[] args) {

// Step 1: Create Scanner object to accept input

Scanner sc = new Scanner(System.in);

// Step 2: Accept a sentence from the user

System.out.print("Enter a sentence:");

String sentence = sc.nextLine();

// Step 3: Split the sentence into individual words

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

// Step 4: Initialize variables to keep track of the longest palindrome

String longestPalindrome = "";

// Step 5: Check each word for palindrome and find the longest one

for (String word : words) {

if (isPalindrome(word)) {

if (word.length() > longestPalindrome.length()) {

longestPalindrome = word; } } }

// Step 6: Display the longest palindrome

if (!longestPalindrome.equals("")) {

System.out.println("Longest Palindrome:"+longestPalindrome);

} else {

System.out.println("no palindrome found"); }

// Close the scanner

sc.close(); }
// Function to check if a word is palindrome

public static boolean isPalindrome(String word) {

int length = word.length();

for (int i = 0; i < length / 2; i++) {

if (word.charAt(i) != word.charAt(length -1-i)) {

return false; } }

return true;

outPut:

```

variable DescriPtion table:


| Variable | Data Type | Description
|
| `sentence` | String | Stores the sentence input by the
user. |
| `words` | String[] | Array to store individual words from
the sentence. |
| `longestPalindrome` | String | Stores the longest palindrome found
in the sentence. |
| `sc` | Scanner | Used for accepting input from the
user. |
| `word` | String | Temporary variable to hold the
current word during iteration. |
| `length` | int | Stores the length of the word for
palindrome checking. |
Program 15
Question:
Write a program to declare a square matrix A[][] of order (M x M) where ‘M’ is the number of rows and the number of
columns such that M must be greater than 2 and less than 20. Allow the user to input integers into this matrix. Display
appropriate error message for an invalid input. Perform the following tasks:

(a) Display the input matrix.


(b) Create a mirror image matrix.

© Display the mirror image matrix.

algorithm:
1. **Start**

2. Accept a sentence as input from the user.

3. Split the sentence into individual words using space as the delimiter.

4. Initialize a variable to store the longest palindrome word.

5. For each word in the list:

- Check if the word is a palindrome.

- If it is a palindrome and longer than the current longest palindrome, update the longest palindrome variable.

6. After iterating through all words, display the longest palindrome word.

7. **End**

Java Program:
import java.util.Scanner;

Public class LongestPalindrome {

Public static void main(String[] args) {

// Step 1: Create Scanner object to accept input

Scanner sc = new Scanner(System.in);

// Step 2: Accept a sentence from the user

System.out.print(“Enter a sentence: “);

String sentence = sc.nextLine();

// Step 3: Split the sentence into individual words

String[] words = sentence.split(“ “);

// Step 4: Initialize variables to keep track of the longest palindrome

String longestPalindrome = “”;

// Step 5: Check each word for palindrome and find the longest one

For (String word : words) {

If (isPalindrome(word)) {

If (word.length() > longestPalindrome.length()) {

longestPalindrome = word; } } }

// Step 6: Display the longest palindrome

If (!longestPalindrome.equals(“”)) {

System.out.println(“Longest Palindrome: “ + longestPalindrome);


} else {

System.out.println(“No palindrome word found.”); }

// Close the scanner

Sc.close(); }

// Function to check if a word is palindrome

Public static boolean isPalindrome(String word) {

Int length = word.length();

For (int I = 0; I < length / 2; i++) {

If (word.charAt(i) != word.charAt(length – 1 – i)) {

Return false;

} } Return true; } }

``` variable DescriPtion table:


| Variable | Data Type | Description
|
| `sentence` | String | Stores the sentence input by the
user. |
| `words` | String[] | Array to store individual words from
the sentence. |
| `longestPalindrome` | String | Stores the longest palindrome found
in the sentence. |
| `sc` | Scanner | Used for accepting input from the
user. |
| `word` | String | Temporary variable to hold the
current word during iteration. |
| `length` | int | Stores the length of the word for
palindrome checking. |
-
Program 16
Question:
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.

Sure! Below is a Java program that accepts two positive integers \( m \) and \( n \) where \( m < n \), and then displays the
number of Composite Magic integers between \( m \) and \( n \) (both inclusive) along with the numbers themselves. I’ll
also provide the algorithm and variable description table.

algorithm
1. **Input Validation:**

- Read two integers \( m \) and \( n \) from the user.

- Check if \( m \) is less than \( n \) and both are positive integers.

2. **Composite Number Check:**

- For each number in the range [\( m \), \( n \)], determine if it is composite by counting its factors. A number is composite
if it has more than two factors.

3. **Magic Number Check:**

- For each number in the range, check if it is a magic number by continuously summing its digits until a single-digit result is
obtained. If this result is 1, the number is a magic number.

4. **Count and Display:**

- Count and display all numbers that are both composite and magic.

- Print the frequency of such numbers.

Java Program
import java.util.Scanner;

public class CompositeMagicNumbers { // Method to check if a number is composite

public static boolean isComposite(int num) {

if (num <= 1) return false;

int count = 0;

for (int I = 1; I <= num; I++) {

if (num % I == 0) count++;

if (count > 2) return true; }

return false; } // Method to calculate the sum of digits and check if it is a magic number

public static boolean isMagic(int num) {

while (num >= 10) {


int sum = 0;

while (num > 0) {

sum += num % 10;

num /= 10; }

num = sum; }

return num == 1; } // Main method to execute the program

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); // Input two positive integers m and n

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

int m = scanner.nextInt();

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

int n = scanner.nextInt(); // Validate input

if (m >= n || m <= 0 || n <= 0) {

System.out.println("invalid input, ensure m<n");

return; } // Find and display Composite Magic numbers in the range [m, n]

System.out.println("composite magiuc no. between" + m + " and " + n + ":");

int count = 0;

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

if (isComposite(I) && isMagic(I)) {

System.out.print(I + " ");

count++; } } // Display the frequency

System.out.println("\nfrequency" + count); }}

variable DescriPtion table


| Variable | Description |
| `m` | Lower bound of the range (positive integer). |
| `n` | Upper bound of the range (positive integer). |
| `num` | Number currently being checked (in composite or magic
checks). |
| `count` | Counter for the number of composite magic integers
found. |
| `sum` | Sum of digits during magic number check.
|

outPut
Program 17
Question:
Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or ‘!’ only. Any other character may be
ignored. The words may be separated by more than one blank space and are in UPPER CASE.

Perform the following tasks:

(a) Accept the sentence and reduce all the extra blank space between two words to

A single blank space.

(b) Accept a word from the user which is part of the sentence along with its

Position number and delete the word and display the sentence.

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

Example 1

INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.

WORD TO BE DELETED: IS

WORD POSITION IN THE SENTENCE: 6

OUTPUT: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.

algorithm
1. **Input Handling:**

- Read the full sentence from the user.

- Read the word to be deleted and its position in the sentence.

2. **Reduce Spaces:**

- Remove leading and trailing spaces from the sentence.

- Replace all multiple spaces between words with a single space.

3. **Delete Word:**

- Split the sentence into individual words.

- Remove the word at the specified position (1-based index).

- Reconstruct the sentence with remaining words.

4. **Output:**

- Display the modified sentence with reduced spaces and the specified word removed.

Java Program
import java.util.Scanner;

public class SentenceEditor {

// Method to reduce multiple spaces to a single space

public static String reduceSpaces(String sentence) {

// Trim leading and trailing spaces and replace multiple spaces with a single space

return sentence.trim().replaceAll("\s", " "); }

// Method to delete a word from the sentence based on its position

public static String deleteWord(String sentence, String wordToDelete, int position) {

// Split the sentence into words


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

StringBuilder result = new StringBuilder();

// Loop through words and append to result except the word to be deleted at the specified position

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

if (I != position -1) { // Convert 1-based position to 0-based index

result.append(words[I]).append(" "); } }

// Return the final sentence with reduced spaces and trimmed

return reduceSpaces(result.toString()); }

// Main method to execute the program

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); // Input sentence

System.out.print("enter the sentence:");

String sentence = scanner.nextLine(); // Input word to be deleted and its position

System.out.print("enter the word to be deleted");

String wordToDelete = scanner.nextLine().toUpperCase();

System.out.print("enter the position of the word to be deleted");

int position = scanner.nextInt(); // Reduce extra spaces in the sentence

sentence = reduceSpaces(sentence); // Delete the specified word from the sentence

String result = deleteWord(sentence, wordToDelete, position); // Output the final sentence

System.out.println("output:" + result);

}}

```

### variable DescriPtion table


| Variable | Description |
| `sentence` | The input sentence from the user. |
| `wordToDelete` | The word to be deleted from the sentence. |
| `position` | The position number (1-based index) of the word to be
deleted. |
| `words` | Array of words obtained by splitting the sentence. |
| `result` | StringBuilder used to construct the final sentence after
deletion. |

outPut:
Program 18
Question:
A game of throwing dice is played between two players. Each player throws a dice unless his/her score adds up to 20. The
player getting score 20 in the minimum number of throws is declared the winner. Define a class Game with the following
specifications:

Data Members: Name, player number

Member methods:

i) To accept the details of the player


ii) To compute the number of tries by each player to get score 20
iii) To display the result

rite a main method to create an object of a class and call the above member methods

algorithm
1. **Define the `Game` class** with data members for player name and player number.

2. **Define methods**:

- `acceptDetails()`: To input the player's name and player number.

- `computeTries()`: To simulate dice rolls and calculate the number of tries required to reach a score of 20.

- `displayResult()`: To display the number of tries required for the player to reach the score of 20.

3. **In the `main` method**:

- Create objects for two players.

- Call `acceptDetails()` for both players to input their details.

- Call `computeTries()` to determine the number of tries each player needs.

- Call `displayResult()` to display the results.

Java Program
import java.util.Random;

import java.util.Scanner;

class Game { // Data Members

private String name;

private int playerNumber;

private int tries; // Method to accept player details

public void acceptDetails() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter player name: ");

name = scanner.nextLine();

System.out.print("Enter player number: ");

playerNumber = scanner.nextInt(); } // Method to compute the number of tries to reach a score of 20

public void computeTries() {

Random random = new Random();

int score = 0;
tries = 0;

while (score < 20) {

int roll = random.nextInt(6) + 1; // Dice roll (1 to 6)

score += roll;

tries++; } } // Method to display the result

public void displayResult() {

System.out.println("Player " + playerNumber + " (" + name + ") took " + tries + " tries to reach a score of 20."); }

public static void main(String[] args) { // Create objects for two players

Game player1 = new Game();

Game player2 = new Game(); // Accept details for player 1

System.out.println("Enter details for Player 1:");

player1.acceptDetails();

player1.computeTries(); // Accept details for player 2

System.out.println("Enter details for Player 2:");

player2.acceptDetails();

player2.computeTries(); // Display results

System.out.println("\nResults:");

player1.displayResult();

player2.displayResult();

`` variable DescriPtion table


| Variable Name | Description |
| `name` | Stores the name of the player. |
| `playerNumber` | Stores the number assigned to the player. |
| `tries` | Stores the number of dice rolls needed to reach a score
of 20. |

outPut:
Program 19
Question:
In a class, the Mathematics teacher gave an assignment to her students to Find the area of a scalene triangle. However, she
writes a program taking the length of the sides as input and calculates its area. Further, she enters the answers obtained by
all 40 students in a Single Dimensional Array The program compares the area calculated by the teacher and the answers
stored in the array to display the number of students who have given the correct answer. Write the program in Java what
the teacher would write to solve the purpose.

algorithm
1. **Input the sides of the triangle**:

- Read the lengths of the three sides of the scalene triangle from the user.

2. **Calculate the area of the triangle**:

- Use Heron’s formula to compute the area:

- Compute the semi-perimeter \( s \) as \((a + b + c) / 2\).

- Use the formula \( \text{Area} = \sqrt{s \times (s – a) \times (s – b) \times (s – c)} \) to find the area.

3. **Input the students’ answers**:

- Read 40 answers from the user and store them in a single-dimensional array.

4. **Compare each student’s answer**:

- Check each answer against the calculated area and count how many are correct.

5. **Display the result**:

- Print the number of students who provided the correct answer.

Java Program
import java.util.Scanner;

public class TriangleAreaChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); // Input lengths of the sides of the triangle

System.out.print("enter length of side a:");

double a = scanner.nextDouble();

System.out.print("enter length of side b:");

double b = scanner.nextDouble();

System.out.print("enter length of side c:");

double c = scanner.nextDouble(); // Calculate the area using Heron’s formula

double s = (a + b + c) / 2;

double area = Math.sqrt(s * (s-a) * (s-b) * (s - c)); // Input student answers

double[] studentAnswers = new double[40];

System.out.println("Enter the answers provided by 40 students");

for (int I = 0; I < studentAnswers.length; I++) {

studentAnswers[I] = scanner.nextDouble(); } // Compare answers and count the correct ones

int correctCount = 0;

for (double answer : studentAnswers) { // Using a tolerance to account for floating-point precision issues
if (Math.abs(answer - area) < 0.01) {

correctCount++; } } // Display the result

System.out.println("Number of students who gave correct answer" + correctCount);

scanner.close(); }}```

variable DescriPtion table


| Variable Name | Description |
| `a`, `b`, `c` | Lengths of the sides of the triangle. |
| `s` | Semi-perimeter of the triangle. |
| `area` | Computed area of the triangle. |
| `studentAnswers[]` | Array storing the answers provided by the students. |
| `correctCount` | Number of students who provided the correct answer. |
| `n` | Total number of students (constant, 40). |
outPut:
Program 20
Question:
A class NumSort enables the user to sort the digits of an integer number.

Example,

Sample Input: 62943

Sample Output: 96432 (after sorting in descending order of its digits)

Some of the members of the class are given below:

Class name

: NumSort

Data members/Instance variables:

Num: to store the integer number

Arr: array to store the digits of the number

Member functions/methods:

NumSort(int n) : parameterised constructor to initialise the data member num= of the number and stores in the array

Void extract_digit(): extract the digit

Void sort(): sorts the array elements in descending order by using standard sorting technique

Void display(): displays the original number along with the elements of the sorted array with an appropriate message

Define the class NumSort giving details of the constructor (int), void extract_digit(), void sort() and void display(). Define the
main () function to create an object and call the functions accordingly to enable the task

algorithm
1. **Define the `NumSort` class** with the following:

- **Data Members**:

- `num`: An integer to store the number.

- `arr`: An array to store the digits of the number.

- **Constructor**:

- `NumSort(int n)`: Initializes `num` and stores the digits of the number in `arr`.

- **Methods**:

- `void extract_digit()`: Extracts digits from `num` and stores them in `arr`.

- `void sort()`: Sorts `arr` in descending order.

- `void display()`: Displays the original number and the sorted digits.

2. **Define the `main` method**:

- Create an object of `NumSort`.

- Call the `extract_digit()`, `sort()`, and `display()` methods to perform the operations and display the results.

Java Program:
import java.util.Scanner;

class NumSort {

private int num;


private int[] arr;

private int size; // Parameterized constructor to initialize the number and extract its digits

public NumSort(int n) {

num = n;

size = String.valueOf(num).length(); // Determine the number of digits

arr = new int[size]; // Create an array to store digits

// Method to extract digits and store them in the array

public void extract_digit() {

int temp = num;

for (int i = size - 1; i >= 0; i--) {

arr[i] = temp % 10;

temp /= 10;

} }

// Method to sort the array elements in descending order

public void sort() {

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

if (arr[j] < arr[j + 1]) {

// Swap arr[j] and arr[j+1]

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

} } } }

// Method to display the original number and the sorted digits

public void display() {

System.out.println("Original Number: " + num);

System.out.print("Digits after sorting in descending order: ");

for (int digit : arr) {

System.out.print(digit);

} System.out.println();

// Main method to create an object and invoke methods

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter an integer number: ");

int n = sc.nextInt();

// Create an object of NumSort


NumSort obj = new NumSort(n);

// Call the methods

obj.extract_digit();

obj.sort();

obj.display();

sc.close();

variable DescriPtion table


| Variable Name | Description |
| `num` | Stores the integer number provided by the user. |
| `arr` | Array to store the digits of the number. |
| `n` | The number passed to the constructor. |
| `temp` | Temporary variable used for swapping elements in
sorting. |

outPut:

You might also like