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

Write A Program in Java To Input A Number and Check Whether It Is A Fascinating Number or Not-1

Uploaded by

fake Fake
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
268 views

Write A Program in Java To Input A Number and Check Whether It Is A Fascinating Number or Not-1

Uploaded by

fake Fake
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Program 1.

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.

import java.util.Scanner;

public class KboatFascinatingNumber


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to check: ");
int num = in.nextInt();

if (num < 100) {


System.out.println(num + " is not a Fascinating Number");
return;
}

int num2 = num * 2;


int num3 = num * 3;

boolean isFascinating = true;


String str = "" + num + num2 + num3;
for (char i = '1'; i <= '9'; i++) {
int idx1 = str.indexOf(i);
int idx2 = str.lastIndexOf(i);
if (idx1 == -1 || idx1 != idx2) {
isFascinating = false;
break;
Output
if (isFascinating)

System.out.println(num + " is a Fascinating Number");

else
System.out.println(num + " is not a Fascinating Number");
}
}

Algorithm for Checking a Fascinating Number


1. **Input Handling**:
Read the number from the user input.
If the number is less than 100, print that it is not a fascinating number and exit.
2. **Generate Multiples**:
Calculate the second multiple of the number (num * 2).
Calculate the third multiple of the number (num * 3).
3. **Concatenate Strings**:
Convert the number, its second multiple, and its third multiple to strings.
Concatenate these strings together.
4. **Check for Fascination**:
Initialize a boolean flag `isFascinating` to true.
Loop through characters '1' to '9'.
For each character, check if it appears exactly once in the concatenated string.
If any character is missing or appears more than once, set `isFascinating` to false and break the
loop.
5. **Output Result**:
If `isFascinating` is true, print that the number is a fascinating number.Otherwise, print that the
number is not a fascinating number.This algorithm outlines the step-by-step approach taken by
the Java program to determine if a given number is a fascinating number.
Program 2.
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 ………. are 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.
import java.util.Scanner;

public class KboatSmithNumber


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

if (n <= 0) {
System.out.println(n + " is not a Smith Number.");
return;
}

boolean isComposite = false;


for (int i = 2; i < n; i++) {
if (n % i == 0) {
isComposite = true;
break;
}
}

if (isComposite && n != 1) {
int sumDigits = 0;
int t = n;
while (t != 0) {
int d = t % 10;
sumDigits += d;
t /= 10;
}

int sumPrimeDigits = 0;
t = n;
for(int i = 2; i < t; i++) {
Output
while(t % i == 0) {

t /= i;
int temp = i;
while (temp != 0) {
int d = temp % 10;
sumPrimeDigits += d;
temp /= 10;
}
}
}

if(t > 2) {
while (t != 0) {
int d = t % 10;
sumPrimeDigits += d;
t /= 10;
}
}

if (sumPrimeDigits == sumDigits)
System.out.println(n + " is a Smith Number.");
else
System.out.println(n + " is not a Smith Number.");
}
else {
System.out.println(n + " is not a Smith Number.");
}
}
}
Algorithm for Checking a Smith Number
1. **Input Handling**:
- Read the number `n` from the user input.
- If `n` is less than or equal to 0, print that it is not a Smith Number and exit.
2. **Check for Composite Number**:
- Initialize a boolean flag `isComposite` to false.
- Loop from 2 to `n-1` to check if `n` is divisible by any number. If it is, set `isComposite` to true and
break the loop.
- If `isComposite` is false or `n` is 1, print that it is not a Smith Number and exit.
3. **Calculate Digit Sum of `n`**:
- Initialize `sumDigits` to 0.
- While `n` is not 0:
- Add the last digit of `n` to `sumDigits`.
- Remove the last digit from `n`.
4. **Calculate Digit Sum of Prime Factors of `n`**:
- Initialize `sumPrimeDigits` to 0.
- For each integer `i` from 2 to the original value of `n`:
- While `n` is divisible by `i`:
`.
- Divide `n` by `i`.
- For each digit in `i`, add it to `sumPrimeDigits
- If `n` is greater than 2 after the loop, add the digits of `n` to `sumPrimeDigits`.
5. **Compare Sums**:
- If `sumPrimeDigits` equals `sumDigits`, print that `n` is a Smith Number.
- Otherwise, print that `n` is not a Smith Number.This algorithm outlines the step-by-step approach
taken by the Java program to determine if a given number is a Smith Number.
Program 3.
Write a menu driven program to accept a number from the user and check
whether it is a Prime number or an Automorphic number.

(a) Prime number: (A number is said to be prime, if it is only divisible by 1 and


itself)

Example: 3,5,7,11

(b) Automorphic number: (Automorphic number is the number which is


contained in the last digit(s) of its square.)

Example: 25 is an Automorphic number as its square is 625 and 25 is present as


the last two digits.
SOULTION
import java.util.Scanner;

public class KboatPrimeAutomorphic


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Prime number");
System.out.println("2. Automorphic number");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
System.out.print("Enter number: ");
int num = in.nextInt();

switch (choice) {
case 1:
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
if (c == 2)
System.out.println(num + " is Prime");
else
System.out.println(num + " is not Prime");
break;

case 2:
int numCopy = num;
int sq = num * num;
Output
int d = 0;

/*
* Count the number of
* digits in num
*/
while(num > 0) {
d++;
num /= 10;
}

/*
* Extract the last d digits
* from square of num
*/
int ld = (int)(sq % Math.pow(10, d));

if (ld == numCopy)
System.out.println(numCopy + " is automorphic");
else
System.out.println(numCopy + " is not automorphic");
break;

default:
System.out.println("Incorrect Choice");
break;
}
}
}

### Algorithm for Checking Prime and Automorphic Numbers


1. **Input Handling**:
- Display options for the user to choose:
1. Prime number
2. Automorphic number
- Read the user's choice.
- Read the number `num` from the user input.
2. **Choice Handling**:
- **Case 1**: Check if `num` is a prime number.
- **Case 2**: Check if `num` is an automorphic number.
3. **Prime Number Check**:
- Initialize a counter `c` to 0.
- Loop from 1 to `num`:
- If `num` is divisible by the current loop index, increment `c`.
- If `c` is exactly 2, print that `num` is prime.
- Otherwise, print that `num` is not prime.
4. **Automorphic Number Check**:
- Copy the value of `num` to `numCopy`.
- Calculate the square of `num` and store it in `sq`.
- Initialize a counter `d` to 0.
- Count the number of digits in `num` by looping until `num` is 0, incrementing `d` and dividing `num`
by 10 each time.
- Extract the last `d` digits from `sq` by calculating `sq % 10^d`.
- If the extracted digits are equal to `numCopy`, print that `numCopy` is automorphic.
- Otherwise, print that `numCopy` is not automorphic.
5. **Default Case**:
- If the user input is not 1 or 2, print "Incorrect Choice".

This algorithm outlines the step-by-step approach taken by the Java program to
determine if a given number is either a prime number or an automorphic number
based on the user's choice.
Output
Program 4.
A prime number is said to be 'Twisted Prime', if the new number obtained after
reversing the digits is also a prime number. Write a program to accept a number
and check whether the number is 'Twisted Prime' or not.
Sample Input: 167
Sample Output: 761
167 is a 'Twisted Prime'.
Solution.
import java.util.Scanner;

public class KboatTwistedPrime


{
public void twistedPrimeCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();

if (num == 1) {
System.out.println(num + " is not a twisted prime number");
}
else {
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {

int t = num;
int revNum = 0;

while (t != 0) {
int digit = t % 10;
t /= 10;
revNum = revNum * 10 + digit;
}

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


if (revNum % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime)
System.out.println(num + " is a twisted prime number");
else
System.out.println(num + " is not a twisted prime number");
}

}
}
Here's the algorithm for checking if a number is a Twisted Prime
Number:
1. **Input**:
- Prompt the user to enter a number.
2. **Initial Check**:
- If the number is 1, it is not a twisted prime number. Print a message and exit.
3. **Check if the Number is Prime**:
- Initialize a boolean flag `isPrime` to `true`.
- Loop through the numbers from 2 to `num / 2`.
- If the number is divisible by any of these numbers, set `isPrime` to `false` and break the loop.
- If `isPrime` remains `true`, proceed to the next step. Otherwise, print that the number is not a
twisted prime number and exit.
4. **Reverse the Number**:
- Initialize `revNum` to 0.
- While the number is not 0:
- Extract the last digit of the number.
- Append the digit to `revNum`.
- Remove the last digit from the number.
5. **Check if the Reversed Number is Prime**:
- If the number is still prime (i.e., `isPrime` is `true`):
- Loop through the numbers from 2 to `revNum / 2`.
- If the reversed number is divisible by any of these numbers, set `isPrime` to `false` and break the
loop.- If `isPrime` remains `true`, print that the number is a twisted prime number. Otherwise, print that
the number is not a twisted prime number.

This algorithm ensures that both the original number and its reversed version are prime to determine if
it is a twisted prime number.
Output
Program 5.
Write a program to input a number and display the new number after reversing
the digits of the original number. The program also displays the absolute
difference between the original number and the reversed number.

Sample Input: 194


Sample Output: 491
Absolute Difference= 297

Soltion.

import java.util.Scanner;

public class KboatDigitReverse


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);


System.out.print("Enter Number: ");
int orgNum = in.nextInt();

int copyNum = orgNum;


int revNum = 0;

while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}

int diff = revNum - orgNum;


System.out.println("Reversed Number = " + revNum);
System.out.println("Absolute Difference = " + Math.abs(diff));
}
}

.
Sure, here's the algorithm for the `KboatDigitReverse` program that
reverses a given integer and calculates the absolute difference between
the original and the reversed number:
1. **Initialize Scanner:**
- Create a `Scanner` object to read input from the user.
2. **Read Input:**
- Prompt the user to enter a number.
Store the input number in a variable `orgNum`.
3. **Initialize Variables:**
- Create a copy of the original number and store it in `copyNum`.
- Initialize `revNum` to 0, which will hold the reversed number.
4. **Reverse the Number:**
- While `copyNum` is not zero:
- Extract the last digit of `copyNum` using the modulus operator (`copyNum % 10`) and store it in
`digit`.
- Remove the last digit from `copyNum` by dividing it by 10 (`copyNum /= 10`).
- Update `revNum` by multiplying it by 10 and adding `digit` to it.
5. **Calculate the Difference:**
- Calculate the difference between the reversed number (`revNum`) and the original number
(`orgNum`) and store it in `diff`.
6. **Print Results:**
- Print the reversed number.
- Print the absolute value of the difference using `Math.abs(diff)`.

This algorithm effectively captures the process described in your Java program for reversing a number
and finding the absolute difference between the original and the reversed number
Output
Program 6.
Write a program to input a natural number less than 1000 and display it in
words. Test your program on the sample data and some random data.
Example –
INPUT: 29
OUTPUT: TWENTY NINE
INPUT: 17001 zOUTPUT: OUT OF RANGE
INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN
INPUT: 500
OUTPUT: FIVE HUNDRED
SOLUTION.
import java.util.*;

class ISCprac2011q01 {
public static void main(String args[]) throws InputMismatchException {
Scanner scan = new Scanner(System.in);
int n;

System.out.println("Enter a number less than 1000");


n = scan.nextInt();

if (n >= 1000) {
System.out.println("OUT OF RANGE");
} else {
String result = "";
int a, b, c;
String ones[] = {"one", "two", "three", "four", "five", "six",
"seven", "eight", "nine"};
String teens[] = {"eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
String tens[] = {"ten", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};

if (n >= 100) {
a = n / 100;
result = ones[a - 1] + " hundred";
n = n % 100;
if (n != 0) {
result += " and ";
}
}

if (n >= 20) {
a = n / 10;
b = n % 10;
result += tens[a - 1];
if (b != 0) {
result += " " + ones[b - 1];
}
} else if (n >= 11 && n <= 19) {
result += teens[n - 11];
} else if (n == 10 || (n < 10 && n > 0)) {
if (n == 10) {
result += tens[0];
} else {
result += ones[n - 1];
}
}

System.out.println("\n" + result.toUpperCase());
}
scan.close();
}
}

Here's the algorithm for the program that converts a number less than
1000 into its English words representation:
1. **Input Reading:**
- Read the input number `n` from the user.
- If `n` is greater than or equal to 1000, print "OUT OF RANGE" and terminate the program.
2. **Initialization:**
- Initialize arrays `ones`, `teens`, and `tens` to store the English words for digits, teen numbers, and
tens respectively.
- Initialize an empty string `result` to store the final English words representation.
3. **Handling Hundreds Place:**
- If `n` is greater than or equal to 100:
- Calculate the hundreds digit `a` as `n / 100`.
- Append the corresponding word from the `ones` array followed by " hundred" to `result`.
- Update `n` to `n % 100`.
- If the updated `n` is not zero, append " and " to `result`.
4. **Handling Tens and Ones Places:**
- If `n` is between 20 and 99 (inclusive):
- Calculate the tens digit `a` as `n / 10` and the ones digit `b` as `n % 10`.
- Append the corresponding word from the `tens` array to `result`.
- If `b` is not zero, append the corresponding word from the `ones` array to `result`.
- If `n` is between 11 and 19 (inclusive):
- Append the corresponding word from the `teens` array to `result`.
- If `n` is 10 or between 1 and 9 (inclusive):
- If `n` is 10, append the corresponding word from the `tens` array.
- Otherwise, append the corresponding word from the `ones` array.
5. **Output the Result:**
- Print the `result` string in uppercase.
This algorithm ensures that the number is correctly converted into words, handling various edge cases and
ensuring proper formatting.
Output
Program 7.
Encryption is a technique of coding messages to maintain their secrecy. A String
array of size 'n' where 'n' is greater than 1 and less than 10, stores single
sentences (each sentence ends with a full stop) in each row of the array.
Write a program to accept the size of the array.
Display an appropriate message if the size is not satisfying the given condition.
Define a string array of the inputted size and fill it with sentences row-wise.
Change the sentence of the odd rows with an encryption of two characters ahead
of the original character. Also change the sentence of the even rows by storing
the sentence in reverse order.
SOULTION.
import java.io.*;

class Question2 {
public static void main() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int nos;
System.out.print("Enter number of sentences: ");
nos = Integer.parseInt(br.readLine());

if (nos < 1 || nos >= 10) {


System.out.println("\nInvalid Entry");
} else {
String[] s = new String[nos];

System.out.println("\nEnter " + nos + " sentences:");


for (int i = 0; i < nos; i++) {
s[i] = br.readLine().toUpperCase();
}

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


String t = "";
s[i] = " " + s[i]; // add a blank space before each sentence
int l = s[i].length();

if (i % 2 == 0) {
// Shift letters by 2 positions for even indexed sentences
for (int j = 0; j < l; j++) {
int ch = s[i].charAt(j); // store the ASCII code of the
character
if (ch != 32 && ch != 46) { // if not a space or a period
ch += 2; // shift the letter two spaces
if (ch > 90) { // to maintain cyclic order
ch -= 26; // subtract 26
}
}
t += (char) ch; // convert to character and add to a
temporary string
}
s[i] = t.trim(); // remove leading or trailing spaces
} else {
// Reverse words for odd indexed sentences
int p = l - 1;
for (int j = l - 1; j >= 0; j--) {
char ch = s[i].charAt(j);
if (ch == ' ') {
t += s[i].substring(j + 1, p + 1) + " "; // add the
extracted word and a space
p = j;
}
}
t += s[i].substring(0, p + 1) + "."; // add the last word and a
period
s[i] = t.trim(); // remove leading or trailing spaces
}
}

System.out.println("\nOUTPUT:");
for (int i = 0; i < nos; i++) {
System.out.println(s[i]);
}
}
}
}
### Algorithm for the Java Program
1. **Initialize Input Reader**:
- Create a `BufferedReader` object to read input from the user.
2. **Read Number of Sentences**:
- Prompt the user to enter the number of sentences (`nos`).
- Read and parse the input as an integer.
3. **Validate Input**:
- Check if the number of sentences (`nos`) is within the valid range (1 to 9).
- If not, print "Invalid Entry" and terminate the program.
4. **Read Sentences**:
- Initialize an array `s` of size `nos` to store the sentences.
- Prompt the user to enter the sentences.
- Read each sentence, convert it to uppercase, and store it in the array `s`.
5. **Process Each Sentence**:
- Loop through each sentence in the array `s`:
- Prepend a space to the sentence.
- Determine the length (`l`) of the sentence.
- Initialize an empty string `t` to store the transformed sentence.

- **Even Indexed Sentences**:


- Loop through each character in the sentence:
- If the character is not a space (ASCII 32) or a period (ASCII 46), shift the ASCII value of the
character by 2 positions.
- If the shifted ASCII value exceeds 'Z' (ASCII 90), wrap around by subtracting 26.
- Convert the ASCII value back to a character and append it to `t`.
- Trim leading or trailing spaces from `t` and update the sentence in `s`.
- **Odd Indexed Sentences**:
- Reverse the order of words in the sentence:
- Loop through the sentence from the end to the beginning.
- When a space is encountered, extract the word following the space and append it to `t`.
- Update the position pointer (`p`) to the current position.
- Append the last word and a period to `t`.
- Trim leading or trailing spaces from `t` and update the sentence in `s`.
6. **Output Transformed Sentences**:
- Print "OUTPUT:".
- Loop through the array `s` and print each transformed sentence.

This algorithm effectively transforms each sentence according to the specified rules, handling
both character shifting and word reversing based on the sentence index.
Output
Program 8.
A bank intends to design a program to display the denomination of an input
amount, upto 5 digits. The available denomination with the bank are of rupees
1000, 500, 100, 50, 20, 10 ,5, 2 and 1.

Design a program to accept the amount from the user and display the break-up
in descending order of denominations. (i,e preference should be given to the
highest denomination available) along with the total number of notes. [Note: only
the denomination used should be displayed]. Also print the amount in words
according to the digits.
SOLUTION.
import java.util.*;

class Question3 {
public static void main() {
Scanner scan = new Scanner(System.in);
int amt;

try {
System.out.print("Enter a five-digit amount : ");
amt = scan.nextInt();

if (amt < 10000 || amt > 99999) {


System.out.println("INVALID AMOUNT.");
} else {
int[] denominations = {1000, 500, 100, 50, 20, 10, 5, 2, 1};
int p, r, b, t;
p = amt;

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


t = amt / denominations[i];
if (t != 0) {
System.out.println(denominations[i] + "X" + t + "=" +
(t * denominations[i]));
amt = amt % denominations[i];
}
}

String[] ones = {"ONE", "TWO", "THREE", "FOUR", "FIVE",


"SIX", "SEVEN", "EIGHT", "NINE"};
String[] tens = {"TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY",
"SIXTY", "SEVENTY", "EIGHTY", "NINETY"};
String[] teens = {"ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN",
"FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};

// Convert number to words


int reverseAmt = 0;
while (p > 0) {
reverseAmt = reverseAmt * 10 + p % 10;
p /= 10;
}

while (reverseAmt > 0) {


b = reverseAmt % 10;
if (b == 1 && reverseAmt / 10 > 0) {
reverseAmt /= 10;
b = reverseAmt % 10;
System.out.print(teens[b - 1] + " ");
} else if (b == 0) {
reverseAmt /= 10;
continue;
} else if (b > 1) {
System.out.print(tens[b - 1] + " ");
} else {
System.out.print(ones[b - 1] + " ");
}
reverseAmt /= 10;
}
}
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT.");
} finally {
scan.close();
}
}
}
here is the algorithm for the provided Java program:
1. **Input Handling**
1.1. Initialize a Scanner object for user input.
1.2. Prompt the user to enter a five-digit amount.
1.3. Read the input amount.
2. **Validation**
2.1. Check if the input amount is a five-digit number (between 10000 and 99999).
2.2. If the amount is not within the valid range, print "INVALID AMOUNT." and exit.
3. **Denomination Calculation**
3.1. Define an array of denominations: `{1000, 500, 100, 50, 20, 10, 5, 2, 1}`.
3.2. Initialize a variable `p` with the input amount for later use.
3.3. Loop through the denominations array:
3.3.1. Calculate how many times the denomination can be divided into the amount.
3.3.2. If the result is not zero, print the denomination, the multiplier, and the product.
3.3.3. Update the amount to the remainder after dividing by the denomination.
4. **Number to Words Conversion**
4.1. Define arrays for single digits (`ones`), tens (`tens`), and teens (`teens`).
4.2. Reverse the input amount to simplify word conversion:
4.2.1. Initialize a variable `reverseAmt` to zero.
4.2.2. While the original amount `p` is greater than zero:
4.2.2.1. Update `reverseAmt` by appending the last digit of `p`.
4.2.2.2. Remove the last digit from `p`.
4.3. Convert the reversed number to words:
4.3.1. While `reverseAmt` is greater than zero:
4.3.1.1. Extract the last digit `b` of `reverseAmt`.
4.3.1.2. If `b` is 1 and the next digit exists, handle it as a teen number.
4.3.1.3. Otherwise, handle it as a tens or ones digit.
4.3.1.4. Print the corresponding word in uppercase.
4.3.1.5. Remove the last digit from `reverseAmt`.
5. **Exception Handling**
5.1. If an `InputMismatchException` occurs, print "INVALID INPUT."
5.2. Close the Scanner object to avoid resource leaks.
Output
Program 9.
Given the two positive integers p and q, where p < q. Write a program to
determine how many kaprekar numbers are there in the range between 'p' and
'q'(both inclusive) and output them. About 'kaprekar' number:

A positive whole number 'n' that has 'd' number of digits is squared and split
into 2 pieces, a right hand piece that has 'd' digits and a left hand piece that has
remaining 'd' or 'd-1' digits. If sum of the pieces is equal to the number then it's a
kaprekar number.
SOLUTION.
import java.util.*;

class Question4 {
public static void main() {
Scanner scan = new Scanner(System.in);

try {
System.out.println("Enter the range: ");
int p = scan.nextInt();
int q = scan.nextInt();

int d, n, a, b, s, freq;
freq = 0; // to find the frequency of Kaprekar numbers

System.out.println("The Kaprekar numbers are: ");

for (int i = p; i <= q; i++) {


n = i;
d = 0; // to store the number of digits

// count the number of digits in the number


int temp = n;
while (temp > 0) {
d++;
temp /= 10;
}

s = i * i; // find the square of the number

// extract 'd' digits from the right of the square of the


number
a = s % (int) Math.pow(10, d);

// extract the remaining digits from the left of the square


of the number
b = s / (int) Math.pow(10, d);

// Check if the two parts add up to the original number i.e.,


condition for Kaprekar number
if (a + b == i) {
System.out.print(i + " ");
freq++;
}
}

System.out.println("\nFREQUENCY OF KAPREKAR NUMBERS IS: " +


freq);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT.");
} finally {
scan.close();
}
}
}

Here is the algorithm for the given Java program to find Kaprekar
numbers within a specified range:

1. **Input Handling**
1.1. Initialize a `Scanner` object for user input.
1.2. Prompt the user to enter the range (two integers).
1.3. Read the input values `p` and `q`.
2. **Initialization**
2.1. Initialize a variable `freq` to `0` to keep track of the frequency of Kaprekar numbers.
3. **Finding Kaprekar Numbers**
3.1. Print the message "The Kaprekar numbers are: ".
3.2. Loop through each number `i` from `p` to `q`:
3.2.1. Initialize `n` with the value of `i`.
3.2.2. Initialize `d` to `0` to count the number of digits in `n`.
4. **Counting Digits**
4.1. Copy `n` to a temporary variable `temp`.
4.2. While `temp` is greater than `0`:
4.2.1. Increment `d` by `1`.
4.2.2. Divide `temp` by `10` to remove the last digit.
5. **Calculating Square**
5.1. Calculate the square of `i` and store it in `s`.
6. **Extracting Parts**
6.1. Extract the rightmost `d` digits of `s` and store it in `a`.
6.2. Extract the remaining leftmost digits of `s` and store it in `b`.
7. **Kaprekar Number Check**
7.1. Check if `a + b` equals `i`:
7.1.1. If true, print `i` and increment `freq` by `1`.
8. **Output Frequency**
8.1. Print the message "FREQUENCY OF KAPREKAR NUMBERS IS: " followed by the value of `freq`.
9. **Exception Handling**
9.1. If an `InputMismatchException` occurs, print "INVALID INPUT."
10. **Resource Management**
10.1. Close the `Scanner` object to avoid resource leaks.

This algorithm outlines the steps taken by the program to identify Kaprekar numbers in a given
range and count their frequency, with appropriate input handling and exception management.
Output
Program 10.
Write a program to create an array of n integers and display the frequency of
each element of the array.
SOULTION.
import java.util.*;

class Question7 {
public static void main() {
Scanner sc = new Scanner(System.in);

try {
System.out.println("Enter the number of terms: ");
int n = sc.nextInt();
int[] a = new int[n];

System.out.println("Enter " + n + " integers");


for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}

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


if (a[i] == 0) continue; // Skip if the number is already
processed and marked as zero

int f = 1; // Frequency of the current element


for (int j = i + 1; j < n; j++) {
if (a[i] == a[j] && a[j] != 0) {
f++;
a[j] = 0; // Mark as zero to avoid counting again
}
}
System.out.println("Frequency of " + a[i] + " : " + f);
}
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT.");
} finally {
sc.close();
}
}
}

Here is the algorithm for the given Java program:

1. **Initialization:**
- Create a `Scanner` object to read input from the user.
2. **Input Handling:**
- Prompt the user to enter the number of terms.
- Read the number of terms (`n`) and store it in an integer variable.
- Create an integer array `a` of size `n` to store the input integers.
3. **Read Array Elements:**
- Prompt the user to enter `n` integers.
- Use a loop to read `n` integers from the user and store them in the array `a`.
4. **Frequency Counting:**
- Iterate over the array `a` using an outer loop from index `i = 0` to `n-1`.
- For each element at index `i`, check if it is zero:
- If it is zero, skip the element (this means it has been processed already).
- If it is not zero, initialize a frequency counter `f` to 1.
- Use an inner loop from index `j = i + 1` to `n-1` to count occurrences of the element:
- If the element at `a[j]` is equal to `a[i]` and is not zero, increment the frequency counter `f` and
mark `a[j]` as zero to avoid counting it again in future iterations.
5. **Output Frequency:**
- After processing each element in the outer loop, print the frequency of the element `a[i]`.
6. **Exception Handling:**
- Catch any `InputMismatchException` that occurs if the user enters invalid input and print "INVALID
INPUT."
Output
Program 11.
Write a program to create an array of n integers and sort the array in
ascending order using Insertion sort technique.
SOLUTION.
import java.util.*;

class Question8 {
public static void main()throws InputMismatchException{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the size of the array: "); int n=sc.nextInt();

int a[]=new int[n];


int i,j,k;

System.out.println("Enter "+n+" integers:");

for(i=0;i<n;i++){ a[i]=sc.nextInt();
}

for(i=1;i<n;i++){ k=a[i];
for(j=i-1;j>=0 && k<a[j];j--){ //Shift the elements to the right until
the condition is false a[j+1]=a[j];
}
a[j+1]=k; //Store the element in the proper
position of the array
}

System.out.println("Array in ascending order: ");

for(i=0;i<n;i++){
System.out.print(a[i]+" ");
}
}
}
Here's the algorithm for the given Java program, which sorts an array of integers
using the insertion sort algorithm:

1. **Initialization:**
- Create a `Scanner` object to read input from the user.
2. **Input Handling:**
- Prompt the user to enter the size of the array.
- Read the size (`n`) and store it in an integer variable.
- Create an integer array `a` of size `n` to store the input integers.
3. **Array Population:**
- Prompt the user to enter `n` integers.
- Read each integer and store it in the array `a`.
4. **Insertion Sort:**
- Iterate through the array starting from the second element (index 1) to the last element (index `n-1`):
1. Assign the current element (`a[i]`) to a temporary variable `k`.
2. Initialize `j` to the index of the previous element (`i-1`).
3. Shift elements of the array that are greater than `k` to the right until the correct position for `k` is
found:
- While `j` is greater than or equal to 0 and `a[j]` is greater than `k`, do the following:
- Move `a[j]` to the position `j+1`.
- Decrement `j` by 1.
4. Place `k` in its correct position in the sorted portion of the array (`a[j+1]`).
5. **Output the Sorted Array:**
- Print the elements of the sorted array in ascending order.
Output
Program 12.
Write a program to create an array of n elements and delete a given element
from the array. Your program should display appropriate error message if
the element to be deleted is not found in the array.
SOLUTION.
import java.util.*;

public class Question11{


public static void main()throws InputMismatchException{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array: "); int n=sc.nextInt(); int
a[]=new int[n];
int i,j,k;
System.out.println("Enter "+n+" integers:"); for(i=0;i<n;i++)
{ a[i]=sc.nextInt();
}
System.out.println("Enter the element to be deleted: "); int e=sc.nextInt();

boolean flag=false;

for(i=0;i<n;i++){ if(a[i]==e){ for(j=i;j<n-1;j++){ a[j]=a[j+1];


}
flag=true; n--; break;
}
} if(flag){ for(i=0;i<n;i++)
System.out.print(a[i]+" ");
}else{
System.out.print("Element not found");
}

} //end of main
} //end of class

Here's the algorithm for the given Java program, which deletes an
element from an array and prints the modified array or a message if the
element is not found:

1. **Initialization:**
- Create a `Scanner` object to read input from the user.
2. **Input Handling:**
Program 12.
- Prompt the user to enter the size of the array.
- Read the size (`n`) and store it in an integer variable.
- Create an integer array `a` of size `n` to store the input integers.
3. **Array Population:**
- Prompt the user to enter `n` integers.
- Read each integer and store it in the array `a`.
4. **Element Deletion:**
- Prompt the user to enter the element to be deleted.
- Read the element (`e`) to be deleted.
- Initialize a boolean flag `flag` to `false` to track if the element is found and deleted.
5. **Search and Delete:**
- Iterate through the array to find the element `e`:
1. If `a[i]` equals `e`:
- Iterate through the array starting from the found position (`i`) to the second last element (`n-2`):
- Shift each element to the left to overwrite the element to be deleted.
- Set `flag` to `true`.
- Decrement the size `n` by 1.
- Break out of the loop.
6. **Output the Result:**
- If `flag` is `true` (element found and deleted):
- Print the modified array elements.
- Otherwise (element not found):
- Print "Element not found".

You might also like