Java COMPUTER PROJECT Cms
Java COMPUTER PROJECT Cms
1
Acknowledgement
I would like to express my special thanks of
gratitude to my teacher Mr. Sarfraz Ahmad Sir
who gave me the golden opportunity to do
this wonderful project 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 him. I am also thankful to my principals Mrs.
Jyoti Kashyap ma’am and Mrs. Shivani Singh
ma’am for always encouraging us to give our
best in everything. Their motivation helped a
lot to complete this project on time.
I would also like to thank my parents and
friends who helped me in finalizing this project
within the limited time frame.
Anant Shukla
2
Index
S.No. Program Page No.
1 Circular Prime Number 4-7
2 Boundary and Diagonals of a Square Matrix 8-11
3 Vowel words and shift of words 12-14
4 Find number whose sum of all its digits is equal to N 15-17
5 Rotate the matrix 90ᵒ clockwise and corner element sum 18-21
6 Find the number of vowels and consnants in each word 22-25
7 Number which is composite as well as a magic number. 26-28
8 Check if the given matrix is symmetric or not. 29-32
9 Deleting given word from the string 33-35
10 An ISBN ( International Standard Book Number) 36-38
11 Create a mirror image of the inputted matrix. 39-41
12 Display and the count of palindromic words in the sentence 42-44
13 A prime palindrome which is prime as well as a palindrome. 45-47
14 Arrange the sentence in alphabetical order of the words. 48-50
15 Find the maximum and minimum value in the matrix 51-55
16 Display a Natural number less than 1000 in words 56-58
17 Encryption of a string to maintain their secrecy 59-62
18 Check whether the date entered is valid or not. 63-64
19 Denomination of an input amount 65-67
20 Kaprekar numbers 68-69
21 Display the words in ascending order of their frequency. 70-73
22 Program on Inheritance 74-77
23 Prime using recursive technique 78-80
24 Program on Data Structure - STACK 81-84
25 Program on Data Structure – Simple Queue 85-88
3
Question 1
A Circular Prime is a prime number that remains prime under cyclic shifts of its digits. When the
leftmost digit is removed and replaced at the end of the remaining string of digits, the generated number
is still prime. The process is repeated until the original number is reached again.
A number is said to be prime if it has only two factors 1 and itself.
Example:
131
311
113
Hence, 131 is a circular prime.
Test your program with the sample data and some random data:
Example 1
INPUT :N = 197
OUTPUT:
197
971
719
197 IS A CIRCULAR PRIME
Example 2
INPUT :N = 1193
OUTPUT:
1193
1931
9311
3119
Example 3
INPUT :N = 29
OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME
4
ALGORITHM
PROGRAM
import java.util.*;
class CircularPrime {
public static boolean isPrime(int num) {
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) //checking for prime
{ c++;
}
}
if (c == 2)
return true; //number is prime
else
return false; //number is not prime
}
public static int getDigitCount(int num) {
int c = 0;
while (num != 0) {
c++; to count number of digits
num /= 10;
}
5
return c;
}
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number to check ");
int n = sc.nextInt();
int flag = 1;
if (isPrime(n)) { //if original number is prime
System.out.println(n);
int dc = getDigitCount(n);
int div = (int)(Math.pow(10, dc - 1));
int n2 = n;
for (int i = 1; i < dc; i++) {
int t1 = n2 / div;
int t2 = n2 % div;
n2 = t2 * 10 + t1; //calculating the shifted number
System.out.println(n2); //check if cyclic number is primeor not
if (!isPrime(n2)) {
flag--;
break;
}
}
}
if (flag == 1) //number is circular prime
{ System.out.println(n + " is a Circular Prime");
} else { //number is not circular prime
System.out.println(n + " is NOT a Circular Prime");
}
}
}
6
OUTPUT
Enter number to check 234
234
342
423
234 is NOT a Circular Prime
Enter number to check 1193
1193
1931
9311
3119
1193 is a Circular Prime
7
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 the 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:
Example 1
INPUT :M = 4
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
OUTPUT:
ORIGINAL MATRIX
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
REARRANGED MATRIX
9 2 1 5
8 3 6 4
15 8 13 11
7 12 23 8
DIAGONAL ELEMENTS
9 5
3 6
8 13
7 8
ALGORITHM
Step 1: Start
Step 2: Declare a constant variable 'M' representing the order of the square matrix,
ensuring it is greater than 3 and less than 10.
Step 3: Declare a 2D array A[][] of order (M x M).
Step 4: Allow the user to input positive integers into the matrix A[][].
Step 5: Declare a 1D array 'nonBoundaryElements' to store non-boundary elements of the
matrix.
Step 6: Traverse the matrix excluding the boundary elements, and populate the
'nonBoundaryElements' array.
Step 7: Use any standard sorting technique to sort the 'nonBoundaryElements' array in
ascending order.
Step 8: Traverse the matrix excluding the boundary elements again, and replace the
elements with the sorted elements from 'nonBoundaryElements'.
8
Step 9: Declare variables 'sumDiagonal1' and 'sumDiagonal2' to store the sum of both
diagonals.
Step 10: Traverse the matrix diagonally, summing the elements for both diagonals.
Step 11: Display the original matrix.
Step 12: Display the rearranged matrix.
Step 13: Display only the diagonal elements of the rearranged matrix.
Step 14: End.
Note: Ensure to handle user input validation, such as checking if the entered order 'M' is
within the specified range and that the user inputs positive integers.
PROGRAM
import java.util.*;
class mtrxsort {
int m;
int a[][];
public void inputarr() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of matrix ");
m = sc.nextInt();
if (m <= 3 || m >= 10) {
System.out.println("ERROR (Matrix size out of range)");
System.exit(0); //exiting the matrix as size is out of range
}
a = new int[m][m];
System.out.println("Enter matrix elements (Only positive integers)");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = sc.nextInt(); //inputting matrix elements
}
}
}
public static void sortnb(int a[][], int m) {
int b[] = new int[(m - 2) * (m - 2)]; //array initialization
int k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
b[k++] = a[i][j];
}
}
//binary sorting
for (int i = 0; i < k - 1; i++) {
for (int j = 0; j < k - i - 1; j++) {
if (b[j] >b[j + 1]) {
int t = b[j];
9
b[j] = b[j + 1];
b[j + 1] = t;
}
} }
k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
a[i][j] = b[k++];
}
} }
10
display(obj.a, obj.m); //displaying sorted matrix
diagonalsum(obj.a, obj.m);
}}
VARIABLE DESCRIPTION TABLE
OUTPUT
Enter size of matrix 3
ERROR (Matrix size out of range)
Enter size of matrix 4
Enter matrix elements (Only positive integers)
12
46346
45
54
435
457
253
574
235
8
243
67
24
68
23
4697
ORIGINAL MATRIX
12 46346 45 54
435 457 253 574
235 8 243 67
24 68 23 4697
REARRANGED MATRIX
12 46346 45 54
435 8 243 574
235 253 457 67
24 68 23 4697
Diagonal Elements
12 54
8 243
253 457
24 4697
Sum of Diagonal elements: 574
11
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:
Example 1
INPUT: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL
Example 2
INPUT: HOW ARE YOU@
OUTPUT: INVALID INPUT
ALGORITHM
Step 1: Start
Step 2: Accept a sentence terminated by '.', '?' or '!' and store it in a string variable.
Step 3: Tokenize the sentence into words, considering multiple blank spaces as
separators.
Step 4: Initialize two lists, one for words beginning and ending with a vowel (let's call it
'vowelWords'), and another for the remaining words (let's call it 'remainingWords').
Step 5: Traverse each word in the tokenized sentence.
Step 6: Check if the current word begins and ends with a vowel.
Step 7: If yes, add it to the 'vowelWords' list; otherwise, add it to the 'remainingWords'
list.
Step 8: Concatenate the 'vowelWords' list with the 'remainingWords' list to create the
final list of words.
Step 9: Display or return the modified sentence with words beginning and ending with
vowels placed at the beginning.
Step 10: End.
PROGRAM
import java.util.*;
public class VowelWord { //to check for vowel
13
VARIABLE DESCRIPTION TABLE
OUTPUT
Enter sentence
INDIA IS A DEVELOPING NATION
INVALID INPUT
Enter sentence
INDIA IS A DEVELOPING NATION.
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 2
INDIA A IS DEVELOPING NATION
Enter sentence
ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL
14
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:
Example 1
INPUT :
M = 100
N = 11
OUTPUT :
The required number = 119
Total number of digits = 3
Example 2
INPUT :
M = 1500
N = 25
OUTPUT :
The required number = 1699
Total number of digits = 4
Example 3
INPUT :
M = 99
N = 11
OUTPUT :
INVALID INPUT
Example 4
INPUT :
M = 112
N = 130
OUTPUT :
INVALID INPUT
ALGORITHM
Step 1: Start
Step 2: Accept positive numbers M and N from the user.
Step 3: Check if M is between 100 and 10000 and if N is less than 100. If not, display an
error message and end the program.
Step 4: Initialize a variable 'currentNumber' with M.
Step 5: Iterate until a suitable number is found.
STEP 6: Calculate the sum of digits of 'currentNumber'.
STEP 7: If the sum is equal to N, display 'currentNumber' and the total number of digits,
then end the program.
STEP 8: If not, increment 'currentNumber' by 1 and repeat from Step 6.
15
Step 9: End.
PROGRAM
import java.util.Scanner;
class number_mn {
}
}
16
VARIABLE DESCRIPTION TABLE
OUTPUT
Enter M: 120
Enter N: 23
The number = 599
Total number of digits = 3
Enter M: 1500
Enter N: 25
The number = 1699
Total number of digits = 4
Enter M: 99
Enter N: 11
Invalid Input
17
Question 5
Write a program to declare a square matrix A[][] of order M×M where „M‟ is the number of
rows and the number of rows and the number of columns, such that M must be greater than 2
and less than 10. Accept the value M as user input. Display an appropriate message for an
invalid input. Allow the user to input integers into the matrix. Perform the following tasks:
1. Display the original matrix.
2. Rotate the matrix 90ᵒ clockwise as shown below:
Original matrix Rotated matrix
1 2 3 7 4 1
4 5 6 8 5 2
7 8 9 9 6 3
3. Find the sum of the elements of the four corners of the matrix.
Example 1
INPUT :
M=3
OUTPUT :
ORIGINAL MATRIX
OUTPUT :
ORIGINAL MATRIX MATRIX AFTER ROTATION
18
ALGORITHM
Step 1: Start
Step 2: Accept the number of rows and columns 'M' from the user.
Step 3: Check if 'M' is greater than 2 and less than 10. If not, display an error message
and end the program.
Step 4: Declare a square matrix A[][] of order M×M.
Step 5: Allow the user to input integers into the matrix A[][].
Step 6: Display the original matrix A[][].
Step 7: Initialize a new matrix 'rotatedMatrix' of order M×M.
Step 8: Perform the 90ᵒ clockwise rotation of the matrix A[][] and store the result in
'rotatedMatrix'.
Step 9: Display the rotated matrix 'rotatedMatrix'.
Step 10: Calculate the sum of the elements at the four corners of the original matrix
A[][].
Step 11: Display the sum of the corner elements.
Step 12: End.
PROGRAM
import java.util.*;
class rotatematrix {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows and columns(> 2 and < 10) : ");
int m = sc.nextInt();
19
ctr = 0;
c = m - 1;
ctr = 0;
while (c >= 0) {
c--;
}
20
OUTPUT
Enter the number of rows and columns(> 2 and < 10) :
3
Enter numbers for the matrix:
234
1
2342
12
3
12
325
2354
769
ORIGINAL MATRIX
234 1 2342
12 3 12
325 2354 769
MATRIX AFTER ROTATION
325 12 234
2354 3 1
769 12 2342
Sum of the corner elements = 3670
21
Question 6
Write a program to accept a sentence which may be terminated by either „.‟ Or „?‟ only. The
words are to be separated by a single blank space. Print an error message if the input does
not terminate with „.‟ Or „?‟. You can assume that no word in the sentence exceeds 15
characters, so that you get a proper formatted output.
Perform the following tasks:
1. Convert the first letter of each word to uppercase.
2. Find the number of vowels and consonants in each word and display them with proper headings
along with the words.
Test your program with the following inputs.
Example 1
INPUT: Intelligence plus character is education.
OUTPUT:
Intelligence Plus Character Is Education
WORD VOWELS CONSONANTS
Intelligence 5 7
Plus 1 3
Character 3 6
Is 1 1
Education 5 4
Example 2
INPUT: God is great.
OUTPUT:
God Is Great
WORDS VOWELS CONSONANTS
God 1 2
Is 1 1
Great 2 3
Example 3
INPUT: All the best!
OUTPUT:
Invalid Input.
ALGORITHM
Step 1: Start
Step 2: Accept a sentence terminated by '.' or '?' from the user.
Step 3: Check if the sentence terminates with '.' or '?'. If not, display an error message and
end the program.
Step 4: Tokenize the sentence into words using a single blank space as a separator.
Step 5: Iterate through each word in the tokenized sentence.
Step 6: Convert the first letter of each word to uppercase.
Step 7: Initialize variables for counting vowels and consonants in each word.
Step 8: For each word, iterate through its characters.
Step 9: Check if the current character is a vowel. If yes, increment the vowel count;
otherwise, increment the consonant count.
22
Step 10: Display the word with its first letter converted to uppercase.
Step 11: Display the count of vowels and consonants for the current word.
Step 12: Repeat from Step 5 for the next word.
Step 13: End.
PROGRAM
import java.util.*;
class wordsincap {
public static void main() {
int i, j, vowels, cons, p, l;
String str, word, t;
char ch, ch1;
}
}
System.out.print("\nWord");
for (j = 15 - 4; j >= 1; j--)
23
System.out.print(" ");
System.out.println("\tVowels\tConsonants");
p = 0;
for (i = 0; i < l; i++) {
ch = str.charAt(i);
if (ch != ' ' && ch != '.' && ch != '?') {
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) {
24
OUTPUT
Enter :
IS WAR BAD?
IS WAR BAD?
25
Question 7
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:
Example 1:
INPUT:
m = 10
n = 100
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2:
INPUT:
m = 1200
n = 1300
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
1207, 1216, 1225, 1234, 1243, 1252, 1261, 1270, 1288
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9
Example 3:
INPUT:
m = 120
n = 99
OUTPUT:
INVALID INPUT
ALGORITHM
Step 1: Start
Step 2: Accept two positive integers m and n as user input.
Step 3: Check if m is less than n. If not, display an error message and end the program.
Step 4: Initialize a list 'compositeMagicIntegers' to store numbers that are both composite
and magic in the range [m, n].
Step 5: Iterate through each number in the range [m, n].
Step 6: Check if the current number is composite and magic using separate functions for
checking compositeness and magic property.
Step 7: If yes, add the number to the 'compositeMagicIntegers' list.
Step 8: Display the 'compositeMagicIntegers' list.
Step 9: Display the frequency of composite magic integers.
Step 10: End.
26
PROGRAM
import java.util.*;
class compositeMagicNumber
{
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter m: ");
int m = sc.nextInt();
if (num == 1) {
count++; //counting frequency of the numbers
System.out.print(i + " ");
27
}
}
}
System.out.println(); //printing the frequency
System.out.println("Frequency of composite magic numbers: " + count);
}
}
OUTPUT
Enter m: 130
Enter n: 250
The composite magic numbers are:
136 145 154 172 190 208 217 226 235 244
Frequency of composite magic numbers: 10
28
Question 8
Write a program to declare a square matrix A[][] of order MXM where M is an positive
integer and represents row and column. M should be greater than 2 and less than 10.Accept
the value of M from the user. Display an appropriate message for invalid input.
Perform the following task:
1. Display the original matrix
2. Check if the given matrix is symmetric or not. If the element of the ith row and jth
column is the same as the element of the jth row and ith column.
3. Find the sum of the left and right diagonal of the matrix and display them
Example 1
INPUT : M=3
1 2 3
2 4 5
3 5 6
OUTPUT :
ORIGINAL MATRIX
1 2 3
2 4 5
3 5 6
THE GIVEN MATRIX IS SYMMETRIC
The sum of the left diagonal = 11
The sum of the right diagonal = 10
Example 2
INPUT : M=4
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
OUTPUT :
ORIGINAL MATRIX
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
THE GIVEN MATRIX IS NOT SYMMETRIC
The sum of the left diagonal = 17
The sum of the right diagonal = 20
Example 3
INPUT : M = 22
OUTPUT : THE MATRIX SIZE IS OUT OF RANGE
ALGORITHM
Step 1: Start
Step 2: Accept a positive integer 'M' from the user.
Step 3: Check if 'M' is greater than 2 and less than 10. If not, display an error message
and end the program.
Step 4: Declare a square matrix A[][] of order MXM.
29
Step 5: Allow the user to input integers into the matrix A[][].
Step 6: Display the original matrix A[][].
Step 7: Initialize a variable 'isSymmetric' to true.
Step 8: Check if the matrix A[][] is symmetric:
Step 9: Iterate through each element of the matrix.
Step 10: Compare the element of the ith row and jth column with the element of the jth
row and ith column.
Step 11: If any pair of elements is not equal, set 'isSymmetric' to false and break from the
loop.
Step 12: If 'isSymmetric' is true, display a message indicating that the matrix is
symmetric; otherwise, display a message indicating that it is not.
Step 13: Calculate the sum of the left diagonal of the matrix.
Step 14: Calculate the sum of the right diagonal of the matrix.
Step 15: Display the sum of the left diagonal.
Step 16: Display the sum of the right diagonal.
Step 17: End.
PROGRAM
import java.util.*;
class symMatrix
{
public static void display(int A[][])
{
for (int r = 0; r <A.length; r++) {
for (int c = 0; c <A.length; c++) {
System.out.print(A[r][c] + "\t"); //displaying matrix elements
}
System.out.println();
}
}
31
OUTPUT
M=4
Enter matrix elements
124
12
35
12
789
45
908
54
087
67
98
456
089
576
0897
679
ORIGINAL MATRIX
124 12 35 12
789 45 908 54
87 67 98 456
89 576 897 679
THE GIVEN MATRIX IS NOT SYMMETRIC
The sum of the left diagonal = 946
The sum of the right diagonal = 1076
32
Question 9
Write a program to accept a sentence which may be terminated by either '.', '?', or '!' only.
Any other character may be ignored. The words may be separated by more than one blank
space and are in UPPER CASE.
Perform the following tasks.
1. Accept the sentence and reduce all the extra blank space between two words to a single blank
space.
2. Accept a word from the user which is part of the sentence along with its position number and
delete the word and display the sentence.
Test your program with the sample data and some random data.
Example 1
INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
OUTPUT: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
Example 2
INPUT: AS YOU SOW, SO SO YOU REAP.
WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4
OUTPUT: AS YOU SOW, SO YOU REAP.
Example 3
INPUT: STUDY WELL ##
OUTPUT: INVALID INPUT
ALGORITHM:
Step 1: Start
Step 2: Accept a sentence terminated by '.', '?', or '!' from the user.
Step 3: Iterate through the sentence to reduce extra blank spaces between words to a
single blank space.
Step 4: Initialize a new string 'processedSentence' to store the modified sentence.
Step 5: Iterate through each character in the input sentence.
Step 6: If the current character is not a blank space or the previous character was not a
blank space, append it to 'processedSentence'.
Step 7: Accept a word from the user along with its position number.
Step 8: Tokenize the processed sentence into words.
Step 9: Initialize a counter variable to keep track of the position number of words.
Step 10: Iterate through each word in the tokenized sentence.
Step 11: If the current word matches the user-provided word and its position matches the
input position, skip appending this word.
Step 12: Otherwise, append the word to a new string 'modifiedSentence' with proper
spacing.
Step 13: Display the modified sentence 'modifiedSentence'.
Step 14: End.
33
PROGRAM
import java.util.*;
class word_delete {
public static void main() {
int i = 0, count = 1, len = 0, pos = 0;
char ch = ' ', last = ' ';
String sen = "", newsen = "", wd = "", wd1 = "";
Scanner sc = new Scanner(System.in);
System.out.print("ENTER A SENTENCE: ");
sen = sc.nextLine(); //input sentence
len = sen.length();
last = sen.charAt(len - 1);
if (last != '.' && last != '?' && last != '!') { //if does not end in . or ?
System.out.println("INVALID INPUT.");
System.exit(0);
}
sen = sen.toUpperCase(); //converting to uppercase
} else {
newsen = newsen + wd1 + ch; //not the word to be deleted
}
wd1 = "";
count++;
} else {
wd1 = wd1 + ch;
}
}
System.out.println("OUTPUT:" + newsen); //printing after deleting word
}
}
34
VARIABLE DESCRIPTION TABLE
OUTPUT
ENTER A SENTENCE: A MORNING WALK IS GOOD FOR YOUR HEALTH.
WORD TO BE DELETED: WALK
WORD POSITION IN THE SENTENCE: 3
OUTPUT: A MORNING IS GOOD FOR YOUR HEALTH.
35
Question 10
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.
For example:
1. 02011003311 = 10 x 0 + 9 x 2 + 8 x 0 + 7 x 1 + 6 x 1 + 5 x 0 + 4 x 3 + 3 x 3 + 2 x 1 + 1 x 1 = 55
Since 55 leaves no remainder when divisible by 11, hence it is a valid ISBN.
2. 007462542X = 10 x 0 + 9 x 0 + 8 x 7 + 7 x 4 + 6 x 6 + 5 x 2 + 4 x 5 + 3 x 4 + 2 x 2 + 1 x
10 = 176 Since 176 leaves no remainder when divided by 11, hence it is a valid ISBN.
3. 0112112425 = 10 x 0 + 9 x 1 + 8 x 1 + 7 x 2 + 6 x 1 + 5 x 1 + 4 x 1 + 3 x 4 + 2 x 2 + 1 x
5 = 71 Since 71 leaves no remainder when divided by 11, hence it is not a valid ISBN.
Design a program to accept a ten digit code from the user. For an invalid input, display an
appropriate message. Verify the code for its validity in the format specified below:
Test your program with sample data and some random data.
Example 1
INPUT CODE: 0201530821
OUTPUT : SUM = 99
LEAVES NO REMAINDER – VALID ISBN CODE
Example 2
INPUT CODE: 035680324
OUTPUT : INVALID INPUT
Example 3
INPUT CODE: 0231428031
OUTPUT : SUM = 122
LEAVES REMAINDER – INVALID ISBN CODE
ALGORITHM
Step 1: Start
Step 2: Accept a ten-digit ISBN code from the user.
Step 3: Initialize a variable 'sum' to 0.
Step 4: Iterate through each digit of the ISBN from left to right.
Step 5: Multiply the current digit by its position (10 for the first digit, 9 for the second,
and so on).
Step 6: Add the result to the 'sum'.
Step 7: If the last digit is 'X', treat it as 10 and add it to the 'sum'.
Step 8: Check if the 'sum' is divisible by 11.
Step 9: If yes, display a message indicating that the ISBN is valid.
Step 10: If no, display a message indicating that the ISBN is not valid.
Step 11: End.
36
PROGRAM
import java.util.*;
public class ISBNnumber {
public static void main() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the ISBN: ");
long isbn = in.nextLong();
37
VARIABLE DESCRIPTION TABLE
OUTPUT
Enter the ISBN: 018224012
INVALID INPUT8
Enter the ISBN: 1234567890
Sum = 210
LEAVES REMAINDER – INVALID ISBN CODE
Enter the ISBN: 0201530821
Sum = 99
LEAVES NO REMAINDER – VALID ISBN CODE
38
Question 11
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:
Example 1
INPUT : M = 3
4 16 12
8 2 14
4 1 3
OUTPUT :
ORIGINAL MATRIX
4 16 12
8 2 14
4 1 3
MIRROR IMAGE MATRIX
12 16 4
14 2 8
3 1 6
Example 2
INPUT : M = 22
OUTPUT : SIZE OUT OF RANGE
ALGORITHM
Step 1: Start
Step 2: Accept a positive integer 'M' from the user.
Step 3: Check if 'M' is greater than 2 and less than 20. If not, display an error message
and end the program.
Step 4: Declare a square matrix A[][] of order (M x M).
Step 5: Allow the user to input integers into the matrix A[][].
Step 6: Display the input matrix A[][].
Step 7: Initialize a new matrix 'mirrorMatrix' of the same order as A[][].
Step 8: Create a mirror image of the input matrix:
STEP 9: Iterate through each element of the matrix A[][].
STEP 10: Assign the element at the current position to the corresponding position in
'mirrorMatrix', but mirrored along the vertical axis.
Step 11: Display the mirror image matrix 'mirrorMatrix'.
Step 12: End.
PROGRAM
import java.util.*;
39
class mirrormat
{
public static void main() {
int M, i, j, k, t;
System.out.println("ORIGINAL MATRIX");
for (i = 0; i < M; i++) {
for (j = 0; j < M; j++) {
System.out.print(A[i][j] + " "); //printing original matrix
}
System.out.println();
}
t = A[i][j];
A[i][j] = A[i][k];
A[i][k] = t;
}
}
System.out.println("MIRRORED MATRIX");
for (i = 0; i < M; i++) {
for (j = 0; j < M; j++) {
System.out.print(A[i][j] + " "); //printing the mirrored matrix
40
}
System.out.println();
}
} }
}
OUTPUT
7895
ORIGINAL MATRIX
234 1 246
3679 364 78
796 674 7895
MIRRORED MATRIX
246 1 234
78 364 3679
7895 674 796
41
Question 12
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:
Example 1
INPUT : MOM AND DAD ARE COMING AT NOON.
OUTPUT : MOM DAD NOON
NUMBER OF PALINDROMIC WORDS : 3
Example 2
INPUT : NITIN ARORA USES LIRIL SOAP.
OUTPUT : NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS : 3
Example 3
INPUT : HOW ARE YOU?
OUTPUT : NO PALINDROMIC WORDS
ALGORITHM
Step 1: Start
Step 2: Accept a sentence in UPPER CASE terminated by ".", "?", or "!" from the user.
Step 3: Tokenize the sentence into words using a single blank space as a separator.
Step 4: Initialize variables for counting palindromic words and storing palindromic
words.
Step 5: Iterate through each word in the tokenized sentence.
STEP 6: Check if the current word is a palindrome:
STEP 7: Initialize two pointers, one at the beginning and one at the end of the current
word.
STEP 8: Compare characters at the pointers.
STEP 9: If characters are not equal, the word is not a palindrome; otherwise, continue
comparing until the pointers meet.
STEP 10: If pointers meet, add the word to the list of palindromic words and increment
the count.
Step 11: Display the count of palindromic words.
Step 12: Display the palindromic words.
Step 13: End.
42
PROGRAM
import java.util.*;
class Palindromic {
boolean isPalindrome(String str) {
String rev = "";
boolean f = false;
}
}
if (c == 0) { //no palindrome words found
System.out.print(" NO PALINDROMIC WORDS");
} else {
System.out.println("\nNUMBER OF PALINDROMIC WORDS : " + c);
43
}
}
}
OUTPUT
Enter sentence
The radar was placed at a low level
INVALID INPUT.
Enter sentence
The radar was placed at a low level.
radar a level
NUMBER OF PALINDROMIC WORDS : 3
44
Question 13
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:
Example 1
INPUT:
m=100
n = 1000
OUTPUT:
THE PRIME PALINDROME INTEGERS ARE:
101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929
FREQUENCY OF PRIME PALINDROME INTEGERS : 15
Example 2
INPUT:
m = 100
n = 5000
OUTPUT: OUT OF RANGE
ALGORITHM
Step 1: Start
Step 2: Accept two positive integers m and n from the user where m < 3000 and n <
3000.
Step 3: Initialize a variable 'count' to 0 to store the count of prime palindrome integers.
Step 4: Iterate through the range [m, n].
STEP 5: Check if the current number is a prime palindrome:
STEP 6: Check if the number is prime using a prime-checking function.
STEP 7: Initialize a variable 'isPrime' to true.
STEP 8: Iterate from 2 to the square root of the number.
STEP 9: If the number is divisible by any of these values, set 'isPrime' to false and break
from the loop.
STEP 10: If 'isPrime' is still true, the number is prime.
STEP 11: Check if the number is a palindrome using a palindrome-checking function.
STEP 12: Convert the number to a string.
STEP 13: Initialize two pointers, one at the beginning and one at the end of the string
representation.
STEP 14: Compare characters at the pointers.
STEP 15: If characters are not equal, the number is not a palindrome; otherwise, continue
comparing until the pointers meet.
STEP 16: If pointers meet, the number is a palindrome.
45
STEP 17: If the number is both prime and a palindrome, increment 'count' and display the
number.
Step 18: Display the count of prime palindrome integers.
Step 19: End.
PROGRAM
import java.util.*;
class primepalindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int m, n, i, j, t, c, r, a, freq;
System.out.println("Enter two positive integers m and n( m< 3000 and n < 3000): ");
m = sc.nextInt();
n = sc.nextInt();
freq = 0;
t = i;
c = 0;
for (j = 1; j <= t; j++) { //checkimg for prime
if (t % j == 0)
c++;
}
if (c == 2) {
r = 0;
while (t > 0) {
a = t % 10;
r = r * 10 + a; //reversing the integer
t = t / 10;
}
if (r == i) { // checking for palindrome
System.out.print(i + " "); //printing prime palindrome number
freq++;
}
}
46
}
System.out.println("\nFrequency of prime palindrome integers:" + freq);
} else {
System.out.println("OUT OF RANGE");
}
}
}
OUTPUT
Enter two positive integers m and n( m< 3000 and n < 3000):
110
250
The prime palindrome integers are:
131 151 181 191
Frequency of prime palindrome integers :4
47
Question 14
Write a program to accept a sentence as input. The words in the string are to be separated by
a blank. Each word must be in upper case. The sentence is terminated by either '.','!' or '?'.
Perform the following tasks:
1. Obtain the length of the sentence (measured in words)
2. Arrange the sentence in alphabetical order of the words.
Test your program with the sample data and some random data:
Example 1:
INPUT: NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT:
Length: 6
Rearranged Sentence:
INVENTION IS MOTHER NECESSITY OF THE
Example 2:
INPUT: BE GOOD TO OTHERS.
OUTPUT:
Length: 4
Rearranged Sentence: BE GOOD OTHERS TO
ALGORITHM
Step 1: Start
Step 2: Accept a sentence terminated by '.', '!', or '?' from the user. Ensure each word is in
upper case.
Step 3: Tokenize the sentence into words using a blank space as a separator.
Step 4: Obtain the length of the sentence (number of words) by counting the tokens.
STEP 5: Initialize a variable 'length' to 0.
STEP 6: Iterate through each word in the tokenized sentence and increment 'length' for
each word.
Step 7: Display the length of the sentence.
Step 8: Arrange the sentence in alphabetical order:
STEP 9: Create an array or list to store the words.
STEP 10: Iterate through each word in the tokenized sentence and add it to the array.
STEP 11: Sort the array in alphabetical order.
STEP 12: Display the sentence in alphabetical order.
Step 13: End.
PROGRAM
import java.util.*;
class alphabetical
{
public static void main() {
Scanner sc = new Scanner(System.in);
int i, j, l, p, x, now;
48
String str, word, temp;
char ch;
now = 0;
char last = str.charAt(str.length() - 1);
if (last != '.' && last != '?' && last != '!') {
System.out.println("INVALID INPUT.");
System.exit(0);
}
for (i = 0; i < l; i++) {
ch = str.charAt(i);
if (ch == ' ' || ch == '?' || ch == '.' || ch == '!')
now++; //counting number of tokens
}
x = 0;
p = 0;
OUTPUT
50
Question 15
Write a program to declare a matrix A [][] of order (MXN) where 'M' is the number of rows
and 'N' is the number of columns such that both M and N must be greater than 2 and less
than 20. Allow the user to input integers into this matrix.
Perform the following tasks on the matrix:
1. Display the input matrix
2. Find the maximum and minimum value in the matrix and display them along with their position.
3. Sort the elements of the matrix in ascending order using any standard sorting technique and
rearrange them in the matrix.
Output the rearranged matrix.
Example 1
INPUT:
M=3
N=4
Entered values: 8,7,9,3,-2,0,4,5,1,3,6,-4
OUTPUT:
Original matrix:
8 7 9 3
-2 0 4 5
1 3 6 -4
Largest Number: 9
Row: 0
Column: 2
Smallest Number: -4
Row=2
Column=3
Rearranged matrix:
-4 -2 0 1
3 3 4 5
6 7 8 9
ALGORITHM
Step 1: Start
Step 2: Accept two positive integers 'M' and 'N' from the user where both M and N are
greater than 2 and less than 20.
Step 3: Declare a matrix A[][] of order (M x N).
Step 4: Allow the user to input integers into the matrix A[][].
Step 5: Display the input matrix A[][].
Step 6: Find the maximum and minimum values in the matrix:
STEP 7: Initialize variables 'maxValue', 'minValue', 'maxRow', and 'maxColumn' to store
maximum and minimum values along with their positions.
STEP 8: Iterate through each element of the matrix.
STEP 9: Compare the current element with 'maxValue' and 'minValue'.
STEP 10: Update 'maxValue', 'minValue', 'maxRow', and 'maxColumn' if needed.
STEP 11: Display the maximum and minimum values along with their positions.
Step 12: Sort the elements of the matrix in ascending order:
STEP 13: Flatten the matrix into a 1D array.
51
STEP 14: Use any standard sorting technique to sort the 1D array in ascending order.
STEP 15: Rearrange the sorted elements back into the matrix A[][].
Step 16: Display the matrix A[][] after sorting.
Step 17: End.
PROGRAM
import java.util.*;
class maxminsort {
public static void main() {
Scanner scan = new Scanner(System.in);
int m,n,i,j,x,t,min,rowS,colS,max,rowL,colL;
System.out.println("Enter number of rows and columns (2 < number < 20): ");
m = scan.nextInt();
n = scan.nextInt();
if (m > 2 && m < 20 && n > 2 && n < 20) {
min = a[0][0];
max = a[0][0];
rowS = colS = rowL = colL = 0;
52
b[x++] = a[i][j];
//finding minimum value
if (min > a[i][j]) {
min = a[i][j];
rowS = i;
colS = j;
} //finding maximum value
if (max < a[i][j]) {
max = a[i][j];
rowL = i;
colL = j;
}
}
}
//rearranging matrix
for (i = 1; i < x; i++) {
for (j = 0; j < x - i; j++) {
x = 0;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a[i][j] = b[x++];
}
}
} else {
System.out.println("Invalid value");
}
}
}
OUTPUT
54
4
37777
3467
23
865
235
Original Matrix:
375 35375 2354 679 354
8 346 78 32 879
352 769 83 35 4
37777 3467 23 865 235
4 8 23 32 35
78 83 235 346 352
354 375 679 769 865
879 2354 3467 35375 37777
55
Question 16
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
Examples
Input: 29
Output: TWENTY NINE
Input: 17001
Output: OUT OF RANGE
Input: 119
Output: ONE HUNDRED AND NINETEEN
Input: 500
Output: FIVE HUNDRED
ALGORITHM
Step 1: Start
Step 2: Accept a natural number 'num' from the user, ensuring it is less than 1000.
Step 3: Check if 'num' is greater than or equal to 1000. If yes, display an error message
and end the program.
Step 4: Define arrays or lists to store words for the units, tens, and special cases (e.g.,
teens).
Step 5: Divide 'num' into hundreds, tens, and units places.
STEP 6: Calculate the hundreds place, tens place, and units place separately.
Step 7: Convert each place value into words using the defined arrays or lists.
Step 8: Construct the final word representation of the number.
STEP 9: If the number is greater than 99, append the word for hundreds place.
STEP 10: If the tens‟ place is 1, append the word for teens (special cases).
STEP 11: If the tens place is greater than 1, append the word for tens place.
STEP 12: If the units place is greater than 0, append the word for units place.
Step 13: Display the word representation of the number.
Step 14: End.
PROGRAM
import java.util.*;
class number {
public static void main() {
int n;
}
}//main
}//class
57
VARIABLE DESCRIPTION TABLE
Variable DataType Description
n int The input number
result String The string representation of the input number in words
h String The hundreds part of the input number in words
t String The tens part of the input number in words
o String The ones part of the input number in words
a int The hundreds digit of the input number
b int The tens digit of the input number
c int The ones digit of the input number
ones String[] Array of strings containing the names of the ones digits
teens String[] Array of strings containing the names of the teen numbers
tens String[] Array of strings containing the names of the tens digits
OUTPUT
58
Question 17
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. Display
the encrypted sentences as per the sample data given below.
Test your program on the sample data and some random data.
Example 1
INPUT: n = 4
IT IS CLOUDY.
IT MAY RAIN.
THE WEATHER IS FINE.
IT IS COOL.
OUTPUT:
KV KU ENQWFA.
RAIN MAY IT.
VJG YGCVJGT KU HKPG.
COOL IS IT.
ALGORITHM
Step 1: Start
Step 2: Accept an integer 'n' as the size of the array from the user, ensuring it is greater
than 1 and less than 10.
Step 3: Check if 'n' satisfies the given conditions. If not, display an error message and end
the program.
Step 4: Declare a String array 'sentences' of size 'n'.
Step 5: Iterate through each row of the 'sentences' array and accept a sentence for each
row.
STEP 6: For odd rows, encrypt the sentence by shifting each character two positions
ahead.
STEP 7: Initialize a new empty string 'encryptedSentence'.
STEP 8: Iterate through each character in the sentence.
STEP 9: Shift the character two positions ahead and append it to 'encryptedSentence'.
STEP 10: Store 'encryptedSentence' in the corresponding row of the 'sentences' array.
STEP 11: For even rows, reverse the sentence.
STEP 12: Initialize a new empty string 'reversedSentence'.
STEP 13: Iterate through each character in the sentence in reverse order.
STEP 14: Append the character to 'reversedSentence'.
STEP 15: Store 'reversedSentence' in the corresponding row of the 'sentences' array.
Step 16: Display the encrypted sentences in the 'sentences' array.
59
Step 17: End.
PROGRAM
import java.util. * ;
class encrysen {
String input() {
Scanner sc = new Scanner(System. in );
return sc.nextLine();
}
void encrypt(String s) {
int i,len;
char ch;
String st = "";
len = s.length();
for (i = 0; i < len; i++) {
ch = s.charAt(i);
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) {
ch = (char)(ch + 2); //shifting character to +2 of it ASCII
if (ch > 90 && ch < 97) {
ch = (char)((64 + ch - 90));
}
else if (ch > 122) {
ch = (char)((96 + ch - 122));
}
}
st = st + ch; //adding to the string
}
System.out.println(st);
}
void reverse(String s) {
s = s.trim();
s = s.substring(0, s.length() - 1);
int i;
String t = "";
StringTokenizer st = new StringTokenizer(s);
int n = st.countTokens();
for (i = 0; i < n; i++) { //reversing the inputted string
String c = st.nextToken();
t = c + " " + t;
}
System.out.println(t + ".");
}
public static void main() {
encrysen obj = new encrysen();
String str[],s;
60
int i,n;
Scanner sc = new Scanner(System. in );
61
OUTPUT
Enter number of sentences:
5
Enter sentences
IT IS A GOOD DAY.
IT MIGHT RAIN TOMMOROW.
SCHOOL WAS CLOSED YESTERDAY.
WE HAVE FINISH PROJECTS BEFORE DEADLINE.
TECHNOLOGY IS EXPONENTIALLY EXPANDING EVERYDAY.
DAY GOOD A IS IT .
KV OKIJV TCKP VQOOQTQY.
YESTERDAY CLOSED WAS SCHOOL .
YG JCXG HKPKUJ RTQLGEVU DGHQTG FGCFNKPG.
EVERYDAY EXPANDING EXPONENTIALLY IS TECHNOLOGY .
62
Question 18
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.
Testing of the program
Example 1
INPUT: Enter your date of birth in dd mm yyyy format
05
01
2010
OUTPUT: VALID DATE
5
Example 2
INPUT: Enter your date of birth in dd mm yyyy format
03
04
2010
OUTPUT: VALID DATE
93
Example 3
INPUT: Enter your date of birth in dd mm yyyy format
34
06
2010
OUTPUT: INVALID DATE
ALGORITHM
Step 1: Start
Step 2: Accept the date of birth in dd mm yyyy format from the user.
Step 3: Extract the day, month, and year components from the input.
Step 4: Check if the day, month, and year are valid.
STEP 5: Check if the month is between 1 and 12.
STEP 6: Check if the day is valid for the given month (considering leap years for
February).
STEP 7: Check if the year is a valid positive integer.
STEP 8: If any of the conditions in Steps 5-7 fails, display "INVALID DATE" and
terminate the program.
Step 9: Calculate the day number of the year.
STEP 10: Initialize an array 'daysInMonth' to store the number of days in each month.
STEP 11: Calculate the day number by summing the days of the months preceding the
given month and adding the day.
Step 12: Display "VALID DATE".
Step 13: Display the calculated day number.
Step 14: End.
63
PROGRAM
import java.util.*;
class DOB {
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your date of birth in dd_mm_yyyy format : ");
int d = sc.nextInt();
int m = sc.nextInt();
int y = sc.nextInt();
int dom[] = {31,28,31,30,31,30,31,31,30,31,30,31}; //number of days in months
if (y % 400 == 0 || (y % 100 != 0 && y % 4 == 0)) //if leap year
dom[1] = 29; //29 days in february in leap year
if (d <= dom[m - 1]) {
System.out.println("VALID DATE ");
int i, s = 0;
for (i = 0; i < m - 1; i++)
s = s + dom[i];
System.out.print(s);
} else {
System.out.println("INVALID DATE");
}
}//main
}//class
OUTPUT
ALGORITHM
Step 1: Start
Step 2: Accept the amount from the user.
Step 3: Check if the amount is a valid positive integer.
STEP 4: If not, display "INVALID AMOUNT" and terminate the program.
Step 5: Convert the amount to words.
STEP 6: Initialize arrays or lists to store the words for each digit.
STEP 7: Iterate through each digit in the amount and append the corresponding word to
the result.
Step 8: Display the amount in words.
Step 9: Determine the denomination breakdown.
STEP 10: Initialize an array 'denominations' with the available denominations [1000,
500, 100, 50, 20, 10, 5, 2, 1].
STEP 11: Iterate through each denomination in 'denominations'.
STEP 12: Calculate the number of notes for the current denomination.
STEP 13: If the number of notes is greater than 0, display the denomination and the
number of notes.
Step 14: End.
PROGRAM
import java.util.*;
class denomination {
65
public static void main() {
p = amt;
String ones[] = {"one","two","three","four","five","six","seven","eight","nine"};
r = 0;
while (p > 0) {
r = r * 10 + p % 10;
p /= 10;
}
while (r > 0) {
b = r % 10;
System.out.print(ones[b - 1].toUpperCase() + " "); //printing name
r /= 10;
}
System.out.println("\nDenomination :"); //printing denominations
for (i = 0; i <a.length; i++) {
t = amt / a[i]; // till amount is divisible by highest denomination
if (t != 0) {
System.out.println(a[i] + "X" + t + "=" + (t * a[i]));
amt = amt % a[i];
}
}
}
}//main
}//class
66
VARIABLE DESCRIPTION TABLE
Variable DataType Description
amt int The amount entered by the user.
a[] int[] Array of denominations
i int Loop counter
p int Temporary variable to store the amount in reverse order
r int Temporary variable to store the reversed amount
b int Temporary variable to store the digit at the current position
Temporary variable to store the number of notes of the current
t int denomination
ones[] String[] Array of strings containing the names of the ones digits
OUTPUT
67
Question 20
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 the sum of the pieces is equal to the number then it's a Kaprekar number.
Example 1
INPUT:
p=1
q=1000
OUTPUT:
THE KAPREKAR NUMBERS ARE:
1,9,45,55,99,297,999
FREQUENCY OF KAPREKAR NUMBERS IS:8
ALGORITHM
Step 1: Start
Step 2: Accept two positive integers p and q from the user, ensuring that p < q.
Step 3: Initialize variables for counting Kaprekar numbers and storing them.
Step 4: Iterate through the range [p, q].
STEP 5: Calculate the square of the current number.
STEP 6: Convert the square to a string to determine the number of digits.
STEP 7: Iterate through each possible split position (from 1 to the number of digits - 1).
STEP 8: Extract the left and right pieces based on the split position.
STEP 9: Convert the left and right pieces to integers.
STEP 10: Check if the sum of the left and right pieces is equal to the original number.
STEP 11: If yes, it is a Kaprekar number. Increment the count and store the number.
Step 12: Display the Kaprekar numbers.
Step 13: Display the frequency of Kaprekar numbers.
Step 14: End.
PROGRAM
import java.util.*;
class kaprekar {
public static void main() {
int d, i, n, a, b, s;
int ff = 0;
68
System.out.println("The Kaprekar numbers are : ");
for (i = p; i <= q; i++) {
n = i;
d = 0;
while (n > 0) {
d++;
n /= 10;
}
//finding if a kaprekar number
s = i * i;
a = s % (int) Math.pow(10, d); //first half of the square of number
OUTPUT
Enter range :
35
100
The Kaprekar numbers are :
45 55 99
FREQUENCY OF KAPREKAR NUMBER IS : 3
69
Question 21
Input a paragraph containing 'n' number of sentences where (1<=n<=4). The words are to be
separated with a 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.
Example 1
INPUT: Enter number of sentences: 1
Enter sentences:
TO BE OR NOT TO BE.
OUTPUT:
Total number of words: 6
WORD FREQUENCY
OR 1
NOT 1
TO 2
BE 2
Example 2
INPUT: Enter number of sentences: 3
Enter sentences:
THIS IS A STRING PROGRAM. IS THIS EASY? YES, IT IS.
OUTPUT:
Total number of words: 11
WORD FREQUENCY
A 1
STRING 1
PROGRAM 1
EASY 1
YES 1
IT 1
THIS 2
IS 3
ALGORITHM
Step 1: Start
Step 2: Accept the number of sentences 'n' from the user, ensuring that 1 <= n <= 4.
STEP 3: If 'n' exceeds the limit, display a message and terminate the program.
Step 4: Initialize a dictionary or map to store word frequencies.
Step 5: Iterate 'n' times to accept each sentence from the user.
Step 6: Tokenize each sentence into words using a single blank space as a separator.
Step 7: Update the word frequencies in the dictionary.
Step 8: Calculate the total number of words in the paragraph.
STEP 9: Iterate through the dictionary to sum the frequencies.
Step 10: Display the total number of words.
Step 11: Display the words in ascending order with their frequencies.
STEP 12: Sort the dictionary based on keys (words).
STEP 13: Display the sorted words along with their frequencies.
70
Step 14: End.
PROGRAM
import java.util.*;
class freqword
{
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of sentences.");
int n = sc.nextInt();
if (n < 1 || n >4)
{
System.out.println("Invalid Entry");
System.exit(0);
}
System.out.println("Enter sentence");
sc.nextLine();
String S = sc.nextLine();
S = S.toUpperCase();
if (j == idx) {
wrdarr[idx] = word; //inputting word in the array wrdarr
freq[idx]++; //inputting frequency of that word in array freq
71
idx++;
}
}
72
OUTPUT
Enter number of sentences.
3
Enter sentence
TODAY IS A GOOD DAY.
Total number of words: 5
Word Frequency
TODAY 1
IS 1
A 1
GOOD 1
DAY 1
73
Question 22
A class Employee contains employee details and another class Salary calculates the
employee‟s net salary. The details of the two classes are given below.
Class name – Employee
Data Members-:
empno - to store employee no
empname - to store employee name
empdesign – to store designation
Member Functions-:
Employee( ) - default contructor
Employee(---) - parameterized constructor
void display( ) – to display data members with proper message
Display the details of the class Employee and the net salary
Specify the class Employee giving the details of the functions using the concept of
inheritance and also specify the class in which object is created and functions are called in
the main function
ALGORITHM
Step 1: Start
Step 2: Define a class named "Employee" with attributes empno (employee number),
empname (employee name), and empdesign (employee designation).
Step 3: Create a constructor for the "Employee" class to initialize empno, empname, and
empdesign to default values.
Step 4: Create another constructor for the "Employee" class with parameters to set
empno, empname, and empdesign to specific values.
Step 5: Implement a method called "display" within the "Employee" class to print the
employee's name, number, and designation.
Step 6: Define a class named "Salary" that inherits from the "Employee" class and has an
additional attribute called "basic."
74
Step 7: Create a constructor for the "Salary" class that takes in parameters for basic,
employee number, employee name, and employee designation. Call the constructor of the
parent class (Employee) using the "super" keyword.
Step 8: Implement a method called "calculate" within the "Salary" class to calculate
various components of an employee's salary, including da (dearness allowance), hra
(house rent allowance), gross pay, pf (provident fund), and net pay. Display these
payment details.
Step 9: In the "calculate" method, calculate da, hra, gross pay, pf, and net pay based on
specific formulas.
Step 10: Print the employee's details (name, number, and designation) by calling the
"display" method from the parent class.
Step 11: Display the payment details, including basic, da, hra, gross pay, and net pay.
Step 12: In the "main" method, create a Scanner object to read input from the user.
Step 13: Prompt the user to enter employee details: name, number, designation, and basic
pay.
Step 14: Read the input values for employee details from the user.
Step 15: Create an instance of the "Salary" class, passing the entered values to the
constructor.
Step 16: Call the "calculate" method on the "Salary" instance to perform salary
calculations and display the results.
Step 17: Stop
PROGRAM
import java.util.*;
class Employee
{
int empno ;String empname , empdesign;
Employee()
{
empno=0;
empname="";
empdesign="";
}
Employee(int a,String b,String c)
{
empno=a;
empname=b;
empdesign=c;
}
void display()
{
System.out.println("Employee name:"+empname);
System.out.println("Employee number:"+empno);
System.out.println("Employee designation:"+empdesign);
75
}
}
76
VARIABLE DESCRIPTION TABLE
Variable DataType Description
empno int Employee number.
empname String Employee name.
empdesign String Employee designation.
basic float Employee's basic salary.
da double Employee's dearness allowance (DA).
hra double Employee's house rent allowance (HRA).
gross double Employee's gross salary.
pf double Employee's provident fund (PF).
netpay double Employee's net payable salary.
name String Employee name (input from user).
n int Employee number (input from user).
d String Employee designation (input from user).
b float Employee's basic salary (input from user).
OUTPUT
Employee Details-
Payment Details-
Basic=10000.0
DA=1000.0
HRA=1500.0
Gross Pay=12500.0
Net Pay=11500.0
77
Question 23
Design a class Prime.
Data Members-:
n - to store the number
Member Functions-:
Prime(int) - constructor to initialize n
void check( ) - to check if the no is prime or not by calling a function isPrime(int)
boolean isPrime(int,int) - returns true/false for prime using recursive technique
ALGORITHM
Step 1: Start
Step 2: Initialize an integer variable n to the user-provided value.
Step 3: Create an instance of the Prime class, passing the value of n as a parameter.
Step 4: Call the check method of the Prime instance.
Step 5: Inside the check method, call the isPrime method with the values n and 2 as
parameters.
Step 6: In the isPrime method:
Check if n is less than or equal to 2:
If true, proceed to the next step.
If false, return the result of the following sub-steps:
Check if n is equal to 2:
If true, return true (indicating n is a prime number).
If false, return false (indicating n is not a prime number).
Step 7: If n is greater than 2, check if n is divisible by i:
If it is divisible, return false (indicating n is not a prime number).
If it is not divisible, proceed to the next step.
Step 8: Check if the square of i is greater than n:
If true, return true (indicating n is a prime number).
If false, proceed to the next step.
Step 9: Increment the value of i by 1.
Step 10: Return to step 6 for the next iteration.
Step 11: The result of the isPrime method is returned to the check method.
Step 12: Inside the check method, print a message indicating whether n is a prime
number or not.
Step 13: Stop
78
PROGRAM
import java.util.*;
class Prime
{
int n;
Prime(int nn)
{ n = nn; }
void check()
{
if(isPrime(n,2)) //if true number is prime
{ System.out.println(n+" is a Prime Number."); }
else
{
System.out.println(n+" is NOT a Prime Number.");
} }
boolean isPrime(int n, int i)
{
if (n <= 2)
return (n == 2) ? true : false;
if (n % i == 0) //number is even hence not a prime number
return false;
if (i * i > n) //number is 3, which is prime
return true;
return isPrime(n, i + 1); //recursive parameter to check for prime
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
int nn = sc.nextInt();
Prime obj = new Prime(nn); //creating an object of the class Prime
obj.check();
}}
79
OUTPUT
Enter number:
71
71 is a Prime Number.
Enter number:
12
12 is NOT a Prime Number.
80
Question 24
Design a class Stack-:
Data Members-:
int arr[ ] – size 50
int size – store no of elements
int top
Member Functions-:
Stack(int s) – to initialize the size by s and top by -1
void pushvalues(int v) – to fill the stack if it is empty otherwise display message –
“overflow”
int popvalues() – to delete value from the stack and return it, if possible otherwise
display – “underflow” and return -999
void display()
void main()
ALGORITHM
Step 1: Start
Step 2: Initialize an array `arr` of size 50, a variable `size` to store the number of
elements, and a variable `top` to -1.
Step 3: Define a constructor `Stack(int s)` to initialize `size` with `s` and `top` with -1.
Step 4: In the constructor, set `size` to `s`, and `top` to -1.
Step 5: Define a method `pushvalues(int v)`.
Step 6: Check if the stack is not full (`top` is less than `size - 1`).
- If true, increment `top` by 1 and assign the value `v` to `arr` at the `top` index.
- If false, display the message "overflow."
Step 7: Define a method `popvalues()`.
Step 8: Check if the stack is not empty (`top` is greater than or equal to 0).
- If true, retrieve the value at `arr[top]`, decrement `top` by 1, and return the value.
- If false, display the message "underflow" and return -999.
Step 9: Define a method `display()`.
Step 10: Iterate from `i = 0` to `i = top`.
- Display the element `arr[i]`.
Step 11: End
PROGRAM
import java.util.*;
class stack
{
int arr[];
int size;
int top;
stack(int s)
81
{
size=s;
top=-1;
arr = new int[size]; //initializing the stack array
}
void pushvalues(int v)
{
if(top< size-1)
{
arr[++top] = v; //inserting value to the top
}
else
{
System.out.println("Stack overflow"); //stack is full
}
}
int popvalues()
{
int x = -999;
if(top!=-1) //if array is not empty
{
x = arr[top--]; //deleting value from the top of the array
}
return x;
}
void display()
{
if(top==-1)
{
System.out.println("Stack is empty");
}
else //array not empty
{
for(int i=top;i>-1;i--)
{
System.out.println(arr[i]); //printing array elements
} } }
public static void main()
{
Scanner sc = new Scanner(System.in);
int c,n,d;
stack obj = new stack(50);
do
82
{
System.out.println(“PRESS 1 TO PUSH VALUE | PRESS 2 TO POP VALUE |
\n PRESS 3 TO DISPLAY | PRESS 4 TO EXIT”);
System.out.println("Enter your choice");
c= sc.nextInt(); //take the input of user of which function to use
switch(c) //performing the function
{
case 1:
System.out.println("Enter number to insert");
n = sc.nextInt();
obj.pushvalues(n);
break;
case 2:
d = obj.popvalues();
if(d!=-9999)
System.out.println("Deleted value is "+d);
break;
case 3:
obj.display();
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid Choice");
} }
while(c!=4);
}}
83
OUTPUT
84
Question 25
Design a class SQ
Data Members-:
int arr[ ] – max size 100
int size – store the capacity of arr
int front
int rear
Member Functions-:
SQ(int s) – to initialize the size and front and rear by -1
void addrear(int v) – to add value at rear if possible otherwise display “Queue full at
the rear end… OVERFLOW”
int deletefront() – to delete value from front if possible otherwise display “Queue
empty…UNDERFLOW”
void display() – display elements of the queue
ALGORITHM
Step 1: Start
Step 2: Initialize an array `arr` of max size 100, variables `size`, `front`, and `rear` to -1.
Step 3: Define a constructor `SQ(int s)` to initialize `size`, `front`, and `rear` with -1.
Step 4: In the constructor, set `size` to `s`, `front` to -1, and `rear` to -1.
Step 5: Define a method `addrear(int v)`.
Step 6: Check if the queue is not full (the difference between `rear` and `front` is less
than `size - 1`).
- If true, increment `rear` by 1 and assign the value `v` to `arr` at the `rear` index.
- If false, display the message "Queue full at the rear end... OVERFLOW."
Step 7: Define a method `deletefront()`.
Step 8: Check if the queue is not empty (`front` is less than or equal to `rear`).
- If true, retrieve the value at `arr[front]`, increment `front` by 1, and return the value.
- If false, display the message "Queue empty... UNDERFLOW."
Step 9: Define a method `display()`.
Step 10: Iterate from `i = front` to `i = rear`.
- Display the element `arr[i]`.
Step 11: End
PROGRAM
import java.util.*;
class Queue
{
int size = 10;
int front = -1;
int rear = -1;
int que[];
85
public Queue()
{
que = new int[size]; //initializing the array
}
87
VARIABLE DESCRIPTION TABLE
Variable DataType Description
size int The size of the queue.
front int The index of the first element in the queue.
rear int The index of the last element in the queue.
que[] int[] The queue array.
c int The user's choice of operation.
n int The number to be added to the queue.
d int The number deleted from the queue.
OUTPUT
PRESS 1 TO ADD VALUE | PRESS 2 TO DELETE VALUE
PRESS 3 TO DISPLAY | PRESS 4 TO EXIT
88