com_pra[1]000[1]
com_pra[1]000[1]
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**
3. Use a loop to take 10 integer inputs from the user and store them in the array.
6. **End**
Java Program:
import java.util.Scanner;
System.out.println("Enter 10 numbers:");
arr[i] = sc.nextInt(); }
if (isPrime(arr[i])) {
arr[i] = 0; } }
System.out.println("Modified array:");
if (n < 2) {
return false; }
return false; } }
return true; }}
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`.
4. Loop through the array to find all pairs of odd primes whose sum equals `N`.
7. **End**
Java Program
import java.util.*;
if(num <= 1)
return false;
if(num % I == 0)
return false;
} return true; }
int N = sc.nextInt();
// Check if N is valid
if (N <= 9 || N >= 50 || N % 2 != 0) {
System.out.println("invalid input");
return; }
int[] oddPrimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
if (oddPrimes[I] + oddPrimes[j] == N) {
foundPair = true; } } }
if (!foundPair) {
sc.close(); }}
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.
Class name
Rearrange
Member functions/methods:
Rearrange():default constructor
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**
- Read and accept the word from the user, convert it to uppercase and store it in `wrd`.
- Count the number of vowels and consonants in the word and display the counts.
- Rearrange the word by placing all vowels at the beginning, followed by consonants. Store this new arrangement in
`newwrd`.
Java Program:
import java.util.Scanner;
// Instance variables
// Default constructor
public Rearrange() {
wrd = "";
newwrd = ""; }
int vowelCount = 0;
int consonantCount = 0;
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); }
char ch = wrd.charAt(I);
if ("AEIOU".indexOf(ch) != -1) {
vowels += ch;
} else if (Character.isLetter(ch)) {
consonants += ch; } }
System.out.println("original word="+wrd);
System.out.println("rearranged word="+newwrd); }
// Main method
Obj.readword();
Obj.freq_vow_con();
Obj.arrange();
Obj.display(); }}
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 Output: The Unique-Digit integers are: 102, 103, 104, 105, 106, 107, 108, 109, 120.
algorithm:
1. **Start**
2. **Input** the values of `m` and `n` (where `m < n` and `m < 30000`, `n < 30000`).
- If the number is unique, store it in the list and increment the counter.
7. **End**
Java Program:
import java.util.Scanner;
if (digitSeen[digit]) {
digitSeen[digit] = true;
num /= 10; }
// Main method
int m = sc.nextInt();
System.out.print("enter value of n");
int n = sc.nextInt();
int counter = 0;
if (isUniqueDigit(i)) {
uniqueNumbers.append(i).append(", ");
counter++; } }
if (counter > 0) {
uniqueNumbers.setLength(uniqueNumbers.length()-2); }
System.out.println(uniqueNumbers);
System.out.println("frequency ="+counter); }}
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
- 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;
int n = sc.nextInt();
// Initialize variables
int triangularNumber = 0;
int I = 1;
System.out.println(triangularNumber); }
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
WAP in java to accept a positive no. and check whether it is circular prime or not.
algorithm:
1. **Input** the number `n`.
3. **Generate Cyclic Permutations**: Create a helper function `getCyclicPermutations()` to generate all cyclic permutations
of `n`.
5. **Display Result**:
Java coDe:
import java.util.Scanner;
if (num % i == 0) {
return false; }
permutations[i] = numStr; }
return permutations; } // Main function to check if a number is a circular prime
sc.close();
if (!isPrime(Integer.parseInt(perm))) {
isCircularPrime = false;
if (isCircularPrime) {
} else {
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**
3. If the number is less than 100, output “Not a Bouncy number” because no number less than 100 can be bouncy.
- 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.
9. **End**
Java coDe:
import java.util.Scanner;
System.out.print("enter a no.");
} else {
isDescending = false; } }
} else {
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**
3. If the number is a prime number, output "Not a Smith number" (since Smith numbers are composite).
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.
8. **End**
Java coDe:
import java.util.Scanner;
if (n % i == 0) {
return false;
} } return true; }
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10; }
return sum; }
int sum = 0;
sum += sumOfDigits(2);
n /= 2; }
while (n % i == 0) {
sum += sumOfDigits(i);
n /= i; } }
if (n > 2) {
sum += sumOfDigits(n); }
return sum; }
if (isPrime(number)) {
} else {
if (sumDigits == sumPrimeFactorsDigits) {
} else {
}
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**
6. **End**
Java Program
import java.util.Scanner;
int borderSum = 0;
int nonBorderSum = 0;
matrix[i][j] = sc.nextInt(); } }
// Calculate sums
if (I == 0 || I == 3 || j == 0 || j == 3) {
borderSum += matrix[I][j];
} else {
nonBorderSum += matrix[I][j]; } } }
} }
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**
6. **Insert** the sorted elements back into the matrix in a clockwise spiral pattern.
8. **End**
Java Program
import java.util.Scanner;
int[] sortedArray = new int[16]; // Input elements into the 4x4 matrix
int k = 0;
matrix[I][j] = sc.nextInt();
sortedArray[j + 1] = temp; } } } // Fill the matrix in clockwise order with sorted elements
int index = 0;
while (top <= bottom && left <= right) { // Traverse from left to right across the top row
matrix[top][i] = sortedArray[index++]; }
matrix[bottom][i] = sortedArray[index++]; }
matrix[i][left] = sortedArray[index++]; }
System.out.print(matrix[i][j] +"\t"); }
System.out.println(); } }}
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**
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`.
6. If both conditions are true, the numbers are amicable. Otherwise, they are not.
8. **End**
Java Program
import java.util.Scanner;
int sum = 0;
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:
192 x 1 = 192
192 x 2 = 384
192 x 3 = 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**
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;
// Input a number
System.out.print("enter a no.");
isFascinating = false;
break; } }
if (isFascinating) {
} else {
`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
No. of 1’s: 4
algorithm:
1. **Start**
3. Convert the number `n` to its binary equivalent and store it in a string.
7. **End**
Java Program:
import java.util.Scanner;
System.out.print("input:");
int n = sc.nextInt();
int countOnes = 0;
if (c =='1') {
countOnes++; } }
if (countOnes % 2 == 0) {
} else {
sc.close(); }}
outPut:
Program 14
Question:
Write a program in Bluej to accept a sentence from the user. Display the longest palindrome word in the sentence.
O/P – NITIN
algorithm:
1. **Start**
7. **End**
Java Program:
import java.util.Scanner;
System.out.print("Enter a sentence:");
// Step 5: Check each word for palindrome and find the longest one
if (isPalindrome(word)) {
longestPalindrome = word; } } }
if (!longestPalindrome.equals("")) {
System.out.println("Longest Palindrome:"+longestPalindrome);
} else {
sc.close(); }
// Function to check if a word is palindrome
return false; } }
return true;
outPut:
```
algorithm:
1. **Start**
3. Split the sentence into individual words using space as the delimiter.
- 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;
// Step 5: Check each word for palindrome and find the longest one
If (isPalindrome(word)) {
longestPalindrome = word; } } }
If (!longestPalindrome.equals(“”)) {
Sc.close(); }
Return false;
} } Return true; } }
Composite number:
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:**
- 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.
- 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.
- Count and display all numbers that are both composite and magic.
Java Program
import java.util.Scanner;
int count = 0;
if (num % I == 0) count++;
return false; } // Method to calculate the sum of digits and check if it is a magic number
num /= 10; }
num = sum; }
int m = scanner.nextInt();
return; } // Find and display Composite Magic numbers in the range [m, n]
int count = 0;
System.out.println("\nfrequency" + count); }}
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.
(a) Accept the sentence and reduce all the extra blank space between two words to
(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
WORD TO BE DELETED: IS
algorithm
1. **Input Handling:**
2. **Reduce Spaces:**
3. **Delete Word:**
4. **Output:**
- Display the modified sentence with reduced spaces and the specified word removed.
Java Program
import java.util.Scanner;
// Trim leading and trailing spaces and replace multiple spaces with a single space
// Loop through words and append to result except the word to be deleted at the specified position
result.append(words[I]).append(" "); } }
return reduceSpaces(result.toString()); }
System.out.println("output:" + result);
}}
```
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:
Member methods:
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**:
- `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.
Java Program
import java.util.Random;
import java.util.Scanner;
name = scanner.nextLine();
int score = 0;
tries = 0;
score += roll;
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
player1.acceptDetails();
player2.acceptDetails();
System.out.println("\nResults:");
player1.displayResult();
player2.displayResult();
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.
- Use the formula \( \text{Area} = \sqrt{s \times (s – a) \times (s – b) \times (s – c)} \) to find the area.
- Read 40 answers from the user and store them in a single-dimensional array.
- Check each answer against the calculated area and count how many are correct.
Java Program
import java.util.Scanner;
Scanner scanner = new Scanner(System.in); // Input lengths of the sides of the triangle
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double s = (a + b + c) / 2;
int correctCount = 0;
for (double answer : studentAnswers) { // Using a tolerance to account for floating-point precision issues
if (Math.abs(answer - area) < 0.01) {
scanner.close(); }}```
Example,
Class name
: NumSort
Member functions/methods:
NumSort(int n) : parameterised constructor to initialise the data member num= of the number and stores in the array
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**:
- **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 display()`: Displays the original number and the sorted digits.
- 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 size; // Parameterized constructor to initialize the number and extract its digits
public NumSort(int n) {
num = n;
temp /= 10;
} }
arr[j + 1] = temp;
} } } }
System.out.print(digit);
} System.out.println();
int n = sc.nextInt();
obj.extract_digit();
obj.sort();
obj.display();
sc.close();
outPut: