You are on page 1of 90

Computer Project

Session: 2022-23

Name : Mohammad Yousuf Ansari

Class : XII B

Roll No. : 25

Internal Examiner : _________

External Examiner : _________


Acknowledgement
I would like to express my special thanks of gratitude to my teacher Akash Sir as well as our

Senior Principal Mrs. Jyoti Kashyap and Principal Shivani Singh who gave me the golden

opportunity to do this wonderful project on the topic (Java Programs), which also helped me

in doing a lot of Research and i came to know about so many new things I am really thankful

to them.

Secondly I would also like to thank my parents and friends who helped me a lot in finalizing

this project within the limited time frame.


Index
S.No. Program Page No.
1 Create a mirror image of the inputted matrix. 1–4

2 Display and the count of palindromic words in the sentence 5-7

3 A prime palindrome which is prime as well as a palindrome. 8-10

4 Arrange the sentence in alphabetical order of the words. 11-13

5 Find the maximum and minimum value in the matrix 14-17

6 Find the number of vowels and consonants in each word 18-20

7 Number which is composite as well as a magic number. 21-23

8 Check if the given matrix is symmetric or not. 24-28

9 Deleting given word from the string 29-31

10 An ISBN ( International Standard Book Number) 32-33

11 Circular Prime Numbers 34-36

12 Boundary and Diagonals of a Square Matrix 37-41

13 Vowel words and shift of words 42-44

14 Find number whose sum of all its digits is equal to N 45-47

15 Rotate the matrix 90ᵒ clockwise and corner element sum 48-51

16 Display the words in ascending order of their frequency. 52-54

17 Program on Inheritance 55-58

18 Prime using recursive technique 59-60

19 Program on Data Structure - STACK 61-63

20 Program on Data Structure – Simple Queue 64-66

21 Display a Natural number less than 1000 in words 67-72


22 Encryption of a string to maintain their secrecy 73-76

23 Check whether the date entered is valid or not. 77-81

24 Denomination of an input amount 82-84

25 Kaprekar numbers 85-86


Program 1
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:

Display the input matrix.

Create a mirror image of the inputted matrix.

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();

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

STEP 1 : 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.

STEP 2 : Allow the user to input integers into this matrix.

STEP 3 : Display appropriate error message for an invalid input.

STEP 4 : Display the input matrix.

STEP 5 : Create a mirror image of the inputted matrix.

STEP 6 : Display the mirror image matrix

OUTPUT
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
Program 2
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:

Display the count of palindromic words in the sentence.

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

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);

System.out.println("NUMBER OF PALINDROMIC WORDS:"+count);

else

System.out.println("NO PALINDROMIC WORDS FOUND");


}

ALGORITHM

STEP 1 : Accept a sentence in UPPER CASE which is terminated by either ".", "?", or "!".

STEP 2 : Each word of the sentence is separated by a single blank space.

STEP 3 : Display the count of palindromic words in the sentence.

STEP 4 : Display the palindromic words in the sentence.

OUTPUT

INPUT : NITIN ARORA USES LIRIL SOAP.

OUTPUT :

NITIN ARORA LIRIL

NUMBER OF PALINDROMIC WORDS : 3


Program 3
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

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;

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);

ALGORITHM

STEP 1 : Enter two positive integers m and n, where m < n

STEP 2 : Determine how many prime-palindrome integers are there in the range between m and n (both
inclusive) and output them.

STEP 3 : The input should contains two positive integers m and n where m < 3000 and n < 3000

STEP 4 : Display the number of prime palindrome integers in the specified range along with their values in the
format specified

OUTPUT

INPUT:
m = 100
n = 5000

OUTPUT: OUT OF RANGE
Program 4
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:

Obtain the length of the sentence (measured in words)

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

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=' ';

Scanner sc=new Scanner(System.in);

System.out.print("Sentence: ");
sen =sc.nextLine();

sen = sen.trim();

last = sen.charAt(sen.length() - 1);

if(last != '.' && last != '?' && last != '!')

System.out.println("INVALID SENTENCE!");

return;

sen = sen.toUpperCase();

StringTokenizer st = new StringTokenizer(sen, " .?!,");

len = st.countTokens();

System.out.println("LENGTH: " + len);

wd = new String[len];

for(i = 0; i < len; i++)

wd[i] = st.nextToken();

for(i = 0; i < len; i++)

for(j = 0; j < len - 1 - i; j++)

if(wd[ j].compareTo(wd[ j + 1]) > 0)

temp = wd[ j];

wd[ j] = wd[ j + 1];

wd[ j + 1] = temp;

for(i = 0; i < len; i++)

newsen += wd[i] + " ";


}

System.out.println("REARRANGED SENTENCE:" + newsen);

ALGORITHM

STEP 1 : Accept a sentence as input.

STEP 2 : The words in the string are to be separated by a blank.

STEP 3 : Each word must be in upper case. The sentence is terminated by either '.','!' or '?'.

STEP 4 : Obtain the length of the sentence (measured in words)

STEP 5 : Arrange the sentence in alphabetical order of the words

OUTPUT

INPUT: BE GOOD TO OTHERS.

OUTPUT:

Length: 4

Rearranged Sentence: BE GOOD OTHERS TO


Program 5
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:

Display the input matrix

Find the maximum and minimum value in the matrix and display them along with their position.

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 

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

STEP 1 : 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.

STEP 2 : Allow the user to input integers into this matrix.

STEP 3 : Display the input matrix

STEP 4 : Find the maximum and minimum value in the matrix and display them along with their position.

STEP 5 : 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 
Program 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:

Convert the first letter of each word to uppercase.

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 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++;

ALGORITHM

STEP 1 : Accept a sentence which may be terminated by either ‘.’ Or ‘?’ only.

STEP 2 : The words are to be separated by a single blank space.

STEP 3 : Print an error message if the input does not terminate with ‘.’ Or ‘?’

STEP 4 : Assume that no word in the sentence exceeds 15 characters, so that you get a proper formatted
output.

STEP 5 : Convert the first letter of each word to uppercase.

STEP 6 : Find the number of vowels and consonants in each word and display them with proper headings along
with the words.

STEP 7 : End

OUTPUT

INPUT: All the best!

OUTPUT:
Invalid Input
Program 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();

if (m < 1 || n < 1 || m > n) {

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

STEP 1 : Accept two positive integers m and n, where m is less than n as user input.

STEP 2 : Check whether it is a composite number

STEP 3 : Check whether it is a magic number

STEP 4 : Display the number of composite magic integers that are in the range between m and n (both inclusive)

STEP 5 : Display output along with frequency, in the specified format

STEP 6 : End

OUTPUT

INPUT:

m = 120
n = 99

OUTPUT:      

INVALID INPUT
Program 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.

Perform the following task:

Display the original matrix

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.

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

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();

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];

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

STEP 1 : Declare a square matrix A[][] of order MXM

STEP 2 : M is an positive integer and represents row and column. M should be greater than 2 and less than 10.

STEP 3 : Accept the value of M from user.

STEP 4 : Display an appropriate message for invalid input.

STEP 5 : Display the original matrix

STEP 6 : 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.

STEP 7 : 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
Program 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

public static void main(String args[])

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();

len = sen.length();

last = sen.charAt(len - 1);

if(last != '.' && last != '?' && last != '!')

System.out.println("INVALID INPUT.");

return;

sen = sen.toUpperCase();

System.out.print("WORD TO BE DELETED: ");

wd = sc.next();

wd = wd.toUpperCase();

System.out.print("WORD POSITION IN THE SENTENCE: ");

pos = sc.nextInt();

for(i=0;i< len;i++)

ch=sen.charAt(i);

if(ch==' '||ch=='.'||ch=='?'||ch=='!')

if(wd1.equals(wd)==true && (count)==pos)

/*do nothing*/

else

newsen=newsen+wd1+ch;

wd1="";

count++;

else

{
wd1=wd1+ch;

System.out.println("NEW SENTENCE:"+newsen);

ALGORITHM

STEP 1 : Convert the string into a string array.

STEP 2 : Iterate the array and check the word not equal to the given word.

STEP 3 : Concatenate the word into a new string array name as a new string.

STEP 4 : 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.


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

PROGRAM

import java.util.Scanner;

public class KboatISBNCheck

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the ISBN: ");

long isbn = in.nextLong();

int sum = 0, count = 0, m = 10;

while (isbn != 0) {

int d = (int)(isbn % 10);

count++;

sum += d * m;
m--;

isbn /= 10;

if (count != 10) {

System.out.println("Illegal ISBN");

else if (sum % 11 == 0) {

System.out.println("Legal ISBN");

else {

System.out.println("Illegal ISBN");

ALGORITHM

STEP 1 : Accept a ten digit code from the user.

STEP 2 : For an invalid INPUT display an appropriate message.

STEP 3 : Verify the code for its validity in the format specified

OUTPUT

INPUT CODE: 0201530821

OUTPUT : SUM = 99
LEAVES NO REMAINDER – VALID ISBN CODE
Program 11
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 Coprime {

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 );

if( !isPrime( circular_num ) ) allPrime=false;

}while( circular_num != num );

if( allPrime ) System.out.println("It is Circular Prime number." );

else System.out.println("It is not a Circular Prime number." );

public static boolean isPrime( int n ){

int factorCount = 0;

if( n < 2 ) return false;

else if( n == 2 ) return true;

else if( n % 2 == 0 ) return false;

else{

int num = (int) Math.sqrt( n );

for( int i = 3 ; i <= num; i+=2 ){

if( n %i == 0 ){

return false;

return true;

}
public static int circulate_func( int n, int divisor_part ){

if( n < 10 ) return n;

else return ( n % divisor_part ) * 10 + n / divisor_part;

ALGORITHM

STEP 1 : Check whether a number is a circular prime no.

STEP 2 : Enter a number

STEP 3 : Calculate the no. of digits

STEP 4 : Chop the digits and check whether they are prime

STEP 5 : Shift the digits

STEP 6 : Chop the digits again and check whether they are prime numbers

STEP 7 : If original and modified and shifted numbers are prime, the number is circular prime number

STEP 8 : End

OUTPUT

INPUT :

N = 29

OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME
Program 12
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:

Sort the non-boundary elements in ascending order using any standard sorting technique and rearrange
them in the matrix.

Calculate the sum of both the diagonals.

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    
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");
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");

System.out.println();

}
ALGORITHM

STEP 1 : Declare a square matrix A[][] of order (M x M) where ‘M’ must be greater than 3

and less than 10

STEP 2 : Sort the non-boundary elements in ascending order using any standard sorting technique and

rearrange them in the matrix

STEP 3 : Calculate the sum of both the diagonals

STEP 4 : Display the original matrix, rearranged matrix and only the diagonal elements of the rearranged matrix.

STEP 5 : 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  


Program 13
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:

Find the number of words beginning and ending with a vowel.

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

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;

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;

System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = " + count);

System.out.println(vowels + nonVowels);

ALGORITHM

STEP 1 : A sentence which may be terminated by either '.', '?' or '!' only

STEP 2 : Words may be separated by more than one blank space and are in UPPER CASE

STEP 3 : Find the number of words beginning and ending with a vowel

STEP 4 : Place the words which begin and end with a vowel at the beginning, followed by the remaining words
as they occur in the sentence

STEP 5 : Print the sentences

STEP 6 : End

OUTPUT

INPUT: HOW ARE YOU@

OUTPUT: INVALID INPUT


Program 14
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 4

INPUT :
M = 112
N = 130

OUTPUT :
INVALID INPUT

PROGRAM

import java.util.Scanner;

public class KboatNumber

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();

if (m < 100 || m > 10000 || n < 1 || n >= 100) {

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

return;

int number = -1, count = 0;

for (int i = m + 1; i < Integer.MAX_VALUE; i++) {

int sum = 0;

count = 0;

int t = i;

while (t != 0) {

int d = t % 10;

sum += d;

t /= 10;

count++;

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

STEP 1 : Enter two positive numbers M and N, such that M is between 100 and 10000 and N is less than 100

STEP 2 : Check for the validity of the inputs

STEP 3 : Display an appropriate message for an invalid input

STEP 4 : Find the smallest integer that is greater than M and whose digits add up to n

STEP 5 : Find the total number of digits present in the required number.

STEP 6 : Print the result

STEP 7 : End

OUTPUT

INPUT :
M = 99
N = 11

OUTPUT :
INVALID INPUT
Program 15
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:

Display the original matrix.

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

Find the sum of the elements of the four corners of the matrix.

Example 1

INPUT :

M = 3

OUTPUT :

ORIGINAL MATRIX

MATRIX AFTER ROTATION

Sum of the corner elements = 20

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 :");

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++)

for (int y = x; y < m - x - 1; y++)

int temp = matrix[x][y];

matrix[x][y] = matrix[y][m - 1 - x];


matrix[y][m - 1 - x]= matrix[m - 1 - x][m - 1 - y];

matrix[m - 1 - x][m - 1 - y] = matrix[m - 1 - y][x];

matrix[m - 1 - y][x] = temp;

System.out.println("Matrix After Rotate 90 Degree:");

for(a=0;a<m;a++)

for(b=0;b<m;b++)

System.out.print(matrix[a][b]+" ");

System.out.println();

ALGORITHM

STEP 1 : A square matrix A[][] of order M×M

STEP 2 : 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

STEP 3 : Accept the value M as user input

STEP 4 : Display an appropriate message for an invalid input

STEP 5 : Allow the user to input integers into the matrix

STEP 6 : Display the original matrix.

STEP 7 : Rotate the matrix 90ᵒ clockwise

STEP 8 : Find the sum of the elements of the four corners of the matrix.

STEP 9 : End

OUTPUT

INPUT :

M = 4
OUTPUT :

ORIGINAL MATRIX MATRIX AFTER ROTATION

Sum of the corner elements = 18


Program 16
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:

Enter the number of sentences, if it exceeds the limit show a message.

Find the number of words in the paragraph

Display the words in ascending order with frequency.

Example 1

INPUT: Enter number of sentences: 1

Enter sentences:

TO BE OR NOT

OUTPUT:

Total number of words: 6

WORD FREQUENCY

TO 1

BE 1

OR 1

NOT 1

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;
String temp = wordArr[ j];

wordArr[ j] = wordArr[ j+1];

wordArr[ j+1] = temp;

//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

STEP 1 : Input a paragraph containing 'n' number of sentences where (1<=n<=4).

STEP 2 : The words are to be separated with single blank space and are in upper case

STEP 3 : A sentence may be terminated either with a full stop (.) or question mark (?).

STEP 4 : Enter the number of sentences, if it exceeds the limit show a message.

STEP 5 : Find the number of words in the paragraph

STEP 6 : Display the words in ascending order with frequency.

OUTPUT

THIS IS A STRING PROGRAM. IS THIS EASY? YES.

OUTPUT:

Total number of words: 11

WORD FREQUENCY

THIS 2

A 1

STRING 1

PROGRAM 1

EASY 1

YES 1
Program 17
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

Class name – Salary

Data Members-:

⮚ basic -to store the basic pay

Member Functions-:

⮚ Salary( ) - default constructor

⮚ Salary(---) - parameterized constructor to initialize data members of both classes

⮚ void calculate( ) - calculates the net salary according to the following rules-:

DA=10% of basic

HRA=15% of basic

Salary=basic+DA+HRA

PF=8% of Salary

Net Salary= Salary-PF

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;

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();

ALGORITHM

STEP 1 : Create a parent class Employee.

STEP 2 : Input the data members.

STEP 3 : Perform the member functions as directed in the program.

STEP 4 : Then similarly create a child class Salary and then use extends keyword and write the parent class
name

STEP 5 : 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
Program 18
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

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

STEP 1 : Store the number

STEP 2 : Define a constructor Prime to initialize n

STEP 3 : Define a constructor check to to check if the no is prime or not by calling a function isPrime(int)

STEP 4 : Define a constructor is prime which returns true/false for prime using recursive technique

OUTPUT

Enter a number

23

23 is a prime number
Program 19
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[];

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

STEP 1 : Create a class stack

STEP 2 : Input the data members

STEP 3 : Member function stack (int s) to input data members

STEP 4 : Member function void pushvalues ( ) to insert the values in srack if empty

STEP 5 : Member function popvalues( ) to delete the values from stack

STEP 6 : Function void display to display the stack

OUTPUT

enter size

50
enter 1 for popvalues and 2 for pushvalues

enter the number of values to be filled 5

enter the value

enter the value

enter the value

22

enter the value

65

enter the value

78

The values in stack are:

78

65

22
Program 20
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

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;
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

STEP 1 : Initialize the size and front and rear by -1

STEP 2 : Add value at rear if possible otherwise display “Queue full at the rear end… OVERFLOW”

STEP 3 : Delete value from front if possible otherwise display “Queue empty…UNDERFLOW

STEP 4 : Display elements of the queue


OUTPUT

ENTER A LIMIT: 3

VALUES:

8(If entered, QUEUE IS FULL)

After deleting all values if deleted one more value

Queue is empty….UNDERFLOW
Program 21
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 ";

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)

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;

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

STEP 1 : Input a natural number less than 1000

STEP 2 : Display it in words.

OUTPUT

Input: 29

Output: TWENTY NINE


Program 22
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.

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++)

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

STEP 1 : 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.

STEP 2 : Accept the size of the array.

STEP 3 : Display an appropriate message if the size is not satisfying the given condition.

STEP 4 : 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.

STEP 6 : Change the sentence of the even rows by storing the sentence in reverse order.

STEP 7 : Display the encrypted sentences as per the sample data given below.

OUTPUT

INPUT: n = 4

IT IS CLOUDY.

IT MAY RAIN.

THE WEATHER IS FINE.

IT IS COOL
Program 23
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 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();

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] )

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","December"};

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

STEP 1 : Accept your date of birth in dd mm yyyy format.

STEP 2 : Check whether the date entered is valid or not.

STEP 3 : If it is valid, display "VALID DATE", also compute

STEP 4 : Display the day number of the year for the date of birth.

STEP 5 : If it is invalid, display "INVALID DATE"

STEP 6 : Terminate the program.


OUTPUT

INPUT: Enter your date of birth in dd mm yyyy format

03

04

2010

OUTPUT: VALID DATE

93
Program 24
A bank intends to design a program to display the denomination of an input amount, upto 5 digits. The
available denominations with the bank are of rupees 1000,500,100,50,20,10,5,2 and 1.

Design a program to accept the amount from the user and display the break-up in descending order of
denominations. (i.e. preference should be given to the highest denomination available) along with the total
number of notes. [Note: only the denomination used should be displayed]. Also print the amount in words
according to the digits.

Example 1

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

Example 2

INPUT: 235001

OUTPUT: INVALID AMOUNT

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 denomination1[] = {" 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

            for(i=0;i<10;i++)

            {

                if(rem==i)

                    System.out.print(denomiation1[i]);

            }

            rev=rev/10; // Ineger division

        }

        i = 0;

        // Display the denominators notes   

        System.out.print("\n\nDENOMINATION:\n");
        System.out.print("============:\n");

        while (amount!=0)

        {

            rev=amount/denomination[i];

            if(rev!=0)

            {

                System.out.println(denomination[i]+"\t X " + rev + "\t\t\t= " + rev*denomination[i]);

                totalNotes+=rev;

            }

            amount=amount % denomination[i];

            i++;

        }

        System.out.println("TOTAL NUMBER OF NOTES:  " + totalNotes);

    }

ALGORITHM

STEP 1 : Design a program to display the denomination of an input amount, upto 5 digits.

STEP 2 : The available denominations with the bank are of rupees 1000,500,100,50,20,10,5,2 and 1.

STEP 3 : Design a program to accept the amount from the user

STEP 4 : 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.

STEP 5 : 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

5X1 =5

1X1 =1
Program 25
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

PROGRAM

import java.util.Scanner;

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

STEP 1 : Enter the two positive integers p and q, where p < q.

STEP 2 : Determine how many kaprikar numbers are there in the range between 'p' and 'q'(both inclusive) and
output them.

STEP 3 : Check whether the number is a kaprikar number

STEP 4 :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

You might also like