COMP_PROJECT_11_(1)[1]

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

Computer Project

Name: Mohd Ali Umar

Class: XI-G
2024-25
Internal Examiner’s
sign: __________
External Examiner’s
sign: __________
Acknowledgement
I would like to express my special thanks of
gratitude to my teacher Akash Sir as well as our
Senior Principal Mrs. Jyoti Kashyap and
Principal Shivani Singh who gave me the golden
opportunity to do this wonderful project on the
topic (Java Programs), which also helped me in
doing a lot of Research and i came to know
about so many new things I am really thankful
to them.

Secondly I would also like to thank my parents


and friends who helped me a lot in finalizing
this project within the limited time frame.
Index
S.No. Program Page No.
1 Primo Number 1-2
2 Matrix Operation 3-5
3 Sentence Rearrangement 6-7
4 Smallest Digit and Sum 8-9
5 Composite Magic number 10-11
6 International Standard Book Number 12
7 Mirror Matrix 13-15
8 Palindrome word 16-17
9 Prime Palindrome integer 18-20
10 Number to Word 21-22
11 Date Validation 23-24
12 Denomination Breakdown 25-26
13 Kaprekar Number 27-28
14 Frequency of Words 29-30
15 Prime and nearest Prime 31-32
Question 1
A PRIMO NUMBER is a number that contains all the prime digits in it and is minimum of 4-
digit.
Example:
12375
2357
403275
Write a program in java to input a number and check if it is a PRIMO NUMBER or not.
Also write an ALGORITHM of the program.

import java.util.*;

class PrimoNumberChecker {
boolean isPrimeDigit(int digit) {
return digit == 2 || digit == 3 || digit == 5 || digit == 7;
}
boolean isPrimoNumber(int number) {
if (number < 1000) {
return false;
}
while (number > 0) {
int digit = number % 10;
if (!isPrimeDigit(digit)) {
return false;
}
number /= 10;
}
return true;
}
public static void main() {
Scanner sc = new Scanner(System.in);

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


int number = sc.nextInt();
if (isPrimoNumber(number)) {
System.out.println(number + " is a Primo Number");
} else {
System.out.println(number + " is not a Primo Number"); }
} //main } //class
Algorithm:

Input: Read an integer number from the user.


Check for Minimum Digits: Ensure number is at least a 4-digit number.
Iterate and Check Digits:
While number is greater than 0:
Extract the last digit of number.
Check if the extracted digit is a prime digit (2, 3, 5, or 7).
If not, return false (not a Primo number).
Remove the last digit from number by integer division.
Return Result: If all digits were prime, return true (it's a Primo number).
Output: Print the result based on the returned value.
Question 2
Write a program to declare a square matrix A[][] of order (M x M) where ‘M’ must be
greater than 3 and less than 10. Allow the user to input positive integers into this matrix.
Perform the following tasks on the matrix:
1. Sort NON Boundary elements in ascending order using any standard sorting technique
and rearrange them in the matrix.
2. Calculate the sum of both the diagonals.
3. Display the original matrix, rearranged matrix and only the diagonal elements of the
rearranged matrix.
Test your program with the sample data and some random data:

import java.util.*;
class MatrixOperations {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the square matrix (M > 3 and M < 10): ");
int M = sc.nextInt();
if (M <= 3 || M >= 10) {
System.out.println("Invalid input. Please enter a value between 4 and 9.");
return;
}
int[][] matrix = new int[M][M];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = sc.nextInt();
}
}
// Extract non-boundary elements and sort them using bubble sort
int nonBoundaryCount = (M - 2) * (M - 2);
for (int i = 1; i < M - 1; i++) {
for (int j = 1; j < M - 1; j++) {
for (int k = 1; k < M - 1; k++) {
for (int l = 1; l < M - 1; l++) {
if (matrix[i][j] > matrix[k][l]) {
int temp = matrix[i][j];
matrix[i][j] = matrix[k][l];
matrix[k][l] = temp;
}
}
}
}
}

// Calculate the sum of diagonals


int diagonal1Sum = 0, diagonal2Sum = 0;
for (int i = 0; i < M; i++) {
diagonal1Sum += matrix[i][i];
diagonal2Sum += matrix[i][M - i - 1];
}

// Print the original, rearranged, and diagonal matrices


System.out.println("ORIGINAL MATRIX");
printMatrix(matrix);

System.out.println("\nREARRANGED MATRIX");
printMatrix(matrix);

System.out.println("\nDIAGONAL ELEMENTS");
for (int i = 0; i < M; i++) {
System.out.print(matrix[i][i] + "");
}
System.out.println();
for (int i = 0; i < M; i++) {
System.out.print(matrix[i][M - i - 1] + "");
}
System.out.println();

System.out.println("Sum of diagonal 1: " + diagonal1Sum);


System.out.println("Sum of diagonal 2: " + diagonal2Sum);
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
} } }
Algorithm:

Input:
Read the size M of the square matrix.
Read the elements of the matrix.
Extract and Sort Non-Boundary Elements:
Iterate over the matrix, excluding the boundary elements.
For each non-boundary element:
Compare it with all other non-boundary elements.
If a smaller element is found, swap them.
Calculate Diagonal Sums:
Initialize two variables to store the sums of the two diagonals.
Iterate over the matrix:
Add the element at the current index to the first diagonal sum.
Add the element at the opposite diagonal index to the second diagonal sum.
Print Matrices:
Print the original matrix.
Question 3
Write a program to accept a sentence which may be terminated by either '.', '?' or '!' only.
The words may be separated by more than one blank space and are in UPPER CASE.
Perform the following tasks:
1. Find the number of words beginning and ending with a vowel.
2. Place the words which begin and end with a vowel at the beginning, followed by the
remaining words as they occur in the sentence.
Test your program with the sample data and some random data:

import java.util.*;

class SentenceRearrangement {
boolean isVowel(char ch) {
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
public static void main() {
Scanner sc = new Scanner(System.in);

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


String sentence = sc.nextLine();

if (!sentence.endsWith(".") && !sentence.endsWith("?") && !


sentence.endsWith("!")) {
System.out.println("Invalid Input");
return;
}
String[] words = sentence.split("\\s+");
int vowelWordCount = 0;

// Rearrange the words in-place


for (int i = 0; i < words.length; i++) {
if (isVowel(words[i].charAt(0)) &&
isVowel(words[i].charAt(words[i].length() - 1))) {
// Swap the current word with the first vowel word
String temp = words[i];
words[i] = words[vowelWordCount];
words[vowelWordCount] = temp;
vowelWordCount++;
}
}
System.out.println("Number of words beginning and ending with a vowel
= " + vowelWordCount);

for (String word : words) {


System.out.print(word + " ");
}
}
}

Algorithm:

Input: Read a sentence from the user.


Validate Input:
Check if the sentence ends with a valid punctuation mark ('.', '?', or '!').
Tokenize: Split the sentence into words based on whitespace.
Rearrange Words:
Initialize a counter vowelWordCount to 0.
Iterate through the words:
If the current word is a vowel word (starts and ends with a vowel):
Swap the current word with the word at index vowelWordCount.
Increment vowelWordCount.
Output:
Print the vowelWordCount.
Print the rearranged sentence.
Question 4
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less
than 100. Find the smallest integer that is greater than M and whose digits add up to N.
For example, if M=100 and N=11, then the smallest integer greater than 100 whose digits
add up to 11 is 119.
Write a program to accept the numbers M and N from the user and print the smallest
required number whose sum of all its digits is equal to N. Also, print the total number of
digits present in the required number. The program should check for the validity of the
inputs and display an appropriate message for an invalid input.
Test your program with the sample data and some random data:

import java.util.*;

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

System.out.print("Enter M: ");
int M = sc.nextInt();
System.out.print("Enter N: ");
int N = sc.nextInt(); 1

if (M < 100 || M > 10000 || N < 1 || N > 99) {


System.out.println("Invalid Input");
return;
}

int num = M + 1;
while (true) {
int sum = 0;
int temp = num;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
if (sum == N) {
int digitCount = (int) Math.log10(num) + 1;
System.out.println("The required number = " + num);
System.out.println("Total number of digits = " + digitCount);
break;
}
num++;
}
}
}

Algorithm:

Input:
Read two positive integers M and N from the user.
Validate Input:
Check if M is between 100 and 10000 and N is between 1 and 99.
Initialize:
Set num to M + 1.
Iterate and Check:
Repeat the following steps until a suitable number is found:
Calculate the sum of digits of num.
If the sum is equal to N, break the loop.
Increment num.
Output:
If a suitable number is found, print the number and its digit count.
Otherwise, print "Invalid Input".
Question 5
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 which 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 digit d 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 frequency,
in the format specified below:

import java.util.*;
class CompositeMagicNumbers {

boolean isComposite(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return true;
}
}
return false; 1
}
public static boolean isMagic(int num) {
while (num > 9) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
return num == 1;
}
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter m and n: ");
int m = sc.nextInt();
int n = sc.nextInt();
if (m >= n) {
System.out.println("Invalid Input");
return;
}
int count = 0;
System.out.println("The composite magic integers are:");
for (int i = m; i <= n; i++) {
if (isComposite(i) && isMagic(i)) {
System.out.print(i + "");
count++;
}
}
System.out.println("\nFrequency of composite magic integers is: " +
count);
}
}

Algorithm
The is composite function checks if a number is composite by iterating from 2
to its square root.
The is magic function repeatedly sums the digits of a number until it reaches a
single-digit number. If this final digit is 1, the number is magic.
The main function reads the input, validates it, and iterates through the range
m to n. For each number, it checks if it's composite and magic, and if so, prints
it and increments the count.
Finally, the total count of composite magic numbers is printed.
Question 6
An ISBN ( International Standard Book Number) is a ten digit code which
uniquely identifies a book. The first nine digits represent the Group,
Publisher and Title of the book and the last digit is used to check whether
ISBN is correct or not.
Each of the first nine digits of the code can take a value between 0 and 9.
Sometimes it is necessary to make the last digit equal to ten; this is done
by writing the last digit of the code as X. To verify an ISBN, calculate 10
times the first digit, plus 9 times the second digit, plus 8 times the third
and so on until we add 1 time the last digit. If the final number leaves no
remainder when divided by 11, the code is a valid ISBN.

class ISBN
{
public static void main(String nm)
{
int ln=nm.length();
if(ln<10 || ln>10) System.out.println("INVALID INPUT");
else
{
int tot=0;
int p=10;
int d;
for(int i=0; i<10; i++)
{
char ch=nm.charAt(i);
if(ch=='X') d=10;
else d=ch-48;
tot = tot + d*p--;
}
if(tot%11==0) System.out.println(nm + "= it is an ISBN number ");
else System.out.println(nm + " = it is NOT an ISBN number ");
} } }
Question 7
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:
1. Display the input matrix.
2. Create a mirror image of the inputted matrix.
3. Display the mirror image matrix.
Test your program for the following data and some random data:

import java.util.*;

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

// Input 1 the size of the square matrix


int M;
do {
System.out.print("Enter the size of the square matrix (M > 2 and M <
20): ");
M = scanner.nextInt();
if (M <= 2 || M >= 20) {
System.out.println("Invalid input. Please enter a value between 3 and
19.\n");
}
} while (M <= 2 || M >= 20);

// Declare the matrix


int[][] A = new int[M][M];

// Input the elements of the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
A[i][j] = scanner.nextInt();
}
}
// Display the original matrix
System.out.println("\nOriginal Matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
System.out.print(A[i][j] + "\t");
}
System.out.println();
}

// Create the mirror image matrix


int[][] mirror = new int[M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
mirror[i][j] = A[i][M - j - 1];
}
}

// Display the mirror image matrix


System.out.println("\nMirror Image Matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
System.out.print(mirror[i][j] + "\t");
}
System.out.println();
}
}
}
Algorithm:
Input:
Read the size of the square matrix, M.
Ensure M is between 3 and 19 (inclusive).
Matrix Input:
Create a 2D array A of size M x M.
Read the elements of A from the user.
Display Original Matrix:
Print the elements of A in a matrix format.
Create Mirror Image:
Create a new 2D array mirror of size M x M.
For each element A[i][j] in A:
Assign the value of A[i][M-j-1] to mirror[i][j].
Display Mirror Image Matrix:
Print the elements of mirror in a matrix format.
Question 8
A palindrome is a word that may be read the same way in either direction. Accept a
sentence in UPPER CASE which is terminated by either ".", "?", or "!". Each word of the
sentence is separated by a single blank space.
Perform the following tasks:
1. Display the count of palindromic words in the sentence.
2. Display the palindromic words in the sentence.
Example of palindromic words:
MADAM, ARORA, NOON
Test your program with the sample data and some random data:

import java.util.*;

class PalindromeWords {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
String[] words = sentence.split("\\s+");
int count = 0;
System.out.println("Palindrome words:");
for (String word : words) {
if (isPalindrome(word)) {
System.out.print(word + " ");
count++;
}
}
System.out.println("\nNumber of palindromic words: " + count);
}
boolean isPalindrome(String word) {
int left = 0, right = word.length() - 1;
while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}}
Algorithm:

Input: Read a sentence from the user.


Split the sentence: Split the sentence into words using whitespace as the
delimiter.
Iterate over words:
For each word:
Check if the word is a palindrome using the isPalindrome function.
If it is a palindrome, print the word and increment a counter.
Output:
Print the list of palindrome words.
Print the total count of palindrome words.
isPalindrome function:

Initialize pointers:
Initialize two pointers, left and right, to the beginning and end of the word,
respectively.
Iterate and compare:
While left is less than right:
If the characters at left and right are different, the word is not a palindrome.
Move left one position to the right and right one position to the left.
Return result:
If the loop completes without finding a mismatch, the word is a palindrome.
Return true.
Otherwise, return false.
Question 9
A prime palindrome integer is a positive integer (without leading zeros) which is prime as
well as a palindrome. Given two positive integers m and n, where m < n, write a program
to determine how many prime-palindrome integers are there in the range between m and
n (both inclusive) and output them.
The input contains two positive integers m and n where m < 3000 and n < 3000. Display
the number of prime palindrome integers in the specified range along with their values in
the format specified below:
Test your program with the sample data and some random data:

import java.util.*;

class PrimePalindrome {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the values of m and n: ");
int m = sc.nextInt();
int n = sc.nextInt();

if (n > 3000) {
System.out.println("OUT OF RANGE");
return;
}

System.out.println("THE PRIME PALINDROME INTEGERS ARE:");


int count = 0;
for (int i = m; i <= n; i++) {
if (isPrimePalindrome(i)) {
System.out.print(i + "");
count++;
}
}
System.out.println("\nFREQUENCY OF PRIME PALINDROME INTEGERS: " +
count);
}

boolean isPrimePalindrome(int num) {


if (num < 2) {
return false;
}
// Check for palindrome
int reversedNum = 0, originalNum = num;
while (num > 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}
if (originalNum != reversedNum) {
return false;
}

// Check for prime


for (int i = 2; i * i <= originalNum; i++) {
if (originalNum % i == 0) {
return false;
}
}

return true;
}
}
Algorithm:

Input:
Read two positive integers m and n from the user.
Validate Input:
Check if n is greater than 3000. If so, print an error message and exit.
Iterate and Check:
For each number i from m to n:
Check if i is a prime palindrome using the isPrimePalindrome function.
If i is a prime palindrome, print it and increment a counter.
Output:
Print the list of prime palindrome numbers.
Print the total count of prime palindrome numbers.
isPrimePalindrome function:

Check for base cases:


If num is less than 2, it's not prime.
Check for palindrome:
Reverse the digits of num and store it in reversedNum.
If originalNum (the original value of num) is not equal to reversedNum, it's not
a palindrome.
Check for prime:
Iterate from 2 to the square root of originalNum.
If originalNum is divisible by any number in the range, it's not prime.
Return result:
If the number passes both palindrome and prime checks, return true.
Otherwise, return false.
Question 10
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.
Sample input and output of the program

import java.util.*;
class NumberToWords {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a natural number less than 1000: ");
int number = sc.nextInt();

if (number < 0 || number >= 1000) {


System.out.println("OUT OF RANGE");
} else {
String[] ones = {"", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX",
"SEVEN", "EIGHT", "NINE"};
String[] tens = {"TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN",
"FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"};
String[] tensMultiple = {"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY",
"SIXTY", "SEVENTY", "EIGHTY", "NINETY"};
String word = "";
if (number >= 100) {
int hundred = number / 100;
word += ones[hundred] + " HUNDRED ";
number %= 100;
}
if (number >= 20) {
int ten = number / 10;
word += tensMultiple[ten] + "";
number %= 10;
} else if (number >= 10) {
word += tens[number - 10] + "";
number = 0;
}
if (number > 0) {
word += ones[number];
}
System.out.println(word.trim());
} } }
Algorithm:

Input: Read a natural number n.


Validate Input: Check if n is within the range 0 to 999.
Convert to Words:
Hundreds Place:
If n is greater than or equal to 100, extract the hundreds digit, convert it to
words, and append "HUNDRED" to the result.
Update n by removing the hundreds digit.
Tens and Ones Place:
If n is greater than or equal to 20:
Extract the tens digit, convert it to words, and append to the result.
Update n by removing the tens digit.
If n is between 10 and 19:
Convert the entire number (10-19) to its corresponding word and append to
the result.
Set n to 0.
If n is less than 10:
Convert the ones digit to its corresponding word and append to the result.
Output: Print the final word representation of the number.
Question 11
Design a program which accepts your date of birth in dd, mm , yyyy
format. Check whether the date entered is valid or not.
If it is valid, display "VALID DATE", also compute and display the day
number of the year for the date of birth. If it is invalid, display "INVALID
DATE" and then terminate the program.

import java.util.*;

class DateValidation {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your date of birth in dd mm yyyy format: ");
int day = sc.nextInt();
int month = sc.nextInt();
int year = sc.nextInt();

if (!isValidDate(day, month, year)) {


System.out.println("INVALID DATE");
return;
}
System.out.println("VALID DATE");
System.out.println("Day number of the year: " + calculateDayOfYear(day,
month, year));
}
boolean isValidDate(int day, int month, int year) {
// Check for invalid year
if (year < 1 || year > 9999) {
return false;
}

// Check for invalid month


if (month < 1 || month > 12) {
return false;
}
// Check for invalid day
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[2] = 29;
}
if (day < 1 || day > daysInMonth[month]) {
return false;
}

return true;
}

boolean isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int calculateDayOfYear(int day, int month, int year) {
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[2] = 29;
}
int dayOfYear = 0;
for (int i = 1; i < month; i++) {
dayOfYear += daysInMonth[i];
}
dayOfYear += day;
return dayOfYear;
}
}
Algorithm:
Input: Read the day, month, and year from the user.
Validate Date:Check if the year is within a valid range (e.g., 1-9999).
Check if the month is within the range 1-12.
Check if the day is valid for the given month and year, considering leap years.
Calculate Day of Year:
If the date is valid, calculate the day of the year by summing up the days in the
previous months and adding the current day.
Output: If the date is valid, print "VALID DATE" and the day of the year.
If the date is invalid, print "INVALID DATE".
Question 12
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.

import java.util. *;

class DenominationBreakdown {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the amount: ");
int amount = sc.nextInt(); 1
if (amount <= 0) {
System.out.println("Invalid amount");
return;
}
// Convert amount to words
String[] words = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX",
"SEVEN", "EIGHT", "NINE"};
String amountInWords = "";
for (char digit : String.valueOf(amount).toCharArray()) {
amountInWords += words[digit - '0'] + "";
}
System.out.println(amountInWords.trim().toUpperCase());
// Denomination breakdown
int[] denominations = {1000, 500, 100, 50, 20, 10, 5, 2, 1};
System.out.println("DENOMINATION:");
for (int denomination : denominations) {
int count = amount / denomination;
if (count > 0) {
System.out.println(denomination + " X " + count + " = " +
(denomination * count));
amount %= denomination; } } }
}
Algorithm:

Input: Read the amount to be broken down from the user.


Validate Input:
Check if the amount is positive. If not, print an invalid amount message and
exit.
Convert Amount to Words:
Convert the amount to a string.
Iterate over each digit of the string and map it to its corresponding word using
an array.
Concatenate the words to form the amount in words.
Denomination Breakdown:
Define an array of denominations in descending order.
Iterate over each denomination:
Calculate the number of notes of the current denomination needed.
If the count is greater than 0, print the denomination, count, and total value.
Update the remaining amount.
Output:Print the amount in words.
Print the denomination breakdown.
Question 13
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.

import java.util.*;

class KaprekarNumbers {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter p: ");
int p = sc.nextInt();
System.out.print("Enter q: ");
int q = sc.nextInt();
System.out.println("THE KAPREKAR NUMBERS ARE:");
int count = 0;
for (int i = p; i <= q; i++) {
if (isKaprekar(i)) {
System.out.print(i + "");
count++;
}
}
System.out.println("\nFREQUENCY OF KAPREKAR NUMBERS IS: " + count);
}
boolean isKaprekar(int n) {
if (n == 1) {
return true;
}
int sqr = n * n;
int digits = (int) Math.log10(n) + 1;
int divisor = (int) Math.pow(10, digits);
int rightPart = sqr % divisor;
int leftPart = sqr / divisor;
return leftPart + rightPart == n;
} }
Algorithm:

Input:
Read two positive integers p and q from the user.
Iterate and Check:
For each number n from p to q:
Calculate the square of n.
Determine the number of digits in the square (digits).
Calculate the divisor divisor as 10 raised to the power of digits.
Calculate the right part of the square: rightPart = sqr % divisor.
Calculate the left part of the square: leftPart = sqr / divisor.
If leftPart + rightPart == n, then n is a Kaprekar number.
If n is a Kaprekar number, print it and increment a count variable.
Output:
Print the list of Kaprekar numbers found.
Print the total count of Kaprekar numbers.
Question 14
Input a paragraph containing 'n' number of sentences where (1<=n<=4).
The words are to be separated with single blank space and are in upper
case. A sentence may be terminated either with a full stop (.) or question
mark (?).
Perform the following:
1. Enter the number of sentences, if it exceeds the limit show a message.
2. Find the number of words in the paragraph
3. Display the words in ascending order with frequency.

import java.util.Arrays;
import java.util.*;
public class WordFrequency {
public static void main() {
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of sentences: ");


int numSentences = sc.nextInt();

// Consume the newline character


if (numSentences > 4) {
System.out.println("Number of sentences exceeds the limit.");
return;
}
System.out.println("Enter the sentences:");
String paragraph = "";
for (int i = 0; i < numSentences; i++) {
paragraph += sc.nextLine() + "";
}
String[] words = paragraph.split("\\s+");
int wordCount = words.length;
System.out.println("Total number of words: " + wordCount);
// Sort the words
Arrays.sort(words);
// Count the frequency of each word
int count = 1;
String currentWord = words[0];
for (int i = 1; i < wordCount; i++) {
if (words[i].equals(currentWord)) {
count++;
} else {
System.out.println(currentWord + "\t" + count);
currentWord = words[i];
count = 1;
}
}
System.out.println(currentWord + "\t" + count);
}
}

Algorithm:

Input: Read the number of sentences n from the user.


If n exceeds 4, display an error message and exit.
Read n sentences from the user, concatenating them into a single string
paragraph.
Preprocess the text: Split the paragraph into words using whitespace as the
delimiter.
Sort the words: Sort the words array alphabetically.
Count and Print: Initialize a count variable to 1.
Initialize a currentWord variable to the first word in the sorted array.
Iterate through the sorted array:
If the current word is the same as the previous word, increment the count.
Otherwise, print the previous word and its count, then update the currentWord
and reset the count to 1.
After the loop, print the last word and its count.
Question 15
Design a class Prime.
Data Members-:
 n - to store the number
Member Functions-:
 Prime(int) - constructor to initialize n
 void Print ( ) – To print the number and print the nearest prime
number greater than the number.
 Example: n=15 nearest prime number greater than 15 is 17
 n=9 nearest prime number greater than 9 is 11
 n=19 nearest prime number greater than 19 is 23

 boolean isPrime(int) - returns true/false for prime using recursive


technique

class Prime {
int n;

Prime(int n) {
this.n = n;
}

void print() {
System.out.println("Number: " + n);
System.out.println("Nearest prime number greater than " + n + ": " +
nextPrime());
}

int nextPrime() {
int num = n + 1;
while (!isPrime(num)) {
num++;
}
return num;
}

boolean isPrime(int num) {


if (num <= 1) {
return false;
}
if (num <= 3) {
return true;
}
if (num % 2 == 0 || num % 3 == 0) {
return false;
}

int i = 5;
while (i * i <= num) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
i += 6;
}

return true;
}

public static void main() {


Prime prime1 = new Prime(15);
prime1.print();

Prime prime2 = new Prime(9);


prime2.print();

Prime prime3 = new Prime(19);


prime3.print();
}
}

You might also like