Write A Program in Java To Input A Number and Check Whether It Is A Fascinating Number or Not-1
Write A Program in Java To Input A Number and Check Whether It Is A Fascinating Number or Not-1
import java.util.Scanner;
else
System.out.println(num + " is not a Fascinating Number");
}
}
if (n <= 0) {
System.out.println(n + " is not a Smith Number.");
return;
}
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.
Example: 3,5,7,11
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;
}
}
}
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;
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;
}
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.
Soltion.
import java.util.Scanner;
while(copyNum != 0) {
int digit = copyNum % 10;
copyNum /= 10;
revNum = revNum * 10 + digit;
}
.
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;
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 (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.
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();
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
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];
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);
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
}
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.*;
boolean flag=false;
} //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".