Java Programs for Class XII
Java Programs for Class XII
C la ss : XII - G
In de x N o. : 17
UI D: _ ___ __ ___ __ __
Inte rn al Ex aminer ’ s si gn :
_ ___ __ ___ _
E xtern al Ex aminer ’ s si gn :
_ ___ __ ___ _
2
Index
S.No. Program Pg No.
1 Circular Prime Numbers 4-5
2 Boundary and Diagonals of a Square Matrix 6-9
3 Vowel words and shift of words 10-12
4 Find number whose sum of all its digits is equal to N 13-15
5 Rotate the matrix 90ᵒ clockwise and corner element sum 16-18
6 Find the number of vowels and consonants in each word 19-21
7 Number which is composite as well as a magic number. 22-23
8 Check if the given matrix is symmetric or not. 24-26
9 Deleting given word from the string 27-28
10 An ISBN ( International Standard Book Number) 30-31
11 Create a mirror image of the inputted matrix. 32-34
12 Display and the count of palindromic words in the sentence 35-38
13 A prime palindrome which is prime as well as a palindrome. 39-40
14 Arrange the sentence in alphabetical order of the words. 41-43
15 Find the maximum and minimum value in the matrix 44-45
16 Display a Natural number less than 1000 in words 46-47
17 Encryption of a string to maintain their secrecy 48-49
18 Check whether the date entered is valid or not. 50-51
19 Denomination of an input amount 52-54
20 Kaprekar numbers 55-57
21 Display the words in ascending order of their frequency. 58-61
22 Program on Inheritance 62-63
23 Prime using recursive technique 64-66
24 Program on Data Structure - STACK 67-69
25 Program on Data Structure – Simple Queue 70-71
Acknowledgement
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
1193 IS A CIRCULAR PRIME
Example 3
INPUT :N = 29
OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME
PROGRAM
import java.util.Scanner;
public class Example17 {
public static void main( String args[] ){
int num;
Scanner sc = new Scanner( System.in );
System.out.print("Input a number: ");
num = sc.nextInt();
int num_of_digits = 0, divisor_part=1, circular_num = num;
boolean allPrime = true;
for( int i = num; i > 0; i /= 10 ){
num_of_digits++;
divisor_part *=10;
}
divisor_part /=10;
do{
circular_num = circulate_func( circular_num, divisor_part );
5
ALGORITHM
STEP1: Check whether a number is a circular prime no.
STEP 2: Enter a number
STEP 3: calculate the no. of digits
STEP4: chop the digits and check whether they are prime
STEP5: shift thedigits
STEP6: chop the digits again and check whether they are prime numbers
STEP7: if original and modified and shifted numbers are prime, the number is circular prime number
STEP8: end
OUTPUT
INPUT :N = 29
OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME
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.
6
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
PROGRAM
import java.util.Scanner;
public class MatrixSort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("ENTER MATRIX SIZE (M): ");
int m = in.nextInt();
if (m <= 3 || m >= 10) {
System.out.println("THE MATRIX SIZE IS OUT OF RANGE.");
return;
}
int a[][] = new int[m][m];
System.out.println("ENTER ELEMENTS OF MATRIX");
for (int i = 0; i < m; i++) {
System.out.println("ENTER ROW " + (i+1) + ":");
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
/*
* Only positive integers
* should be enetered
*/
if (a[i][j] < 0) {
System.out.println("INVALID INPUT");
return;
}
}
}
System.out.println("ORIGINAL MATRIX");
printMatrix(a, m);
sortNonBoundaryMatrix(a, m);
System.out.println("REARRANGED MATRIX");
7
printMatrix(a, m);
computePrintDiagonalSum(a, m);
}
public static void sortNonBoundaryMatrix(int a[][], int m) {
/*
* To sort non-boundary elements of Matrix
* copy the non-boundary elements in a
* single dimensional array. Sort the
* single dimensional array and assign the
* sorted elements back in the 2D array at
* their respective positions
*/
int b[] = new int[(m - 2) * (m - 2)];
int k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
b[k++] = a[i][j];
}
}
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];
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++];
}
}
}
public static void computePrintDiagonalSum(int a[][], int m) {
int sum = 0;
System.out.println("DIAGONAL ELEMENTS");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (i == j || i + j == m - 1) {
sum += a[i][j];
System.out.print(a[i][j] + "\t");
}
else {
System.out.print("\t");
}
}
System.out.println();
}
System.out.println("SUM OF THE DIAGONAL ELEMENTS = " + sum);
}
public static void printMatrix(int a[][], int m) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(a[i][j] + "\t");
}
8
System.out.println();
}
}
}
ALGORITHM
STEP1: declare a square matrix A[][] of order (M x M) where ‘M’ must be greater than 3
and less than 10
STEP2: Sort the non-boundary elements in ascending order using any standard sorting technique and
rearrange them in the matrix
STEP3: Calculate the sum of both the diagonals
STEP4: Display the original matrix, rearranged matrix and only the diagonal elements of the rearranged matrix.
STEP5: end
OUTPUT
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
9
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
Example 2
PROGRAM
import java.util.Scanner;
public class VowelCheck
{
public static boolean WordCheck(String w)
{int len1 = w.length();
char first = w.charAt(0);
char last = w.charAt(len1 - 1);
if(isVowel(w.charAt(0))==true && isVowel(w.charAt(len1-1))==true)
{
return true;
}
10
else
{
return false;
}
}
public static boolean isVowel(char ch)
{
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
int count=0,i=0,len=0;
char last=' ',ch=' ';
String sen="",wd="",vowels="",nonVowels="";
Scanner sc=new Scanner(System.in);
System.out.print("Sentence: ");
sen = sc.nextLine();
sen = sen.trim();
sen = sen.toUpperCase();
len = sen.length();
last = sen.charAt(len - 1);
if(last != '.' && last != '?' && last != '!')
{
System.out.println("INVALID INPUT");
return;
}
for(i = 0; i < len; i++)
{
ch = sen.charAt(i);
if(ch==' '||ch=='.'||ch=='?'||ch==','||ch=='!')
{
if(wd.length() > 0 && WordCheck(wd)==true)
{
count++;
vowels += wd + " ";
}
else
{
nonVowels+= wd + " ";
}
wd = "";
}
else
{
wd += ch;
}
}
11
ALGORITHM
STEP1: a sentence which may be terminated by either '.', '?' or '!' only
STEP2: words may be separated by more than one blank space and are in UPPER CASE
STEP3: Find the number of words beginning and ending with a vowel
STEP4: Place the words which begin and end with a vowel at the beginning, followed by the remaining
words as they occur in the sentence
STEP5: print the sentences
STEP6: end
OUTPUT
INPUT: HOW ARE YOU@
OUTPUT: INVALID INPUT
12
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
PROGRAM
import java.util.Scanner;
System.out.print("Enter m: ");
int m = in.nextInt();
13
System.out.print("Enter n: ");
int n = in.nextInt();
if (sum == n) {
number = i;
break;
}
}
if (number == -1) {
System.out.println("Required number not found");
}
else {
System.out.println("The required number = " + number);
System.out.println("Total number of digits = " + count);
}
}
}
ALGORITHM
STEP1: enter two positive numbers M and N, such that M is between 100 and 10000 and N is less than
100
STEP2: check for the validity of the inputs
STEP3: display an appropriate message for an invalid input
STEP4: Find the smallest integer that is greater than M and whose digits add up to n
STEP5: Find the total number of digits present in the required number.
STEP6: Print the result
STEP7: end
OUTPUT
INPUT :
M = 99
N = 11
OUTPUT :
INVALID INPUT
14
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 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
15
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
PROJECT
import java.util.*;
class Rotate90
{
public static void main(String arr[])
{
int matrix[][]=new int[10][10];
int m,a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Value of M : ");
m=sc.nextInt();
System.out.println("Enter "+(m*m)+" Elements for Matrix : ");
for(a=0;a<m;a++)
{
for(b=0;b<m;b++)
{
matrix[a][b]=sc.nextInt();
}
}
System.out.println("Original Matrix :");
16
for(a=0;a<m;a++)
{
for(b=0;b<m;b++)
{
System.out.print(matrix[a][b]+" ");
}
System.out.println();
}
// Rotate a Matrix anti clock wise 90 degree
for (int x = 0; x < m / 2; x++)
{
ALGORITHM
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
18
Is 1 1
Great 2 3
Example 3
INPUT: All the best!
OUTPUT:
Invalid Input.
PROGRAM
import java.util.Scanner;
public class StringProgram
{
public static void main(String args[])
{
String sen="",wd="",upper="";
char ch=' ',last=' ';
int i=0,len=0,vowelsFrequency=0,consonantsFrequency=0;
Scanner sc=new Scanner(System.in);
System.out.print("String: ");
sen = sc.nextLine();
sen = sen.trim();
len = sen.length();
last = sen.charAt(len - 1);
if(last != '.' && last != '?')
{
System.out.println("Invalid input.");
}
else
{
System.out.println("Word\tVowels\tConsonants");
for(i = 0; i < len; i++)
{
ch = sen.charAt(i);
if(ch == ' ' || ch == '.' || ch == '?')
{
wd=Character.toUpperCase(wd.charAt(0))+wd.substring(1).toLowerCase();
System.out.println(wd+"\t"+vowelsFrequency+"\t"+consonantsFrequency);
wd = "";
vowelsFrequency=0;
consonantsFrequency=0;
}
else
{
wd += ch;
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
{
vowelsFrequency++;
}
else
{
consonantsFrequency++;
}
}
}
}
19
}
}
ALGORITHM
STEP1:accept a sentence which may be terminated by either ‘.’ Or ‘?’ only.
STEP2:The words are to be separated by a single blank space.
STEP3:Print an error message if the input does not terminate with ‘.’ Or ‘?’
STEP4: assume that no word in the sentence exceeds 15 characters, so that you get a proper formatted
output.
STEP5:Convert the first letter of each word to uppercase.
STEP6:Find the number of vowels and consonants in each word and display them with proper headings
along with the words.
STEP7: end
OUTPUT
INPUT: All the best!
OUTPUT:
Invalid Input
20
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
PROGRAM
import java.util.Scanner;
public class KboatCompositeMagicNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
System.out.println("Invalid input");
return;
}
System.out.println("The composite magic numbers are:");
int count = 0;
for (int i = m; i <= n; i++) {
boolean isComposite = false;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isComposite = true;
break;
}
}
if (isComposite && i != 1) {
int num = i;
while (num > 9) {
int sum = 0;
while (num != 0) {
int d = num % 10;
num /= 10;
sum += d;
}
num = sum;
}
if (num == 1) {
count++;
System.out.print(i + " ");
}
}
}
System.out.println();
System.out.println("Frequency of composite magic numbers: " + count);
}
ALGORITHM
STEP1:Accept two positive integers m and n, where m is less than n as user input.
STEP2:check whether it is a composite number
STEP3:check whether it is a magic number
STEP4:Display the number of composite magic integers that are in the range between m and n (both
inclusive) STEP5: Display output along with frequency, in the specified format
STEP6:end
OUTPUT
INPUT:
m = 120
n = 99
OUTPUT:
INVALID INPUT
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 user. Display an appropriate message for invalid input.
22
PROGRAM
import java.util.Scanner;
class Q2_2014
{
int m,a[][],rd,ld,z,k,x,t;
public void inp()
{
int i,j;
Scanner Sc = new Scanner(System.in);
System.out.print("M=");
m=Sc.nextInt();
if(m>2 && m<10)
{
a=new int[m][m];
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
a[i][j]=Sc.nextInt();
23
}
}
display();
chk();
}
else
{
System.out.println("Matrix Size is out of range");
}
}
public void display()
{
int i,j;
System.out.println("\nOriginal Matrix");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public void chk()
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j] == a[j][i])
{
z = z+1;
}
}
}
if(z ==(m*m))
{
System.out.println("The Given Matrix is symmetric");
}
else
{
System.out.println("The Given Matrix is not symmetric");
}
sum();
}
public void sum()
{
int i,j;
System.out.print("Sum of the left diagonal=");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if(i==j)
{
ld+=a[i][j];
24
}
}
}
System.out.println(ld);
System.out.print("Sum of the Right diagonal=");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if((i+j)==m-1)
{
rd+=a[i][j];
}
}
}
System.out.print(rd);
}
}
class SymMatrix
{
public static void main(String args[])
{
Q2_2014 ob =new Q2_2014();
ob.inp();
}
}
ALGORITHM
STEP1: declare a square matrix A[][] of order MXM
STEP2:M is an positive integer and represents row and column. M should be greater
than 2 and less than 10.
STEP3:Accept the value of M from user.
STEP4:Display an appropriate message for invalid input.
STEP5:Display the original matrix
STEP6:Check if the given matrix is symmetric or not. If the element of the ith row and jth
column is same as element of the jth row and ith column.
STEP7:Find the sum of the left and right diagonal of the matrix and display them
OUTPUT
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
25
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
PROGRAM
import java.util.Scanner;
public class DeleteWordFromPosition
{
26
ALGORITHM
STEP1:Convert the string into a string array.
STEP2:Iterate the array and check the word not equal to the given word.
STEP3:Concatenate the word into a new string array name as a new string.
STEP4:Print the new string.
OUTPUT
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.
27
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 inout, 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
PROGRAM
import java.util.Scanner;
public class KboatISBNCheck
{
public static void main(String args[]) {
28
ALGORITHM
STEP1: accept a ten digit code from the user.
STEP2:For an invalid INPUT display an appropriate message.
STEP3:Verify the code for its validity in the format specified
OUTPUT
INPUT CODE: 0201530821
OUTPUT : SUM = 99
LEAVES NO REMAINDER – VALID ISBN CODE
29
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
PROGRAM
import java.util.Scanner;
public class MirrorMatrix
{
public static void main(String args[])
{
int i=0,j=0,m=0,row=0,col=0;
int arr[][],mirror[][];
Scanner sc=new Scanner(System.in);
System.out.print("M = ");
m = sc.nextInt();
if(m < 2 || m > 20)
{
System.out.println("SIZE OUT OF RANGE");
}
else
{
arr = new int[m][m];
System.out.println("Enter matrix elements:");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
arr[i][j] = sc.nextInt();
30
}
}
System.out.println("ORIGINAL MATRIX");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
mirror= new int[m][m];
row = 0;
col = m - 1;
for(i = 0; i < m; i++)
{
row = 0;
for(j = 0; j < m; j++)
{
mirror[row][col] = arr[i][j];
col--;
}
row++;
}
System.out.println("MIRROR MATRIX");
for(i = 0; i < m; i++)
{
for(j = 0; j < m; j++)
{
System.out.print(mirror[i][j] + "\t");
}
System.out.println();
}
}
}
}
ALGORITHM
STEP1: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.
STEP2:Allow the user to input integers into this matrix.
STEP3:Display appropriate error message for an invalid input.
STEP4:Display the input matrix.
STEP5:Create a mirror image of the inputted matrix.
STEP6:Display the mirror image matrix
OUTPUT
INPUT : M = 3
4 16 12
8 2 14
4 1 3
OUTPUT :
ORIGINAL MATRIX
31
4 16 12
8 2 14
4 1 3
MIRROR IMAGE MATRIX
12 16 4
14 2 8
3 1 6
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.
32
PROGRAM
import java.util.Scanner;
public class palindromeWordsInSentence
{
public static void main(String[] args)
{
String sen="",wd="",wd1="",palindromeWords="";
char ch=' ',ch1=' ';
int i=0,len=0,count=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
sen = sc.nextLine();
sen=sen+" ";
sen=sen.toLowerCase();
len=sen.length();
for(i=0;i< len;i++)
{
ch=sen.charAt(i);
if(ch==' ')
{
if(wd.equals(wd1)==true)
{
palindromeWords+=wd1+" ";
count++;
}
wd1="";
wd="";
}
else
{
wd=wd+ch;
wd1=ch+wd1;
}
}
if(count>0)
{
System.out.println("Palindrome words in sentence:");
System.out.println(palindromeWords);
ALGORITHM
STEP1: Accept a sentence in UPPER CASE which is terminated by either ".", "?", or "!".
STEP2:Each word of the sentence is separated by a single blank space.
STEP3:Display the count of palindromic words in the sentence.
STEP4:Display the palindromic words in the sentence.
OUTPUT
INPUT : NITIN ARORA USES LIRIL SOAP.
OUTPUT : NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS : 3
34
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
PROGRAM
import java.util.Scanner;
public class PrimePalindromeNumber
{
public static boolean isPrime(int n)
{
int c = 0,i=0;
for(i = 1; i <= n; i++)
{
if(n % i == 0)
{
c++;
}
}
if(c > 2)
{
return false;
}
else
{
return true;
}
}
public static boolean isPalindrome(int n)
{
int rev = 0,temp=0;
temp=n;
while(temp>0)
{
rev = rev * 10 + temp % 10;
35
temp=temp/10;
}
if(rev==n)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
int i=0,m=0,n=0,count=0;
Scanner sc=new Scanner(System.in);
System.out.print("m = ");
m =sc.nextInt();
System.out.print("n = ");
n = sc.nextInt();
if(m > 3000 || n > 3000 || m > n)
{
System.out.println("OUT OF RANGE.");
return;
}
System.out.println("THE PRIME PALINDROME INTEGERS ARE:");
for(i = m; i <= n; i++)
{
if(isPalindrome(i) && isPrime(i))
{
if(count == 0)
System.out.print(i);
else
{
System.out.print(", " + i);
}
count++;
}
}
System.out.println();
System.out.println("FREQUENCY OF PRIME PALINDROME INTEGERS: " + count);
}
}
AGORITHM
OUTPUT
36
INPUT:
m = 100
n = 5000
OUTPUT: OUT OF RANGE
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.
37
OUTPUT:
Length: 4
Rearranged Sentence: BE GOOD OTHERS TO
PROGRAM
import java.util.Scanner;
import java.util.StringTokenizer;
public class ArrangeAlphabetically
{
public static void main(String args[])
{
int i=0,j=0,count=0,len=0;
String sen="",temp="",newsen="";
String wd[];
char last=' ';
ALGORITHM
38
OUTPUT
INPUT: BE GOOD TO OTHERS.
OUTPUT:
Length: 4
Rearranged Sentence: BE GOOD OTHERS TO
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
39
3 3 4 5
6 7 8
PROGRAM
import java.util.Scanner;
public class ArraySort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF M: ");
int m = in.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (m <= 2
|| m >= 10
|| n <= 2
|| n >= 10) {
System.out.println("MATRIX SIZE OUT OF RANGE.");
return;
}
int a[][] = new int[m][n];
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++) {
System.out.println("ENTER ELEMENTS OF ROW " + (i+1) + ":");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - 1; j++) {
for (int k = 0; k < n - j - 1; k++) {
if (a[i][k] > a[i][k + 1]) {
int t = a[i][k];
a[i][k] = a[i][k+1];
a[i][k+1] = t;
}
}
}
}
System.out.println("MATRIX AFTER SORTING ROWS");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
ALGORITHM
40
STEP1: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. STEP2:Allow the user to input integers into this matrix.
STEP3:Display the input matrix
STEP4:Find the maximum and minimum value in the matrix and display them along with
their position.
STEP5:Sort the elements of the matrix in ascending order using any standard sorting technique
and rearrange them in the matrix.
OUTPUT
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
41
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
PROGRAM
import java.io.*;
import java.lang;
public class num
{
//Declaring Instance variables
int n;
//Method to take input
void inputNumber() throws IOException
{
BufferedReader inp=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nINPUT:\t");
n=Integer.parseInt(inp.readLine());
}
//Method to Extract digits , call other methods and display output
public void extract()
{
String str=",str1=",str2=";
int hund=0,tens=0,units=0,i=0;
if(n<1 || n>999)
System.out.println(\nOUT OF RANGE “);
else
{
while(n!=0)
{
if(i==0)
units=n%10;
else if(i==1)
tens=n%10;
else if(i==2)
hund=n%10;
i++;
n=n/10;
}
if(hund>0)
str=word1(hund)+ " HUNDRED ";
42
if(tens>1)
str1= word2(tens);
if(tens==1)
str2= word3(units);
else
str2=word1(units);
if((!str.equals("))&&(!str1.equals(") || !str2.equals()))
str=str+ "AND ";
if(!str1.equals(""))
str=str+ str1+ "";
if(!str2.equals(""))
str=str+ str2;
System.out.println("OUTPUT:\t"+str);
}//EndElse
}
//Method to convert digits 0-9
String word1(int x)
{
String s="";
switch(x)
{
case 1:
s="ONE";
break;
case 2:
s="TWO";
break;
case 3:
s="THREE";
break;
case 4:
s="FOUR";
break;
case 5:
s="FIVE";
break;
case 6:
s="SIX";
break;
case 7:
s="SEVEN";
break;
case 8:
s="EIGHT";
break;
case 9:
s="NINE";
break;
}
return s;
}
//Method to convert numbers 20, 30,40,…..90
String word2(int x)
{
String s=";
switch(x)
{
43
case 2:
s="TWENTY";
break;
case 3:
s="THIRTY";
break;
case 4:
s="FOURTY";
break;
case 5:
s="FIFTY";
break;
case 6:
s="SIXTY";
break;
case 7:
s="SEVENTY";
break;
case 8:
s="EIGHTY";
break;
case 9:
s="NINETY";
break;
}
return s;
}
//Method to convert numbers 10 – 19
String word3(int x)
{
String s="";
switch(x)
{
case 0:
s="TEN";
break;
case 1:
s="ELEVEN";
break;
case 2:
s="TWELVE";
break;
case 3:
s="THIRTEEN";
break;
case 4:
s="FOURTEEN";
break;
case 5:
s="FIFTEEN";
break;
case 6:
s="SIXTEEN";
break;
case 7:
s="SEVENTEEN";
break;
44
case 8:
s="EIGHTEN";
break;
case 9:
s="NINETEEN";
break;
}
return s;
}
// Main method to call other methods
public static void main(String args[]) throws IOException
{
num obj=new num();
obj.inputNumber();
obj.extract();
}
}
ALGORITHM
STEP1:input a natural number less than 1000
STEP2:display it in words.
OUTPUT
Input: 29
Output: TWENTY NINE
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.
45
IT IS COOL.
OUTPUT:
KV KU ENQWFA.
RAIN MAY IT.
VJG YGCVJGT KU HKPG.
COOL IS IT.
PROGRAM
import java.util.*;
class sentence
{
String str[],s;
int i,n;
String input()
{
Scanner sc=new Scanner (System.in);
return sc.nextLine();
}
void takeString()
{
Scanner sc=new Scanner (System.in);
System.out.println("How many sentences:");
n=sc.nextInt();
if(n<1||n>9)
{
System.out.println("INVALID ENTRY:");
return;
}
str=new String[n];
for(i=0;i<n;i++)
{
System.out.println("Enter sentence (ends with full stop):");
s=input();
if(s.charAt(s.length()-1)!='.')
{
System.out.println("Full stop at the end is mandatory:");
i--;
continue;
}
str[i]=s;
}
for(i=0;i< n;i++)
{
s=str[i];
if(i%2==0)
encrypt(s);
else
reverse(s);
}
}
void encrypt(String s)
{
int i,len;
char ch;
String st="";
len=s.length();
for(i=0;i< len;i++)
46
{
ch=s.charAt(i);
if((ch>=65 && ch<=90)||(ch>=97 && ch<=122))
{
ch=(char)(ch+2);
if(ch >90 && ch< 97)
{
ch=(char)((64+ch-90));
}
else if(ch >122)
{
ch=(char)((96+ch-122));
}
}
st=st+ch;
}
System.out.println(st);
}
void reverse(String s)
{
int i;
String s1;
s=s.trim();
s=s.substring(0,s.length()-1);
while(true)
{
i=s.lastIndexOf(" ");
if(i<0)
break;
s1=s.substring(i).trim();
System.out.print(s1+ " ");
s=s.substring(0,i).trim();
}
System.out.println(s+".");
}
public static void main(String args[])
{
sentence ob=new sentence();
ob.takeString();
}
}
ALGORITHM
STEP1: enter 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.
STEP2:accept the size of the array.
STEP3:Display an appropriate message if the size is not satisfying the given condition.
STEP4:Define a string array of the inputted size and fill it with sentences row-wise.
STEP5:Change the sentence of the odd rows with an encryption of two characters ahead
of the original character.
STEP6: change the sentence of the even rows by storing the sentence in reverse order.
STEP7:Display the encrypted sentences as per the sample data given below.
OUTPUT
47
INPUT: n = 4
IT IS CLOUDY.
IT MAY RAIN.
THE WEATHER IS FINE.
IT IS COOL
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
PROGRAM
import java.util.*;
public class Date
{
public static void main(String[] args)
{
int day_num;
int yr;
int N;
Scanner in = new Scanner(System.in);
DaysCalculation date = new DaysCalculation();
48
do
{
System.out.println("Enter a day number (between 1 and 366)");
day_num = in.nextInt();
if(day_num < 1 || day_num > 366)
System.out.println("INVALID DAY NUMBER:");
}
while(day_num < 1 || day_num > 366);
do
{
System.out.println("Enter the year");
yr = in.nextInt();
if(Integer.toString(yr).length()!=4)
System.out.println("INVALID YEAR:");
}
while(Integer.toString(yr).length()!=4);
do
{
System.out.println("Enter the value of N:");
N = in.nextInt();
if(N < 1 || N > 100)
System.out.println("INVALID DAY NUMBER (between 1 and 100):");
}
while(N < 1 || N > 100);
date.setDate(day_num,yr,N);
System.out.println("OUTPUT:");
date.dateSpecifier();
in.close();
}
}
class DaysCalculation
{
public void setDate(int dayNumber, int year, int dayAfter)
{
this.dayNumber = dayNumber;
this.year = year;
this.dayAfter = dayAfter;
}
public void dateSpecifier()
{
int m = 0,k=1;
for(int i = 1; i <= dayNumber; i++)
{
if( checkLeap(year) == true ? k > ldays[m] : k > mdays[m] )
{
k = 1;
m++;
}
k++;
}
String prefix;
prefix = (k-1)%10 == 1 ? "st" : (k-1)%10 == 2 ? "nd" : (k-1)%10 == 3 ? "rd" : "th";
System.out.println("DATE: "+(k-1)+prefix+" "+months[m]+" ,"+year);
for (int i = 1; i <= dayAfter; i++)
{
if( checkLeap(year) == true ? k > ldays[m] : k > mdays[m] )
{
49
k = 1;
m++;
if(m > 11)
{
year++;
m = 0;
}
}
k++;
}
prefix = (k-1)%10 == 1 ? "st" : (k-1)%10 == 2 ? "nd" : (k-1)%10 == 3 ? "rd" : "th";
System.out.println("DATE AFTER "+dayAfter+" DAYS:"+(k-1)+""+prefix+" "+months[m]+" ,"+year);
}
private boolean checkLeap(int year)
{
if(year%400==0)
leap=true;
else if (year%100==0)
leap=false;
else if (year%4==0)
leap=true;
else
leap=false;
return leap;
}
private boolean flag;
private static boolean leap;
private int dayNumber,year;
private int dayAfter;
String[] months =
{"January","Feburary","March","April","May","June","July","August","Sepetember","October","November","Dece
mber"};
int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
int[] ldays={31,29,31,30,31,30,31,31,30,31,30,31};
}
ALGORITHM
STEP1:accept your date of birth in dd mm yyyy format.
STEP2: Check whether the date entered is valid or not.
STEP3:If it is valid, display "VALID DATE", also compute
STEP4:display the day number of the year for the date of birth.
STEP5:If it is invalid, display "INVALID DATE"
STEP6:terminate the program.
OUTPUT
INPUT: Enter your date of birth in dd mm yyyy format
03
04
2010
OUTPUT: VALID DATE
93
Question 19
50
PROGRAM
import java.io.*;
public class Bank
{
public static void main(String args[]) throws IOException
{
int rev = 0, amount, temp, rem;
int denomination[] = {1000, 500, 100, 50, 20, 10, 5, 2, 1};
String denomiation1[] = {" Zero"," One", " Two", " Three", " Four", " Five", " Six",
" Seven", " Eight", " Nine"};
int i, totalNotes = 0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Amount:");
amount=Integer.parseInt(br.readLine());
// Checking for the entered amount not more then 100000
if(amount >99999)
{
System.out.println("Invalid Amount…");
return;
}
temp = amount;
// Reverse the amount, example 3456 into 6543
// for displaying as THREE FOUR FIVE SIX
while(temp !=0)
{
rev=rev*10+temp%10;
temp=temp/10;
}
System.out.print("Amount in words :");
// Display the note in words
while(rev!=0)
{
rem=rev%10; // Mod division for reminder
51
for(i=0;i<10;i++)
{
if(rem==i)
System.out.print(denomiation1[i]);
}
ALGORITHM
STEP1:design a program to display the denomination of an input amount, upto 5 digits.
STEP2:The available denomination with the bank are of rupees
1000,500,100,50,20,10,5,2 and 1.
STEP3:Design a program to accept the amount from the user
STEP4: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.
STEP5:print the amount in words according to the digits
OUTPUT
INPUT: 14836
OUTPUT: ONE FOUR EIGHT THREE SIX
DENOMINATION:
1000 X 14 =14000
500 X 1 =500
100 X 3 =300
50 X 1 =50
5 X 1 =5
1 X 1 =1
52
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 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
53
PROGRAM
import java.util.Scanner;
import java.lang.Math;
public class Kaprekar
{
public static void main()
{
int p, q, h;
Scanner S = new Scanner(System.in);
System.out.println(“Enter p and q.”);
p = S.nextInt();
q = S.nextInt();
int count;
int flag = 0;
System.out.println(“Kaprekar numbers are: “);
h = p;
while(h < q)
{
int y = h;
count = 0;
while(y != 0)
{
++count;
y = (int)y/10;
}
int m, n, w;
w = h*h;
n = (int)(w%Math.pow(10,count));
m = (int)(w/Math.pow(10,count));
if((n + m) == h)
{
System.out.println(h);
++flag;
}
++h;
}
System.out.println(“Frequency: ” + flag);
}
}
ALGORITHM
STEP1: Enter the two positive integers p and q,
where p < q.
STEP2:determine how many kaprekar numbers are there in the range between 'p' and
'q'(both inclusive) and output them.
STEP3: Check whether the number isa kaprikar number
STEP4:print the number
OUTPUT
INPUT:
p=1
q=1000
OUTPUT:
THE KAPREKAR NUMBERS ARE:
1,9,45,55,99,297,999
FREQUENCY OF KAPREKAR NUMBERS IS:8
54
Question 21
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.
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
55
PROGRAM 1
EASY 1
YES 1
IT 1
THIS 2
IS 3
PROGRAM
import java.util.*;
public class KboatPara
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number of sentences.");
int n = in.nextInt();
in.nextLine();
if (n < 1 || n > 3) {
System.out.println("Invalid Entry");
return;
}
System.out.println("Enter sentences.");
String ipStr = in.nextLine();
ipStr = ipStr.toUpperCase();
StringTokenizer st = new StringTokenizer(ipStr, " .?");
int wordCount = st.countTokens();
System.out.println();
System.out.println("Total number of words: " + wordCount);
String wordArr[] = new String[wordCount];
int wordFreq[] = new int[wordCount];
int idx = 0;
for (int i = 0; i < wordCount; i++) {
String word = st.nextToken();
int j = 0;
for (j = 0; j < idx; j++) {
if (wordArr[j].equals(word)) {
wordFreq[j]++;
break;
}
}
if (j == idx) {
wordArr[idx] = word;
wordFreq[idx]++;
idx++;
}
}
//Sort Word Frequency in ascending order
for (int i = 0; i < idx - 1; i++) {
for (int j = 0; j < idx - i - 1; j++) {
if (wordFreq[j] > wordFreq[j + 1]) {
int t = wordFreq[j];
wordFreq[j] = wordFreq[j+1];
wordFreq[j+1] = t;
}
}
//Display the words and frequencies
System.out.println("Word\tFrequency");
for (int i = 0; i < idx; i++) {
System.out.println(wordArr[i] + "\t" + wordFreq[i]);
}
}
}
ALGORITHM
STEP1:Input a paragraph containing 'n' number of sentences where (1<=n<=4).
STEP2:The words are to be separated with single blank space and are in upper case
STEP3: A sentence may be terminated either with a full stop (.) or question mark (?).
STEP4:Enter the number of sentences, if it exceeds the limit show a message.
STEP5:Find the number of words in the paragraph
STEP6:Display the words in ascending order with frequency.
OUTPUT
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
57
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
PROGRAM
import java.util.Scanner;
class Employee
{
int empno;String empname,empdesig;
Employee()
{
empno=0;
empname=null;
empdesig=null;
58
}
Employee(int a,String b,String c)
{
empno=a;
empname=b;
empdesig=c;
}
void display()
{
System.out.println("Employee name:"+empname);
System.out.println("Employee number:"+empno);
System.out.println("Employee designation:"+empdesig);
}
}
class Salary extends Employee
{
float basic;
Salary(float b,int n,String name,String d)
{
super(n,name,d);
basic=b;
}
void calculate()
{
double da=0.1*basic,hra=0.15*basic,gross=basic+da+hra,pf=0.08*gross,netpay=gross-
pf;
System.out.println("\nEmployee Details");
System.out.println("----------------");
super.display();
System.out.println("\nPayment Details");
System.out.println("----------------");
System.out.println("Basic="+basic+"\nDA="+da+"\nHRA="+hra+"\nGross
Pay="+gross+"\nNet Pay="+netpay);
}
public static void main(String arg[])
{
Scanner ob=new Scanner(System.in);
System.out.print("Enter employee name:");
String name=ob.nextLine ();
System.out.print("Enter employee number:");
int n=ob.nextInt();
System.out.print("Enter employee designation:");
String d=ob.next();
System.out.print("Enter basic pay:");
float b=ob.nextFloat ();
Salary call=new Salary(b,n,name,d);
call.calculate();
59
}
}
ALGORITHM
STEP1:Create a parent class Employee.
STEP2:Input the data members.
STEP3:Perform the member functions as directed in the program.
STEP4:Then similarly create a child class Salary and then use extends keyword and
write the parent class name
STEP5:Input the data members and perform the member functions as directed
OUTPUT
Enter employee name:abc
Enter employee number:12345
Enter employee designation:officer
Enter basic pay:50000
Employee Details
----------------
Employee name:abc
Employee number:12345
Employee designation:officer
Payment Details
----------------
Basic=50000.0
DA=5000.0
HRA=7500.0
Salary Pay=62500.0
Net Salary=57500.0
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) - returns true/false for prime using recursive technique
60
PROGRAM
import java.util.Scanner;
public class Prime
{
private int n;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
n = in.nextInt();
}
public void checkprime() {
boolean isPrime = true;
if (n == 0 || n == 1)
isPrime = false;
else {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println("Prime Number");
else
System.out.println("Not a Prime Number");
}
public static void main(String args[]) {
Prime obj = new Prime();
obj.input();obj.checkprime(); }}
ALGORITHM
STEP1: store the number
STEP2: define a constructor Prime to initialize n
STEP3: define a constructor check to to check if the no is prime or not by calling a
function isPrime(int)
STEP4: define a constructor isprime which returns true/false for prime using recursive
technique
OUTPUT
Enter a number
23
23 is a prime number
61
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()
PROGRAM
import java.util.*;
class stack
{
int arr[];
62
int size;
int top;
stack(int s)
{
arr=new int[50];
size=s;
top=-1;
}
void pushvalue(int v)
{
if(top<(size-1))
arr[++top]=v;
else
System.out.println("Stack is full");
}
int popvalue()
{
if(top==-1)
{System.out.println("UNDERFLOW");
return-999;}
else
return arr[top--];
}
void display()
{
if(top==-1)
System.out.println("Stack is Empty");
else
{
for(int i=top;i>=0;i--)
System.out.println(arr[i]);
}
}
}
ALGORITHM
STEP1: create a class stack
STEP2:input the data members
STEP3:member function stack
(int s) to input data members
STEP4:member function void pushvalues ( ) to insert the values in srack if empty
STEP5:member function popvalues( ) to delete the values from stack
STEP6: function void dispaly to display the stack
OUTPUT
enter size
50
enter 1 for popvalues and 2 for pushvalues
2
63
PROGRAM
import java.util.*;
class SQ
{
int arr[]=new int[100];
int size;
int front;int rear;
SQ(int s)
{
size=s;
front=rear=-1;
}
void addRear(int v)
{
if(rear<size-1)
{
arr[++rear]=v;
64
if(front==-1)front=0;
}
else
System.out.println("QUEUE IS FULL");
}
int deletefront()
{
if(front<=rear && front!=-1)
{ System.out.println("Value Deleted "+arr[front]);
return arr[front++];}
else
{System.out.println("Queue is empty...UNDERFLOW");
return -999;
}
}
void display()
{
if(front>rear)
{System.out.println("NO VALUES TO BE PRINTED");}
else
{
for(int i=front;i<=rear;i++)
{System.out.println(arr[i]);}
}
}
}
ALGORITHM
STEP1:initialize the size and front and rear by -1
STEP2: add value at rear if possible otherwise display “Queue full at the rear end…
OVERFLOW”
STEP3: delete value from front if possible otherwise display “Queue
empty…UNDERFLOW
STEP4: display elements of the queue
OUTPUT
ENTER A LIMIT: 3
VALUES:
7
8
9
8(If entered, QUEUE IS FULL)
After deleting all values if deleted one more value
Queue is empty….UNDERFLOW