Você está na página 1de 147

Page |1

Acknowledgement

I would like to express my special thanks of


gratitude to our principal, Mrs. Rosamma Mathew and my teacher Mrs.
Ani Sweety Babu who gave me the golden opportunity to do this
wonderful project.

Secondly, I would also like to thank my parents


and friends, who helped me a lot in finishing my project within limited
time. I cannot conclude without thanking God for keeping me healthy
and making me able to complete my project

Contents
Page |2

S.NO TOPIC PAGE


Page |3

1 Arrange 4

2 Wondrous 7

3 Anagrams 15

4 NumberCombinations 20

5 MergeArray 23

6 CopyProtection 29

7 FindDay 34

8 Reverse 38

9 UniqueDigitIntegers 42

10 Smith 45

11 VowelCount 49

12 SortArray 54

13 FindDate 60

14 Boundary 65

15 WordArrange 76

16 Denominations 79

17 Kaprekar 84

18 Frequency 87

19 NumberName 92

20 Encryption 95

21 BirthDate 99

22 PrimePalindrome 102
Page |4

23 AlphabeticalOrder 105

24 Matrix 108

25 ISBN 114

26 MirrorImage 118

27 Palindrome 122

28 CompositeMagic 125

29 SymmetricMatrix 129

30 Delete 135

31 LongestWord 138

32 VowelFrequency 141

33 ReversePalin 143

34 Initials 145

35 Common 147

Question 1
Write a program which takes a string (maximum 80 characters) terminated
by a full stop. The words in this string are assumed to be separated to be
separated by one or more blanks.
Page |5

Arrange the words of the input string in descending order of their lengths.
Same length words should be sorted alphabetically. Each word must start
with an uppercase letter and the sentence should be terminated by a full
stop.
Test your program for the following data and some random data.
SAMPLE DATA:
INPUT: “This is human resource department.”
OUTPUT: Department Resource Human This is.
INPUT: “To handle yourself use your head and to handle others use your
heart.”
OUTPUT:Yourself Handle Handle Others Heart Head Your Your And Use
Use To To.

ALGORITHM:
1) Accept a sentence.
2) Considering the first word as the longest word, compare its length
with other words.
3) Find the number of occurrence of the largest word and display it.
4) After displaying the largest word, replace it with space.

SOURCE CODE:
import java.util.*;
class Arrange
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence"); //Inputting the sentence
String s=sc.nextLine();
int count=0,c=0;
String s1,s2="",large="";
Page |6

System.out.println(“OUTPUT:”);
do
{
StringTokenizer st=new StringTokenizer(s," .");
count=st.countTokens();
while(st.hasMoreTokens())
{
s1=st.nextToken();
large=s1; //Consider first word as largest word
StringTokenizer str=new StringTokenizer(s," .");
while(str.hasMoreTokens())
{
s2=str.nextToken();
if(s2.length()>large.length()) //comparing the length of words with the first word
large=s2;
if(s2.length()==large.length())
{
if((int)s2.charAt(0)<(int)large.charAt(0))
large=s2;
}
}
}
StringTokenizer sr=new StringTokenizer(s," .");
while(sr.hasMoreTokens())
{
if(sr.nextToken().equalsIgnoreCase(large))
c++; //counting number of occurence of the largest word
}
for(int i=1;i<=c;i++)
{
Page |7

int l=large.length();
System.out.print(Character.toUpperCase(large.charAt(0))
+large.substring(1)+" ");
}
s=s.replace(large," "); //replacing the printed word with space
c=0;
}while(count!=0); //loop terminates
System.out.print(".");
}
}

Output:
(i) Enter a sentence:
This is Human Resource Department.
OUTPUT:
Department Resource Human This Is .

(ii) Enter a sentence:


To handle yourself use your head and to handle others use your
heart.
OUTPUT:
Yourself Heart Handle Handle Others Head Your Your And Use
Use To To.

Question 2
A wondrous square is an n by n grid which fulfils the following conditions.
(i) It contains integers from 1 to n2 where each integer appears only
once.
(ii) The sum of integers in any row or column must add up to 0.5 * n *
(n2 + 1).
Page |8

For example the following grid is a wondrous square where the sum of each
row or column is 65 where n = 5:
17 24 2 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
Write a program to read n (2<=n<=10) and the values stored in these n by n
cells and output if the grid represents a wondrous square or not.
Also output all the prime numbers in the grid along with their row index and
column index as shown in the output. A natural numbers is said to be prime if
it has exactly two divisors. E.g. 2, 3, 5, 7, 11 …
The first element of the grid i.e. 24 is stored at row index 0 and column
index 1.
Test your program for the following data and some random data.
SAMPLE DATA:
INPUT: N=4
16 15 1 2
6 4 10 14
9 8 12 5
3 7 11 13
OUTPUT:
YES IT REPRESENTS A WONDROUS SQUARE.
PRIME ROW INDEX COLUMN INDEX
2 0 3
3 3 0
5 2 3
7 3 1
11 3 2
13 3 3
Page |9

INPUT: N=3
1 2 4
3 7 5
8 9 6
OUTPUT:
NOT A WONDROUS SQUARE
PRIME ROW INDEX COLUMN INDEX
2 0 1
3 1 0
5 1 2
7 1 1

ALGORITHM:
1) Input the elements of the grid and print the original grid.
2) Convert the 2-D array to 1-D array to check for duplicate elements.
3) Find the sum of elements of each row and each column and count the
number of rows and columns which satisfy the condition.
4) If all the rows and column satisfy the condition print positive result
else negative result.
5) Find the elements which are prime by passing each element to the sub
function and print them.
SOURCE CODE:
import java.util.*;
class Wondrous
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Wondrous obj=new Wondrous();
System.out.println("Enter the dimension of the grid");
P a g e | 10

int n=sc.nextInt();
int i,j,c,sum=0,co=0,r=0,num;
int size=n*n;
int b[]=new int[size],a[][]=new int[n][n];
if(n>=2&&n<=10)
{
System.out.println("Enter the values"); //Inputting values of the grid
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Grid:"); //Printing the original grid
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
int k=0;
for(i=0;i<n;i++) //Converting 2-D array into 1-D to check for any duplicate elements
{
for(j=0;j<n;j++)
{
b[k]=a[i][j];
k++;
P a g e | 11

}
}
for(i=0;i<size;i++) //Checking whether any number occurs more than once
{
c=0;
for(j=0;j<size;j++)
{
if(b[i]==b[j])
c++;
}
if(c>1)
{
System.out.println("Element "+b[i]+" occurs "+c+" times");
break;
}
}
for(j=0;j<n;j++)
{
k=0;
sum=0;
for(i=0;i<n;i++)
{
sum+=a[k][i]; //Sum of 'k'th row
}
k++;
if(sum==0.5*n*((n*n)+1))
r++; //Counting the number of rows which satisfy the condition
k=0;
sum=0;
for(i=0;i<n;i++)
P a g e | 12

{
sum+=a[i][k]; //Sum of 'k'th column
}
k++;
if(sum==0.5*n*((n*n)+1))
co++; //Counting the number of columns which satisfy the condition
}
if(r==n&&co==n)
System.out.println("YES IT REPRESENTS A WONDROUS SQUARE");
else
System.out.println("NOT A WONDROUS SQUARE");
System.out.println("PRIME\tROW INDEX\tCOLUMN INDEX");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
num=a[i][j];
if(obj.isPrime(num)==true)
System.out.println(num+"\t "+i+"\t\t "+j);
}
}
}
}
public boolean isPrime(int num) //Function to find if an element is prime
{
int i,count=0;
for(i=1;i<=num;i++)
{
if(num%i==0)
count++;
P a g e | 13

}
if(count==2)
return true;
else
return false;
}
}

OUTPUT:
1) Enter the dimension of the grid
4
Enter the values
16
15
1
2
6
4
10
14
9
8
12
5
3
7
11
13
Grid:
16 15 1 2
P a g e | 14

6 4 10 14
9 8 12 5
3 7 11 13
YES IT REPRESENTS A WONDROUS SQUARE
PRIME ROW INDEX COLUMN INDEX
2 0 3
5 2 3
3 3 0
7 3 1
11 3 2
13 3 3

2) Enter the dimension of the grid


3
Enter the values
1
2
4
3
7
5
8
9
6
Grid:
1 2 4
3 7 5
8 9 6
NOT A WONDROUS SQUARE
PRIME ROW INDEX COLUMN INDEX
2 0 1
P a g e | 15

3 1 0
7 1 1
5 1 2
P a g e | 16

Question 3
We would like to generate all possible anagrams of a word. For example if
the given word is ‘TOP’, there will be six possible anagrams:

TOP
TPO
OPT
OTP
PTO
POT

An anagram must be printed only once. You may output the anagrams in any
order. Also output the total number of anagrams. You assume that the
number of letter, n, in the word will be 7 at most, i.e. n<=7

Test your program for the given data and some random data.

SAMPLE DATA:
INPUT: TO
OUTPUT: TO
OT
Total number of anagrams=2

INPUT: LEAN
OUTPUT: LEAN
LENA
LAEN
LANE
LNEA
LNAE
EALN
EANL
ELAN
ELNA
P a g e | 17

ENLA
ENAL
ALNE
ALEN
ANLE
ANEL
AENL
AELN
NLEA
NLAE
NELA
NEAL
NALE
NAEL
Total number of anagrams=24

ALGORITHM:
1) Accept a word.
2) Make the possible combinations by combining different letters of the
word using sub functions.
3) Print the anagrams and the number of anagrams.
P a g e | 18

SOURCE CODE:
import java.util.*;
class Anagrams
{
static int sum=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a word");
String str=sc.nextLine(); //Inputting the word
str=str.toUpperCase();
String w=str.substring(0,str.length());
System.out.println("Output:");
perm(w); //calling the recursion function
System.out.println("Total number of anagrams:"+sum);;
}
public static void perm(String s) //Indirect recursion
{
perm(" ",s); //calling the sub function
}
public static void perm(String prefix,String s)
{
int n=s.length();
if(n==0)
{
System.out.println(prefix);
sum++;
}
else
for(int i=0;i<n;i++)
P a g e | 19

perm((prefix+s.charAt(i)),(s.substring(0,i)+s.substring(i+1,n)));
}
}

Output:
1) Enter a word
TO
Output:
TO
OT
Total number of anagrams:2

2) Enter a word
SUMI
Output:
SUMI
SUIM
SMUI
SMIU
SIUM
SIMU
USMI
USIM
UMSI
UMIS
UISM
UIMS
MSUI
MSIU
MUSI
P a g e | 20

MUIS
MISU
MIUS
ISUM
ISMU
IUSM
IUMS
IMSU
IMUS
Total number of anagrams:24

3) Enter a word
TOP
Output:
TOP
TPO
OTP
OPT
PTO
POT
Total number of anagrams:6

Question 4
P a g e | 21

A positive natural number, (for example 27) can be represented as follows:


2+3+4+5+6+7
8+9+10
13+14
Where every row represents a combination of consecutive natural number,
which add up to 27.
Write a program which inputs a positive natural number N and prints the
possible consecutive number combinations, which when added give N.
Test your program for the following data and some random data.

SAMPLE DATA:
INPUT: N=9
OUTPUT: 4 5
2 3 4
INPUT: N=15
OUTPUT: 1 2 3 4 5
4 5 6
7 8
INPUT: N=21
OUTPUT: 1 2 3 4 5 6
6 7 8
10 11
Algorithm:
1) Input a number.
2) Two loops are used: The outer loop determines the value of the first
number ‘i’ of the sum and the inner loop finds the sum from ‘i’ to n for
each iteration of outer loop, till sum becomes equal or greater than n.
3) The consecutive numbers are stored in a 1-D array for each iteration
of the outer loop.
P a g e | 22

4) When the sum becomes equal to the number, n the consecutive


numbers are printed from the array and the loop terminates. Else the
next iteration takes place with an incremented value of ‘i’.

Source code:
import java.util.*;
class NumberCombinations
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt(); //Accepting the number
int i,j,sum=0,index=0;
int a[]=new int[n];
System.out.println(“Output:”);
for(i=1;i<n;i++)
{
index=0;
for(j=i;j<n;j++)
{
sum+=j; //Finding sum of consecutive numbers
a[index]=j; //The numbers are stored in an array
index++;
if(sum>=n)
break;
}
if(sum==n) //When the sum equals n, printing the array
{
P a g e | 23

for(j=0;j<index;j++)
System.out.print(a[j]+" ");
System.out.println();
}
sum=0; //Sum becomes 0 again for next iteration
}
}
}

Output:
1) Enter a number
9
Output:
234
4 5
2) Enter a number
15
Output:
12345
456
78
3) Enter a number
21
Output:
123456
678
10 11
Question 5
Write a program that inputs the names of people into different arrays, A
and B. Array A has N number of names, while array B has M number of
P a g e | 24

names, with no duplicates in either of them. Merge arrays A and B into a


single array C, such that the resulting array is sorted alphabetically.
Test your program for the given data and random data.
SAMPLE INPUT:
INPUT:
Enter number of names in Array A, N=2
Enter number of names in Array B, M=3
First array: (A)
Suman
Anil
Second array: (B)
Usha
Sachin
John
OUTPUT:

Sorted merged array: (C)


Anil
John
Sachin
Suman
Usha
Sorted first array: (A)
Anil
Suman
Sorted second array: (B)
John
Sachin
Usha

Algorithm:
P a g e | 25

1) Accept sizes of both the arrays and create the arrays.


2) Accept the names in both arrays.
3) Merge the names in both arrays into a third array.
4) Sort all the three arrays and print them.

Source code:
import java.util.*;
class MergeArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i,j,c1=0,c2=0;
System.out.println("Enter the number of names in Array A");
int N=sc.nextInt();
System.out.println("Enter the number of names in Array B");
int M=sc.nextInt();
String A[]=new String[N]; //Creating the arrays
String B[]=new String[M];
int L=N+M;
String tmp;
String C[]=new String[L]; //Creating the combined array of size M+N
System.out.println("First Array:");
for(i=0;i<N;i++) //Inputting the names of first array
{
A[i]=sc.next();
}
System.out.println("Second Array:");
for(i=0;i<M;i++) //Inputting names of second array
{
P a g e | 26

B[i]=sc.next();
}
for(i=0;i<N;i++) //Checking for repitition of names in arrays
{
for(j=i+1;j<N;j++)
{
if(A[i].equalsIgnoreCase(A[j]))
c1++;
if(B[i].equalsIgnoreCase(B[j]))
c2++;
}
}
if(c1>0)
System.out.println("Names are being repeated in first array");
if(c2>0)
System.out.println("Names are being repeated in second array");
if(c1==0&&c2==0) //If no names are repeated, both arrays are combined
{
for(i=0;i<N;i++)
C[i]=A[i]; //First array added to the merged array
j=0;
for(i=N;i<L;i++)
{
if(j<M)
{
C[i]=B[j]; //Second array added to merged array
j++;
}
}
for(i=0;i<L;i++) //Sorting the names of merged array
P a g e | 27

{
for(j=0;j<L-1-i;j++)
{
if(C[j].compareTo(C[j+1])>0)
{
tmp=C[j];
C[j]=C[j+1];
C[j+1]=tmp;
}
}
}
for(i=0;i<M;i++) //Sorting first array
{
for(j=0;j<M-1-i;j++)
{
if(B[j].compareTo(B[j+1])>0)
{
tmp=B[j];
B[j]=B[j+1];
B[j+1]=tmp;
}
}
}
for(i=0;i<N;i++) //Sorting second array
{
for(j=0;j<N-1-i;j++)
{
if(A[j].compareTo(A[j+1])>0)
{
tmp=A[j];
P a g e | 28

A[j]=A[j+1];
A[j+1]=tmp;
}
}
}
System.out.println("OUTPUT:");
System.out.println("Sorted Merged Array: (C)");
for(i=0;i<L;i++)
System.out.println(C[i]);
System.out.println("Sorted first Array: (A)");
for(i=0;i<N;i++)
System.out.println(A[i]);
System.out.println("Sorted second Array: (B)");
for(i=0;i<M;i++)
System.out.println(B[i]);
}
}
}

Output:
Enter the number of names in Array A
2
Enter the number of names in Array B
3
First Array:
Suman
P a g e | 29

Anil
Second Array:
Usha
Sachin
John
OUTPUT:
Sorted Merged Array: (C)
Anil
John
Sachin
Suman
Usha
Sorted first Array: (A)
Anil
Suman
Sorted second Array: (B)
John
Sachin
Usha

Question 6
A new advanced Operating System, incorporating the latest hi-tech features
has been designed by Opera Computer Systems.
The task of generating copy protection codes to prevent software piracy has
been entrusted to Security Department.
P a g e | 30

The Security Department has decided to have codes containing a jumbled


combination of alternate uppercase letters of the alphabet starting from A
up to K (namely among A, C, E, G, I, K). The code may or may not be in
consecutive series of alphabets.
Each code should not exceed 6 characters and there should not be
repetition of characters. If it exceeds 6 characters, display an appropriate
error message.
Write a program to input a code and its length. At the first instance of an
error display “Invalid!” stating the appropriate reason. In case of no error,
display the message “Valid!”
Test your program for the following data and some random data.
SAMPLE DATA:
INPUT: N=4
ABCE
OUTPUT: Invalid! Only alternate letters permitted!
INPUT: N=4
AcIK
OUTPUT: Invalid! Only upper case letters permitted!
INPUT: N=4
AAKE
OUTPUT: Invalid! Repetition of characters not permitted!
INPUT: N=7
OUTPUT: Error! Length of string should not exceed 6 characters!
INPUT: N=4
AEGIK
OUTPUT: Invalid! String length not same as specified!
INPUT: N=3
ACE
OUTPUT: Valid!
INPUT: N=5
GEAIK
P a g e | 31

OUTPUT: Valid!

ALGORITHM:
1) Accept the length of string and if length is less than or equal to six,
accept the code.
2) Check for the given conditions one by one.
3) If the code satisfies all conditions, print positive result that it is valid.

Source code:

import java.util.*;
class CopyProtection
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of N");
int N=sc.nextInt(); //Inputting length of string
if(N>6)
System.out.println("Error! Length of string should not exceed 6 characters!");
else if(N<=6)
{
System.out.println("Enter the code");
String s=sc.next(); //Inputting the code
int l=s.length();
int i,j,count=0;
char c,ch;
if(l!=N)
System.out.println("Invalid! String length not same as specified!");
else if(l==N)
{
count=0;
P a g e | 32

for(i=0;i<l;i++)
{
c=s.charAt(i);
if(Character.isUpperCase(c))
count++; //Counting the number of characters which are in capital letters
}
if(count!=l) //If count is not equal to length, it means some letters are not in caps
System.out.println("Invalid! Only uppercase letters permitted!");
else
{
count=0;
for(i=0;i<l;i++)
{
c=s.charAt(i);
for(j=i+1;j<l;j++)
{
ch=s.charAt(j);
if(c==ch)
count++; //Counting repeated characters
}
}
if(count>0)
System.out.println("Invalid! Repitition of characters not permitted!");
else
{
for(i=0;i<l;i++)
{
c=s.charAt(i);
if(c=='A'||c=='C'||c=='E'||c=='G'||c=='I'||c=='K')
count++;
P a g e | 33

}
if(count!=l)
System.out.println("Invalid! Only alternate letters permitted!");
else
System.out.println("Valid");
}
}
}
}
}
}

Output:
1) Enter the value of N
4
Enter the code
ABCE
OUTPUT:
Invalid! Only alternate letters permitted!

2) Enter the value of N


4
Enter the code
AcIK
OUTPUT:
Invalid! Only uppercase letters permitted!
3) Enter the value of N
4
Enter the code
AAKE
Invalid! Repitition of characters not permitted!
P a g e | 34

4) Enter the value of N


7
Error! Length of string should not exceed 6 characters!
5) Enter the value of N
4
Enter the code
AEGIK
Invalid! String length not same as specified!
6) Enter the value of N
3
Enter the code
ACE
Valid
7) Enter the value of N
4
Enter the code
SUMI
Invalid! Only alternate letters permitted!

Question 7
Write a program to accept a date in the string format dd/mm/yyyy and
accept the name of the day on 1st of January of the corresponding year. Find
the day for the given date.
Example:
Input: Date : 5/7/2001
Day on first January : MONDAY
Output:
Day on 5/7/2001 : THURSDAY
P a g e | 35

Test run the program on the following inputs:


INPUT DATE DAY ON 1ST JANUARY OUTPUT DAY FOR INPUT DATE
4/9/1998 THURSDAY FRIDAY
31/8/1999 FRIDAY TUESDAY
6/12/2000 SATURDAY WEDNESDAY

The program should include the part for validating the inputs namely the
date and the day on 1st January of that year.

ALGORITHM:
1) Accept a date in the format dd/mm/yyyy and also the day of 1 st of
January of that year.
2) Use string tokenizer to separate the date, month and year from
inputted date.
3) Create a 1-D array to store total number of days of each month. The
number of days in ‘i’th month will be at index ‘i+1’ in the array.
4) Find the number of days from January 1st to the inputted date.
5) When we divide the above result by 7, its reminder will give us the
number of that day in the week. For e.g.: It gives 1 for Monday and 0
for Sunday.
6) We can find the number of the day in the week of the day on 1 st
January from array.
7) According to the above value and the value obtained from step 5, we
can find the day of the required date from the array.

Source code:
import java.util.*;
class FindDay
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
P a g e | 36

System.out.println("Enter date in the format dd/mm/yyyy");


String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s,"/ "); /*Divide the inputted
date into three parts seperated by '/' */
int date,month,year;
date=Integer.parseInt(st.nextToken());
month=Integer.parseInt(st.nextToken());
year=Integer.parseInt(st.nextToken());
System.out.println("Enter day on first January");
String day=sc.next();
int i,j,sum=date,find,pos=0,index;
int m[]={31,28,31,30,31,30,31,31,30,31,30,31}; /*Creating an array which
holds total number of days per month*/
for(i=0;i<month-1;i++)
{
sum+=m[i]; //Finding the number of days from january 1st to the inputted date
}
if(year%4==0&&month>2)
sum++; //For leap year
find=sum%7; //Divide the sum by 7 to find number of the day of the week
String d[];//Array to hold the days of a week
d[]={"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};
for(i=0;i<7;i++)
{
if(d[i].equalsIgnoreCase(day))
{
pos=i; //Finding the position of the inputted day in the array
break;
}
}
P a g e | 37

index=pos+(find-1); //Index of required date


if(index>7)
index=index-7;
System.out.print("Day on "+s+":");
System.out.println(d[index]);
}
}

Output:
1) Enter date in the format dd/mm/yyyy
5/7/2001
Enter day on first January
MONDAY
OUTPUT:
Day on 5/7/2001: THURSDAY

2) Enter date in the format dd/mm/yyyy


4/9/1998
Enter day on first January
THURSDAY
P a g e | 38

OUTPUT:
Day on 4/9/1998: FRIDAY

3) Enter date in the format dd/mm/yyyy


31/8/1999
Enter day on first January
FRIDAY
OUTPUT:
Day on 31/8/1999:TUESDAY

4) Enter date in the format dd/mm/yyyy


6/12/2000
Enter day on first January
SATURDAY
OUTPUT:
Day on 6/12/2000:WEDNESDAY
Question 8
The input in this problem will consist of a number of lines of English text
consisting of the letters of the English alphabet, the punctuation marks (‘)
apostrophe, (.) full stop, (,) comma, (;) semicolon, (:) colon and white space
characters (blank, new line). Your task is to print the words of the text in
reverse order without any punctuation marks other than blanks.
For example consider the following input text:
This is a sample piece of text to illustrate this problem.
If you are smart you will solve this right.
The corresponding output would read as:
Right this solve will you smart are you If problem this illustrate to text of
piece sample a is This
That is the lines are printed in reverse order.
Note: Individual words are not reversed.
P a g e | 39

Input format:
The first line of input contains a single integer N(<=20), indicating the
number of lines in the input. This is followed by N lines of input text. Each
line should accept a maximum of 80 characters.
Output format:
Output the text containing the input lines in reverse order without
punctuation except blanks as illustrated above.
Test your program for the following data and some random data.

SAMPLE DATA:
INPUT: 2
Emotions, controlled and directed to word is character.
By Swami Vivekananda.

OUTPUT:
Vivekananda Swami By character is word to directed and
controlled Emotions.
INPUT: 1
Do not judge a book by its cover.
OUTPUT:
Cover its by book a judge not Do

ALGORITHM:
1) Accept a string of ‘N’ lines.
2) Convert the string of ‘N’ lines into a single string.
3) Remove the separators of the string and add each word of the string
into an array.
4) Print the array in reverse order i.e. the last element first and the
first element last.
P a g e | 40

Source code:
import java.util.*;
class Reverse
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of lines");
int N=sc.nextInt();
System.out.println("Enter the statement");
int i,l;
String str="";
String a[];
for(i=1;i<=N;i++)
{
String s=sc.nextLine();
str=str+" "+s; //Converting the string of N lines into a single string
}
StringTokenizer st=new StringTokenizer(str,",. :;'");
l=st.countTokens();
a=new String[l];
while(st.hasMoreTokens())
{
for(i=0;i<l;i++)
{
a[i]=st.nextToken(); //Adding each word of the string into an array
}
}
System.out.println(“OUTPUT:”);
for(i=l-1;i>=0;i--)
P a g e | 41

{
System.out.print(a[i]+" "); //Printing the array in reverse order
}
System.out.print(“.”);
}
}

Output:
1) Enter the number of lines
2
Enter the statement
Emotions, controlled and directed to word is character.
By Swami Vivekananda.
OUTPUT:
Vivekananda Swami By character is word to directed and controlled
Emotions.

2) Enter the number of lines


1
Enter the statement
Do not judge a book by its cover.
OUTPUT:
cover its by book a judge not Do .
P a g e | 42

3) Enter the number of lines


3
Enter the statement
My name is Sumathi.
I am studying in seventh day school.
This is my computer project.
OUTPUT:
project computer my is This school day seventh in studying am I
Sumathi is name My .

Question 9
A unique-digit integer is a positive integer (without leading zeroes) with no
duplicate digits. For example 7, 135, 214 are all unique-digit integers
whereas 33, 3121, 300 are not.
Given two positive integers m and n where m<n. Write a program to
determine how many unique-digit integers are there in the range between m
and n (both inclusive) and output them.
The input contains two positive integers m and n. Assume m<3000 and
n<3000. You are to output the number of unique-digit integers in the
specified range along with their values in the format specified below:
SAMPLE DATA:
INPUT: m=100
n=120
OUTPUT: THE UNIQUE-DIGIT INTEGERS ARE:-
102, 103, 104, 105, 106, 107, 109, 120
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 9
P a g e | 43

ALGORITHM:
1) Accept the range.
2) Take the numbers in between the range one by one and convert them
into string type.
3) Take each digit of one number and check whether it occurs more than
once.
4) If no digits are repeated, print the number else pass on to the next
number.

Source code:
import java.util.*;
class UniqueDigitIntegers
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range");
int m=sc.nextInt();
int n=sc.nextInt();
int i,j,k,count=0,f=0;
String s;
char d,ch;
if(m<3000&&n<3000)
{
System.out.println("THE UNIQUE-DIGIT INTEGERS ARE:");
for(i=m;i<=n;i++)
{
P a g e | 44

s=Integer.toString(i); //Converting the number into string type


for(j=0;j<s.length();j++)
{
d=s.charAt(j); //Taking the digits one by one
for(k=j+1;k<s.length();k++)
{
ch=s.charAt(k);
if(ch==d) //If any digit occurs more than once, count is incremented
count++;
}
}
if(count==0)
{
System.out.print(i+", ");
f++;
}
count=0;
}
System.out.println();
System.out.println("FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: "+f);
}
else
System.out.println("Range should not exceed 3000");
}
}
Output:
1) Enter the range
100
120
THE UNIQUE-DIGIT INTEGERS ARE:
P a g e | 45

102, 103, 104, 105, 106, 107, 108, 109, 120,


FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 9

2) Enter the range


1000
3500
Range should not exceed 3000
P a g e | 46

Question 10
A smith number is a composite number, the sum of whose digits is the sum of
the digits of its prime factors obtained as a result of prime factorization
(excluding 1). The first few such numbers are: 4, 22, 27, 58, 85, 94, 121 ……..
Example:
1) 666
Prime factors are 2, 3, 3, and 37.
Sum of the digits are (6+6+6) =18
Sum of the digits of the factors (2+3+3+ (3+7)) =18
2) 4937775
Prime factors are 3, 5, 5, 65837
Sum of the digits are (4+9+3+7+7+7+5) =42
Sum of digits of the factors (3+5+5+ (6+5+8+3+7)) =42

Write a program to input a number and display whether the number is a


Smith number or not.
Sample data:
Input 94 Output SMITH Number
Input 102 Output NOT SMITH Number
Input 666 Output SMITH Number
Input 999 Output NOT SMITH Number

ALGORITHM:
1) Accept a number.
2) Find its factors and find their sum.
3) Find the sum of digits of the number.
4) If sum of factors and sum of digits are equal, then the number is
smith number.

Source code:
P a g e | 47

import java.util.*;
class Smith
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int num=sc.nextInt();
Smith obj=new Smith(); //Creating an object
System.out.println("OUTPUT:”);
if(obj.sumFactors(num)==obj.sumDigits(num)) //Calling the two sub functions
System.out.println(num+" is a smith number");
else
System.out.println(num+" is not a smith number");
}
public int sumFactors(int n) //Function to find sum of the factors
{
int i,index=0,d;
int a[]=new int[n];
int sumf=0;
for(i=2;i<=n;i++)
{
while(n%i==0)
{
a[index]=i;
index++;
n=n/i;
}
}
for(i=0;i<=index;i++)
P a g e | 48

{
if(a[i]%10==0)
sumf+=a[i];
else
{
while(a[i]!=0)
{
d=a[i]%10;
sumf+=d;
a[i]/=10;
}
}
}
return sumf;
}
public int sumDigits(int no) //Function to find sum of digits of the number
{
int sumd=0,d;
while(no!=0)
{
d=no%10;
sumd+=d;
no/=10;
}
return sumd;
}
}

Output:
1) Enter a number
P a g e | 49

4937775
OUTPUT:
4937775 is a smith number
2) Enter a number
94
OUTPUT:
94 is a smith number
3) Enter a number
102
OUTPUT:
102 is not a smith number
4) Enter a number
666
OUTPUT:
666 is a smith number
5) Enter a number
999
OUTPUT:
999 is not a smith number

Question 11
P a g e | 50

A sentence is terminated by either “.”, “!” or “?” followed by a space. Input a


piece of text consisting of sentences. Assume that there will be a maximum
of 10 sentences in block letters
Write a program to:
(i) Obtain the length of the sentence (measured in words) and the
frequency of vowels in each sentence.
(ii) Generate the output as shown below using the given data.
Sample Data:
INPUT
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF
LUCK.
OUTPUT
Sentence No. of Vowels No. of Words
-----------------------------------------------------------------
1 2 1
2 5 3
3 8 4
4 3 3
Sentence No. of Words/Vowels
-----------------------------------------------------------------
1 VVVVVV
WWW
2 VVVVVVVVVVVVVVV
WWWWWWWWW
3 VVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWW
4 VVVVVVVVV
WWWWWWWWW
-------------------------------------------------------------------
Scale used: 1:3

ALGORITHM:
P a g e | 51

1) Accept a group of sentences separated by “.”, “!” or “?” followed by a


space.
2) Separate the sentences.
3) For each sentence, count the number of words and number of vowels in
it and print the result in the required format.

Source code:
import java.util.*;
class VowelCount
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
s=s.toUpperCase();
StringTokenizer st=new StringTokenizer(s,".,!?");
int sent=st.countTokens();
String sen,vow;
char ch;
int i,j,k,words,vowels=0;
System.out.println("OUTPUT:”);
System.out.println("Sentence\tNo.of Vowels\tNo.of words");
System.out.println("---------------------------------------------");
for(i=1;i<=sent;i++)
{
sen=st.nextToken(); //Seperating the sentences
StringTokenizer str=new StringTokenizer(sen);
words=str.countTokens(); //Counting the number of words
vowels=0;
P a g e | 52

for(k=0;k<sen.length();k++)
{
ch=sen.charAt(k);
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
vowels++; //Counting number of vowels
}
System.out.println(i+"\t\t "+vowels+"\t\t "+words);
}
System.out.println("Sentence\tNo.of words/vowels");
System.out.println("------------------------------------");
StringTokenizer stri=new StringTokenizer(s,".,!?");
for(i=1;i<=sent;i++)
{
vow=stri.nextToken();
vowels=0;
for(k=0;k<vow.length();k++)
{
ch=vow.charAt(k);
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
vowels++;
}
System.out.print(i+"\t");
for(j=1;j<=vowels;j++)
{
System.out.print("VVV");
}
System.out.println();
System.out.print("\t");
StringTokenizer string=new StringTokenizer(vow);
words=string.countTokens();
P a g e | 53

for(j=1;j<=words;j++)
{
System.out.print("WWW");
}
System.out.println();
}
System.out.println("-------------------------------------");
System.out.println("Scale used=1:3");
}
}

Output:

1) Enter a sentence
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF
LUCK.

OUTPUT:
Sentence No.of Vowels No.of words
---------------------------------------------
1 2 1
2 5 3
3 8 4
4 3 3
Sentence No.of words/vowels
------------------------------------
1 VVVVVV
WWW
2 VVVVVVVVVVVVVVV
P a g e | 54

WWWWWWWWW
3 VVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWW
4 VVVVVVVVV
WWWWWWWWW
-------------------------------------
Scale used=1:3

2) Enter a sentence
This is a program to count number of vowels! It also counts the
number of words in it.
OUTPUT:
Sentence No.of Vowels No.of words
---------------------------------------------
1 13 9
2 12 9
Sentence No.of words/vowels
------------------------------------
1 VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWWWWWWW
2 VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWWWWWWW
-------------------------------------
Scale used=1:3

Question 12
P a g e | 55

Given a square matrix list[ ][ ] of order ‘n’. The maximum value possible for ‘n’
is 20. Input the value for ‘n’ and the positive integers in the matrix and
perform the following tasks:
1) Display the original matrix.
2) Print the row and column position of the largest element of the matrix.
3) Print the row and column position of the second largest element of the
matrix.
4) Sort the elements of the rows in the ascending order and display the
new matrix.

Sample Data:
INPUT:
N=3
List[ ][ ] 5 1 3
7 4 6
9 8 2
OUTPUT:
5 1 3
7 4 6
9 8 2
The largest element 9 is in row 3 and column 1
The second largest element 8 is in row 3 and column 2
Sorted List
1 3 5
4 6 7
2 8 9

ALGORITHM:

1) Accept the elements of the grid and print the original grid.
2) Find the largest element of the grid and find its position in the grid.
P a g e | 56

3) Similarly find the second largest element and print the result.
4) Sort the array and print the sorted array.

Source code:
import java.util.*;
class SortArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the dimension of the square matrix");
int n=sc.nextInt();
int list[][]=new int[n][n];
int s=n*n;
int a[]=new int[s];
int i,j,in,large,sec;
int tmp,r=0,c=0;
System.out.println("Enter the elements");
in=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
list[i][j]=sc.nextInt();
a[in]=list[i][j]; //Adding the elements into a single array also
in++;
}
}
System.out.println("OUTPUT:");
for(i=0;i<n;i++)
P a g e | 57

{
for(j=0;j<n;j++)
{
System.out.print(list[i][j]+"\t"); //Printing the original grid
}
System.out.println();
}
large=a[0];
for(i=0;i<s;i++) //Finding the largest element
{
if(a[i]>large)
large=a[i];
}
sec=a[0];
for(i=0;i<s;i++) //Finding second largest element
{
if(a[i]>sec&&a[i]<large)
sec=a[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(list[i][j]==large)
{
r=i+1; //Finding position of largest element in the grid
c=j+1;
break;
}
}
P a g e | 58

}
System.out.println("The largest element "+large+" is in row "+r+" and column "+c);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(list[i][j]==sec) //Finding position of second largest element in the grid
{
r=i+1;
c=j+1;
break;
}
}
}
System.out.println("The second largest element "+sec+" is in row "+r+" and column "+c);
r=0;
System.out.println("Sorted list:");
while(r<n)
{
for(i=0;i<n;i++) //Sorting the grid
{
for(j=0;j<n-1;j++)
{
if(list[r][j]>list[r][j+1])
{
tmp=list[r][j];
list[r][j]=list[r][j+1];
list[r][j+1]=tmp;
}
}
P a g e | 59

}
for(c=0;c<n;c++)
System.out.print(list[r][c]+"\t");
System.out.println();
r++;
}
}
}

Output:
Enter the dimension of the square matrix
3
P a g e | 60

Enter the elements


5
1
3
7
4
6
9
8
2

OUTPUT:
5 1 3
7 4 6
9 8 2
The largest element 9 is in row 3 and column 1
The second largest element 8 is in row 3 and column 2
Sorted list:
1 3 5
4 6 7
2 8 9
P a g e | 61

Question 13
Design a program to accept a day number (between 1 and 366), year (in 4
digits) from the user to generate and display the corresponding date. Also
accept ‘N’ (1<=N<=100) from the user to compute and display future date
corresponding to ‘N’ days after the generated date. Display error message if
the value of the day number, year and N are not within the limit or according
to the condition specified.

Test your program for the following data and some random data.

Example:
1. INPUT:
DAY NUMBER : 233
YEAR : 2008
DATE AFTER (N) : 17
OUTPUT:
20 TH AUGUST 2008
DATE AFTER 17 DAYS : 6 TH SEPTEMBER 2008
2. INPUT:
DAY NUMBER : 360
YEAR : 2008
DATE AFTER (N) : 45
OUTPUT:
25 TH DDECEMBER 2008
DATE AFTER 45 DAYS : 8 TH FEBRUARY 2009

ALGORITHM:
P a g e | 62

1) Accept the required inputs: ‘day’=number of day for which date is to


be found out, ‘year’, and ‘n’=number of days after ‘day’.
2) Create two arrays: one to store the total number of days in a month
and the other to store the names of the month.
3) If the year is a leap year, 2nd month should have 29 days. If ‘day’ is
greater than 365, year is incremented by 1 and day is decreased by
365.
4) We find the sum of total number of days in each month from the array
till it becomes greater than or equal to day.
5) The position of the last element of the sum gives the position of the
month’s name in the array.
6) The ‘day’ subtracted by the difference of sum and the total number of
days in that month gives our required date.
7) Steps 3 to 6 are repeated for day=day+n.

Source code:
import java.util.*;
class FindDate
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("DAY NUMBER:");
int day=sc.nextInt();
System.out.println("YEAR:");
int year=sc.nextInt();
System.out.println("DAY AFTER(N):");
int n=sc.nextInt();
System.out.println("OUPUT:”);
int i,sum=0,pos=0,date,num=1;
String mon;
if(day<=366&&n<=100&&n>=1)
{
P a g e | 63

int month[]={31,28,31,30,31,30,31,31,30,31,30,31}; /*Total number of days in


a month*/
if(year%4==0)
month[1]=29; //Leap year has 29 days on february
String
m[]={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY",
"AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"};
//Names of the months
while(num<=2)
{
if(day>365&&month[1]==28)
{
day=day-365;
year++; //If the number of days exceeds 365, it means that it is next year
}
if(day>366&&month[1]==29) //Same case for leap year
{
day=day-366;
year++;
}
for(i=0;i<12;i++)
{
sum+=month[i];
if(sum>=day)
{
pos=i; //position of the month is obtained
break;
}
}
mon=m[pos];
date=day-(sum-month[pos]); //finding date
if(date>month[pos])
{
mon=m[pos+1]; //Finding the month
P a g e | 64

date=date-month[pos];
}
if(num==2)
System.out.println("DAY AFTER "+n+" DAYS:");
System.out.println(date+"TH "+mon+" "+year);
num++;
day=day+n; //Next iteration to find the date after n days
sum=0;
}
}
else if(n>100||n<1)
System.out.println("N should not be greater than 100 or less than 1");
else if(day>366)
System.out.println("Day should be less than 366");
}
}

Output:
1) DAY NUMBER:
233
YEAR:
2008
DAY AFTER(N):
17
OUTPUT:
20TH AUGUST 2008
DAY AFTER 17 DAYS:
6TH SEPTEMBER 2008
2) DAY NUMBER:
360
YEAR:
P a g e | 65

2008
DAY AFTER(N):
45
OUTPUT:
25TH DECEMBER 2008
DAY AFTER 45 DAYS:
8TH FEBRUARY 2009
3) DAY NUMBER:
300
YEAR:
2014
DAY AFTER(N):
20
27TH OCTOBER 2014
DAY AFTER 20 DAYS:
16TH NOVEMBER 2014
Question 14
Write a program to declare a matrix A[ ][ ] of order (m*n) 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 positive integers
into this matrix. Perform the following tasks on the matrix.
a) Sort the elements of the outer row and column elements in
ascending order using any standard sorting technique.
b) Calculate the sum of the outer row and column elements.
c) Output the original matrix, rearranged matrix and only the
boundary elements of the rearranged array with their sum.
Test your program for the following data and some random data.

1. Example:

INPUT: M=3
N=3
P a g e | 66

1 7 4
8 2 5
6 3 9
OUTPUT:
ORIGINAL MATRIX:
1 7 4
8 2 5
6 3 9
REARRANGED MATRIX:
1 3 4
9 2 5
8 7 6
BOUNDARY ELEMENTS:
1 3 4
9 5
8 7 6
SUM OF THE OUTER ROW AND COLUMN ELEMENTS= 43
2. Example:
INPUT: M=2
N=3
7 1 6
8 9 2
OUTPUT:
ORIGINAL MATRIX:
7 1 6
8 9 2
REARRANGED MATRIX:
1 2 6
9 8 7
BOUNDARY ELEMENTS:
1 2 6
9 8 7
SUM OF THE OUTER ROW AND COLUMN ELEMENTS = 33
3. Example:
INPUT: M=4
P a g e | 67

N=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:
1 2 4 5
23 13 8 7
15 6 3 8
12 11 9 8
BOUNDARY ELEMENTS:
1 2 4 5
23 7
15 8
12 11 9 8

ALGORITHM:
1) Accept the array.
2) Add the boundary elements into a single 1-D array.
3) Sort the elements of the 1-D array.
4) Print the rearranged matrix.
5) Print only the boundary elements.
6) Find the sum of boundary elements and print it.

Source code:
P a g e | 68

import java.util.*;
class Boundary
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows");
int M=sc.nextInt();
System.out.println("Enter the number of columns");
int N=sc.nextInt();
int A[][]=new int[M][N];
int s=M*N,sum=0;
int a[]=new int[s];
String b[][]=new String[M][N];
int i,j,tmp,index=-1;
String str[]=new String[s];
System.out.println("Enter the array elements");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
A[i][j]=sc.nextInt();
}
}
System.out.println("ORIGINAL MATRIX"); //Printing original matrix
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
System.out.print(A[i][j]+"\t");
P a g e | 69

}
System.out.println();
}
for(i=0;i<N;i++)
{
index++;
a[index]=A[0][i]; //Elements of 1st row added to 1-D matrix
}
for(i=1;i<M;i++)
{
index++;
a[index]=A[i][N-1]; //Elements of last column added to 1-D matrix
}
for(i=N-2;i>=0;i--)
{
index++;
a[index]=A[M-1][i]; //Elements of last row added to 1-D matrix
}
for(i=M-2;i>0;i--)
{
index++;
a[index]=A[i][0]; //Elements of 1st column also added to 1-D matrix
}
for(i=0;i<=index;i++) //Sorting the elements of boundary
{
for(j=0;j<=index-1-i;j++)
{
if(a[j]>a[j+1])
{
tmp=a[j];
P a g e | 70

a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
System.out.println("REARRANGED MATRIX"); //Printing rearranged matrix
index=-1;
for(i=0;i<N;i++)
{
index++;
A[0][i]=a[index];
}
for(i=1;i<M;i++)
{
index++;
A[i][N-1]=a[index];
}
for(i=N-2;i>=0;i--)
{
index++;
A[M-1][i]=a[index];
}
for(i=M-2;i>0;i--)
{
index++;
A[i][0]=a[index];
}
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
P a g e | 71

{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
for(i=0;i<=index;i++)
{
str[i]=Integer.toString(a[i]);
}
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
b[i][j]=" ";
}
}
index=-1;
for(i=0;i<N;i++)
{
index++;
b[0][i]=str[index];
}
for(i=1;i<M;i++)
{
index++;
b[i][N-1]=str[index];
}
for(i=N-2;i>=0;i--)
{
index++;
b[M-1][i]=str[index];
P a g e | 72

}
for(i=M-2;i>0;i--)
{
index++;
b[i][0]=str[index];
}
System.out.println("BOUNDARY ELEMENTS"); //printing boundary elements
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
System.out.print(b[i][j]+"\t");
}
System.out.println();
}
for(i=0;i<=index;i++)
sum+=a[i];
System.out.println("SUM OF THE OUTER ROW AND COLUMN
ELEMENTS="+sum);
}
}

Output:
1) Enter the number of rows
3
Enter the number of columns
3
Enter the array elements
1
7
P a g e | 73

4
8
2
5
6
3
9
ORIGINAL MATRIX
1 7 4
8 2 5
6 3 9
REARRANGED MATRIX
1 3 4
9 2 5
8 7 6
BOUNDARY ELEMENTS
1 3 4
9 5
8 7 6
SUM OF THE OUTER ROW AND COLUMN ELEMENTS=43

2) Enter the number of rows


2
Enter the number of columns
3
Enter the array elements
7
1
6
8
9
2
P a g e | 74

ORIGINAL MATRIX
7 1 6
8 9 2
REARRANGED MATRIX
1 2 6
9 8 7
BOUNDARY ELEMENTS
1 2 6
9 8 7
SUM OF THE OUTER ROW AND COLUMN ELEMENTS=33

3) Enter the number of rows


4
Enter the number of columns
4
Enter the array elements
9
2
1
5
8
13
8
4
15
6
3
11
7
12
P a g e | 75

23
8
ORIGINAL MATRIX
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
REARRANGED MATRIX
1 2 4 5
23 13 8 7
15 6 3 8
12 11 9 8
BOUNDARY ELEMENTS
1 2 4 5
23 7
15 8
12 11 9 8
SUM OF THE OUTER ROW AND COLUMN ELEMENTS=105
P a g e | 76

Question 15
Read a single sentence which terminates with a full stop (.)The words are to
be separated with a single blank space and are in lower case. Arrange the
words contained in the sentence according to the length of the words in
ascending order. If two words are of same length then the word occurring
first in the sentence should come first. For both input and output the
sentence must begin in upper case.
Test your program for the following data and some random data.
INPUT : The lines are printed in reverse order.
OUTPUT : In the are lines order printed reverse.
INPUT : Print the sentence in ascending order.
OUTPUT : In the print order sentence ascending.
INPUT : I love my country.
OUTPUT : I my love country.
ALGORITHM:
1) Accept a sentence.
2) Take the words of the sentence one by one and store it in a string
array.
3) Sort the array and print the array.

Source code:
import java.util.*;
class WordArrange
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
P a g e | 77

s=s.toLowerCase();
int token,i,j;
String str,tmp,sub;
char ch;
StringTokenizer st=new StringTokenizer(s," .");
token=st.countTokens();
String a[]=new String[token];
i=0;
while(st.hasMoreTokens())
{
str=st.nextToken();
a[i]=str; //Taking each word and saving in an array
i++;
}
for(i=0;i<token;i++)
{
for(j=0;j<token-1-i;j++)
{
if(a[j].length()>(a[j+1]).length()) //Sorting the array
{
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
tmp=a[0];
ch=tmp.charAt(0);
sub=tmp.substring(1);
System.out.println(“OUTPUT:”);
P a g e | 78

System.out.print(Character.toUpperCase(ch)+sub+" "); //First letter of first word


to be printed in caps
for(i=1;i<token;i++)
{
System.out.print(a[i]+" "); //Printing the arranged sentence
}
System.out.print(".");
}
}

Output:
1) Enter a sentence
The lines are printed in reverse order.
OUTPUT:
In the are lines order printed reverse .

2) Enter a sentence
Print the sentence in ascending order.
OUTPUT:
In the print order sentence ascending .

3) Enter a sentence
I love my country.
OUTPUT:
I my love country .
P a g e | 79

Question 16
A bank intends to design a program to display the denomination of input
amount up to 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 denominations available) along with the total number of notes.
[Note: Only denominations used should be displayed]. Also print the amount
in words according to the digits.
Test your program for the following data and some random data.

Example 1:
Input: 14856
Output: ONE FOUR EIGHT FIVE SIX
DENOMINATIONS:
1000 x 14 = 14000
500 x 1 = 500
100 x 3 = 300
50 x 1 = 50
5 x 1 = 5
1 x 1 = 1
TOTAL = 14856
TOTAL NUMBER OF NOTES = 21

Example 2:
Input: 6043
Output: SIX ZERO FOUR THREE
DENOMINATIONS:
1000 x 6 = 6000
P a g e | 80

20 X 1 = 20
2 x 1 = 2
1 x 1 = 1
TOTAL = 6043
TOTAL NUMBER OF NOTES =10

Example 3:
Input: 235001
Output: INVALID AMOUNT

ALGORITHM:

1) Accept an amount.
2) Check whether the amount has more than 5 digits.
3) In the first sub-function, the digits of the amount are taken one by
one and using switch case, the number-names are displayed.
4) In the second sub-function, the denominations are stored in an array.
5) The amount is divided by each denomination and the quotient and
remainder is found out.
6) The quotient is added into a sum variable and the difference between
amount and quotient is used as the amount for the next iteration of
the denomination.
7) The denominations are displayed along with the number of notes i.e.,
sum.

Source code:
import java.util.*;
class Denominations
{
static int amt; //Static variable
public static void main(String args[])
{
P a g e | 81

Scanner sc=new Scanner(System.in);


System.out.println("Enter the amount");
amt=sc.nextInt();
if(Integer.toString(amt).length()>5) //Checking if number has more than 5 digits
System.out.println("INVALID AMOUNT");
else
{
Denominations obj=new Denominations(); //Object creation statement
obj.Digits(amt); //Calling function through object
obj.Deno(amt);
}
}
public void Digits(int a)
{
int d,rev=0,d1;
String
ar[]={"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIG
HT","NINE"};
while(a!=0)
{
d=a%10;
rev=rev*10+d;
a/=10;
}
while(rev!=0)
{
d1=rev%10;
System.out.print(ar[d1]+" ");
rev/=10;
}
P a g e | 82

System.out.println();
}
public void Deno(int am)
{
int r,q,i=0,sum=0;
int a[]={1000,500,100,50,20,10,5,2,1}; //Array to hold denominations
System.out.println("Denominations:");
while(am!=0&&i<a.length)
{
q=am/a[i]; //Finding quotient
r=am%a[i]; //Remainder
if(q!=0)
System.out.println(a[i]+"\tx\t"+q+"\t=\t"+q*a[i]);
sum+=q;
am=am-(q*a[i]); //The difference is used as the amount for next iteration
i++;
}
System.out.println("\t\tTOTAL\t=\t"+amt);
System.out.println("TOTAL NUMBER OF NOTES\t=\t"+sum);
}
}

Output:
1) Enter the amount
14856
ONE FOUR EIGHT FIVE SIX
Denominations:
1000 x 14 = 14000
500 x1 = 500
100 x3 = 300
P a g e | 83

50 x1 = 50
5 x1 = 5
1 x1 = 1
TOTAL = 14856
TOTAL NUMBER OF NOTES = 21
2) Enter the amount
6043
SIX ZERO FOUR THREE
Denominations:
1000 x6 = 6000
20 x2 = 40
2 x1 = 2
1 x1 = 1
TOTAL= 6043
TOTAL NUMBER OF NOTES = 10
3) Enter the amount
235001
INVALID AMOUNT
P a g e | 84

Question 17
A positive whole number ‘n’ that has ‘d’ number of digits is squared and split
into two pieces, a right-hand piece that has ‘d’ digits and a left-hand piece
that has remaining ‘d’ or ‘d-1’ digits. If the sum of the two pieces is equal to
the number, then ‘n’ is a Kaprekar Number. The first few Kaprekar
Numbers are: 9, 45, 297……

Example 1: 9 (here the value of d=1 i.e. number of digits=1)


92=81, right-hand piece of 81=1 and left-hand piece of 81=8
Sum = 1 + 8 = 9, i.e. equal to the number, so number 9 is kaprekar
number.
Example 2: 45 (here the value of d=2 i.e. number of digits=2)
452=2025, right-hand piece of 2025 = 25 and left-hand piece of
2025 = 20
Sum = 25 + 20 = 45, i.e. equal to the number, so number 45 is
kaprekar number.
Example 3: 297 (here the value of d=3 i.e. number of digits=3)
2972=88209, right-hand piece of 88209 = 209 and left-hand
piece of 88209 = 88
Sum = 209 + 88 = 297, i.e. equal to the number, so number 297 is
kaprekar number.

Given 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).

The input contains two positive integers p and q. Assume p<5000 and q<5000.
You are to output the number of kaprekar numbers in the specified range
along with their values in the format specified below:
P a g e | 85

SAMPLE DATA:
INPUT: p=1 and q=1000
OUTPUT: THE KAPREKAR NUMBERS ARE:- 1,9,45,55,99,297,703,999
FREQUENCY OF KAPREKAR NUMBERS IS: 8

ALGORITHM:
1) Accept a limit.
2) Take the numbers in between the limit one by one and convert it into
string type and find its length ‘d’.
3) Take the square and convert it to string type.
4) Extract ‘d’ number of characters from the square of the number. This
is the right-hand piece and the remaining left-hand piece.
5) Add the right-hand piece and left-hand piece.
6) If the sum becomes equal to the number itself, then print the number.

Source code:
import java.util.*;
class Kaprekar
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a limit");
int p=sc.nextInt();
int q=sc.nextInt();
int f=0;
System.out.println("THE KAPREKAR NUMBERS ARE:");
for(int n=p;n<=q;n++)
{
int rh=0,lh=0,sum=0,digit;
int sq=n*n; //Finding square
P a g e | 86

digit=0;
for(int i=n;i>0;i/=10)
{
digit++; //Count number of digits in n
}
rh=(int)(Math.round(sq%(Math.pow(10,digit)))); //last 'd' digits of square is found
lh=(int)(Math.round(sq/Math.pow(10,digit))); /*Remaining digits are stored as left
-hand piece*/
sum=rh+lh; //Sum of left and right hand pieces
if(sum==n)
{
System.out.print(n+", "); //displaying kaprekar numbers
f++; //Finding frequency of kaprekar numbers in the range
}
}
System.out.println();
System.out.println("FREQUENCY OF KAPREKAR NUMBERS:"+f);
}
}

Output:
Enter a limit
1
1000
THE KAPREKAR NUMBERS ARE:
1, 9, 45, 55, 99, 297, 703, 999,
FREQUENCY OF KAPREKAR NUMBERS: 8

Question 18
P a g e | 87

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 ‘.’ Or a question mark ‘?’ only.
Any other character may be ignored. Perform the following operations:
(i) Accept the number of sentences. If the number of sentences exceeds
the limit, an appropriate error message should be displayed.
(ii) Find the number of words in the whole paragraph.
(iii) Display the words in ascending order of their frequency. Words with
the same frequency may appear in any order.
Example 1: INPUT:
Enter the number of sentences.
1
Enter sentence
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 the number of sentences.
3
Enter sentence
THIS IS A STRING PROGRAM.IS THIS EASY?YES IT IS.
OUTPUT:
Total number of words : 11
WORD FREQUENCY
A 1
STRING 1
P a g e | 88

PROGRAM 1
EASY 1
YES 1
IT 1
THIS 2
IS 3
Example 3: INPUT:
Enter the number of sentences.
5
INVALID ENTRY

ALGORITHM:
1) Accept a sentence and put each word of the sentence into an array.
2) Remove all duplicate elements and put the words into another array.
3) Add the frequency of the corresponding word into another array.
4) Sort the two arrays and print them.

Source code:
import java.io.*;
class Frequency
{
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the number of sentences");
int N=Integer.parseInt(br.readLine());
if(N<1||N>=4)
{
System.out.println("INVALID ENTRY");
}
P a g e | 89

else
{
System.out.println("Enter the sentences");
String sent=br.readLine(); //Inputting the sentence
sent=sent.toUpperCase();
int n=0;
String str,temp="";
char ch;
int h,d;
String w[]=sent.split("[ .?]"); //Adding the words of the sentence into an array
String word[]=new String[w.length];
int f[]=new int[w.length]; //Array to store frequency
for(int i=0;i<w.length;i++)
{
h=0;
d=0;
for(int j=0;j<i;j++)
{
if(w[i].compareTo(w[j])==0)
h=1; //Checking for duplicate elements
}
if(h==0)
{
for(int k=i;k<w.length;k++)
{
if(w[i].compareTo(w[k])==0)
d++;
}
word[n]=w[i]; //Adding the words without repitition into another array
f[n]=d; //Adding the corresponding frequencies into another array
P a g e | 90

n++;
}
}
for(int i=0;i<n-1;i++) //Sorting the arrays
{
for(int j=i+1;j<n;j++)
{
if(f[i]>f[j])
{
int u=f[i];
f[i]=f[j];
f[j]=u;
String s=word[i];
word[i]=word[j];
word[j]=s;
}
}
}
System.out.println("TOTAL NUMBER OF WORDS:"+w.length);
System.out.println("WORD\t\tFREQUENCY");
System.out.println("------------------------------");
for(int i=0;i<n;i++) //Printing the arrays
{
System.out.println(word[i]+"\t\t"+f[i]);
}
}
}
}

Output:
P a g e | 91

1) Enter the number of sentences


3
Enter the sentences
THIS IS A STRING PROGRAM.IS THIS EASY?YES IT IS.
TOTAL NUMBER OF WORDS:11
WORD FREQUENCY
------------------------------
A 1
STRING 1
PROGRAM 1
EASY 1
YES 1
IT 1
THIS 2
IS 3

Question 19
Write a program to input a natural number less than 1000 and display it in
words. Test your program for the given sample data and some random data
INPUT: 29
OUTPUT: TWENTY NINE
INPUT: 17001
P a g e | 92

OUTPUT: OUT OF RANGE


INPUT: 119
OUTPUT: ONE HUNDRED AND NINETEEN
INPUT: 500
OUTPUT: FIVE HUNDRED
ALGORITHM:
1) Accept a number, find its length and if it greater than 3, display
appropriate message.
2) Create three arrays: to store names of numbers if it occurs in one’s
place, ten’s place and hundred’s place respectively.
3) Find out the number in one’s place and find its corresponding name
from the one’s array.
4) Similarly find out the names of numbers in ten’s and hundred’s place
from their respective arrays.
Source code:
import java.util.*;
class NumberName
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Input a number");
int n=sc.nextInt();
int i;
String s=Integer.toString(n); //Converting n to string type
int d=s.length(); //Number of digits in n
if(d>3)
{
System.out.println("INVALID ENTRY");
}
else
P a g e | 93

{
String
o[]={"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NIN
E"}; //Array of names in ones place
String
h[]={"TEN","ELEVEN","TWELVE","THIRTEEN","FOURTEEN","FIFTEEN","S
IXTEEN","SEVENTEEN","EIGHTEEN","NINETEEN"};
String
t[]={"TWENTY","THIRTY","FOURTY","FIFTY","SIXTY","SEVENTY","EIGH
TY","NINETY"}; //Ten's place
if(d==3) //For three digit numbers
{
i=n/100;
System.out.print(o[i-1]+" HUNDRED"); //Naming the number in hundred's place
int ten=n%100;
if(ten/10==1)
{
System.out.print(" AND "+h[ten%10]); /*Naming number in ten's place if it is less
than 20*/
}
else if(ten/10>1)
{
System.out.print(" AND "+t[(ten/10)-2]); //Numbers in tens's place >20
}
if(ten%10!=0) //One's place
{
if(ten/10==0)
System.out.print(" AND "+o[(ten%10)-1]);
else
System.out.print(" "+o[(ten%10)-1]);
P a g e | 94

}
}
}
}
}
Output:
1) Input a number
29
TWENTY NINE
Input a number
17001
INVALID ENTRY
Input a number
119
ONE HUNDRED AND NINETEEN
Input a number
500
FIVE HUNDRED

Question 20
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:
P a g e | 95

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.
EXAMPLE 2:
INPUT: n=13
OUTPUT: INVALID ENTRY

ALGORITHM:
1) Accept the number of sentences and create an array with ‘n’ size.
2) Accept the sentences and store it in array.
3) Take the sentences one by one and store each word of the sentence into
another array using split() function.
4) Now take each word and take its character one by one. Nested loops are
used for this purpose.
5) For sentences in odd-rows, encrypt the words by converting the
characters to ASCII code and increment it by 2.
6) For sentences in even-rows, display the array in reversed form.

Source code:
import java.io.*;
class Encryption
{
public static void main(String args[])throws IOException
P a g e | 96

{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the number of sentences");
int n=Integer.parseInt(br.readLine());
if(n<1||n>10) //Checking condition
System.out.println("INVALID ENTRY");
else
{
int i,j,k;
String A[]=new String[n]; //Array to hold the sentences
String s,word;
char c;
int ch;
System.out.println("Enter the sentences");
for(i=0;i<n;i++)
A[i]=br.readLine(); //Accept sentences and store in an array
for(i=0;i<n;i++)
{
s=A[i]; //Taking the sentences one by one
s=s.toUpperCase();
String a[]=s.split("[ .]"); //Storing the words of the sentence into another array
if((i+1)%2!=0) //For sentences in odd rows
{
for(j=0;j<a.length;j++)
{
word=a[j]; //Taking words one by one from second array
for(k=0;k<word.length();k++)
{
c=word.charAt(k); //Taking each character of word
P a g e | 97

if(c!='Y'&&c!='Z')
{
ch=(int)c;
ch=ch+2; //The ASCII code ofcharacter at 2 places next to c
word=word.replace(c,(char)ch);
}
else if(c=='Y')
word=word.replace(c,'A'); //Replace 'Y' by 'A'
else
word=word.replace(c,'B');
}
System.out.print(word+" "); //Printing the encrypted word
}
System.out.println(".");
}
else //For even rows
{
for(j=a.length-1;j>=0;j--)
{
System.out.print(a[j]+" ");
}
System.out.println(".");
}
}
}
}
}

Output:
1) Enter the number of sentences
4
P a g e | 98

Enter the sentences


IT IS CLOUDY.
IT MAY RAIN.
THE WEATHER IS FINE.
IT IS COOL.
KV KU ENQWFA .
RAIN MAY IT .
VJG YICVJIT KU HKPG .
COOL IS IT .

2) Enter the number of sentences


13
INVALID ENTRY

Question 21
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.
Test your program for the given sample data and some random data.
Example 1:
INPUT: Enter your date of birth in dd mm yyyy format.
05
01
2010
OUTPUT: VALID DATE
P a g e | 99

5
Example 2:
INPUT: Enter your date of birth in dd mm yyyy format.
03
04
2010
OUTPUT: VALID DATE
93
Example 3:
INPUT: Enter your date of birth in dd mm yyyy format.
34
06
2010
OUTPUT: INVALID DATE
ALGORITHM:
1) Accept the date of birth.
2) Store the total number of days in each month in an array.
3) If the inputted date is less than or equal to the date stored in the
array at position (inputted month-1), it is valid date.
4) If it is valid date, find sum of days from array till position (inputted
month-2) and add it to the inputted date. This is the day number.

Source code:
import java.util.*;
class BirthDate
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter date of birth in dd mm yyyy format");
int dd=sc.nextInt(); //Date
P a g e | 100

int mm=sc.nextInt(); //Month


int yyyy=sc.nextInt(); //Year
int m[]={31,28,31,30,31,30,31,31,30,31,30,31}; /*Array storing total number
of days in each month*/
int sum=0,i;
if(yyyy%4==0) //For leap year, february should have 29 days
m[1]=29;
if(dd<=m[mm-1]) //Checking validity of date
{
System.out.println("VALID DATE");
for(i=0;i<mm-1;i++)
{
sum+=m[i];
}
System.out.println(sum+dd); //Number of days from 1st january
}
else
System.out.println("INVALID DATE");
}
}
Output:
1) Enter date of birth in dd mm yyyy format
05
01
2010
VALID DATE
5
2) Enter date of birth in dd mm yyyy format
03
04
2010
P a g e | 101

VALID DATE
93
3) Enter date of birth in dd mm yyyy format
34
06
2010
INVALID DATE
4) Enter date of birth in dd mm yyyy format
14
09
1997
VALID DATE
257
Question 22
A Prime-palindrome integer is a positive integer(without leading zeroes),
which is prime as well as 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:
Example 1: INPUT: m=100 and n=1000
OUTPUT: THE PRIME PALINDROME INTEGERS ARE:
101,131,181,191,313,353,373,383,727,757,787,797,919,929
FREQUENCY OF PRIME PALINDROME INTEGERS: 15
Example 2: INPUT: m=100 and n=5000
OUTPUT: OUT OF RANGE
ALGORITHM:
1) Accept the limit.
2) Take each number between the given limit one by one and check
whether it is prime or not.
P a g e | 102

3) Only if the number is prime, reverse the number.


4) If the reversed number is equal to the original number, print the
number and increment the count variable.
5) Print the number of prime palindrome integers also.

Source code:
import java.util.*;
class PrimePalindrome
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range");
int m=sc.nextInt();
int n=sc.nextInt();
int i,j,f,d,rev,num,c=0;
if(m<3000&&n<3000)
{
System.out.println("THE PRIME PALINDROME INTEGERS ARE:");
for(i=m;i<=n;i++)
{
f=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
f++; //Finding the number of factors
}
if(f==2) //If it is prime number
{
num=i;
rev=0;
while(num!=0) //Reversing the digits in the number
{
d=num%10;
P a g e | 103

rev=rev*10+d;
num/=10;
}
if(i==rev) //Checking if reversed number is equal to original number
{
System.out.print(i+",");
c++; //Counting the prime palindrome numbers
}
}
}
System.out.println();
System.out.println("FREQUENCY OF PRIME PALINDROME INTEGERS:"+c);
}
else
System.out.println("OUT OF RANGE");
}
}

Output:
1) Enter the range
100
1000
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

2) Enter the range


100
5000
OUT OF RANGE
P a g e | 104

Question 23
Write a program to accept a sentence as input. The words in the string are
to be separated by the blank. Each word must be in upper case. The sentence
is terminated by either “.”, “!” or “?”. Perform the following tasks:
(i) Obtain the length of the sentence (measured in words).
(ii)Arrange the sentence in alphabetical order of words.
Test your program with following data values and also some random data:
Example 1: INPUT: NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT: LENGTH 6
REARRANGED SENTENCE: INVENTION IS MOTHER NECESSITY OF THE.
Example 2: INPUT: BE GOOD TO OTHERS.
OUTPUT: LENGTH 4
REARRANGED SENTENCE: BE GOOD OTHERS TO.

ALGORITHM:
1) Accept a sentence, convert it to upper case.
2) Add the words of the sentence to an array.
3) Count the number of words in the sentence from the array and print it.
4) Sort the array alphabetically and print the sorted array.

Source code:
P a g e | 105

import java.io.*;
class AlphabeticalOrder
{
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the sentence");
String s=br.readLine();
s=s.toUpperCase(); //Converting the sentence to upper case
String str[]=s.split("[ !?.]"); //Adding each word of the sentence into an array
int i,j;
int l=str.length; //Number of words in the sentence
String temp;
System.out.println("LENGTH: "+l);
for(i=0;i<l;i++)
{
for(j=i+1;j<l;j++)
{
if(str[i].compareTo(str[j])>0) //Comparing the words lexicographically
{
//Swapping the words
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
}
for(i=0;i<l;i++)
{
P a g e | 106

System.out.print(str[i]+" "); //Printing the sorted array


}
}
}

Output:
1) Enter the sentence
NECESSITY IS THE MOTHER OF INVENTION.
LENGTH: 6
INVENTION IS MOTHER NECESSITY OF THE

2) Enter the sentence


BE GOOD TO OTHERS.
LENGTH: 4
BE GOOD OTHERS TO

3) Enter the sentence


What is your name?
LENGTH: 4
IS NAME WHAT YOUR

4) Enter the sentence


THE FLOWERS ARE VERY BEAUTIFUL!
LENGTH: 5
ARE BEAUTIFUL FLOWERS THE VERY
P a g e | 107

Question 24
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:
a) Display the input matrix.
b) Find the maximum and minimum value in the matrix and display them along
with their positions.
c) Sort the elements of the matrix in ascending order using any standard
sorting technique and rearrange them in the matrix.
d) Output the rearranged matrix.
Test your program with following data values and also some random data:
Example 1: INPUT: M=3 and N=4
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
P a g e | 108

REARRANGED MATRIX -4 -2 0 1
3 3 4 5
6 7 8 9
Example 2: INPUT: M=3 and N=22
OUTPUT: SIZE OUT OF RANGE

ALGORITHM:
1) Accept the dimension of the array and check if it is in the range.
2) If dimension satisfies the range, create an array of size MxN and
accept the elements.
3) Add the elements of the two dimensional array to a single dimensional
array.
4) Sort the elements of the 1-D array in ascending order using bubble
sort technique.
5) Find the first element of the sorted array and find its position in the
2-D array. This is our smallest element.
6) Find the last element of the sorted array and find its position in the
2-D array. This is our largest element.
7) Print the sorted array in a 2x2 matrix form.

Source code:
import java.util.*;
class Matrix
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the dimensions of the matrix");
int M=sc.nextInt();
int N=sc.nextInt();
P a g e | 109

if(M<=2||M>=20||N<=2||M>=20)
System.out.println("SIZE OUT OF RANGE");
else
{
int A[][]=new int[M][N];
System.out.println("Enter the elements of matrix");
int i,j;
for(i=0;i<M;i++) //Accepting the elements
{
for(j=0;j<N;j++)
{
A[i][j]=sc.nextInt();
}
}
System.out.println("ORIGINAL MATRIX:");
for(i=0;i<M;i++) //Printing original matrix
{
for(j=0;j<N;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
int a[]=new int[M*N];
int k=0,tmp;
for(i=0;i<M;i++) //Converting 2-D array to 1-D array
{
for(j=0;j<N;j++)
{
a[k]=A[i][j];
P a g e | 110

k++;
}
}
for(i=0;i<k;i++) //Sorting the elements using bubble sort
{
for(j=0;j<k-1-i;j++)
{
if(a[j]>a[j+1])
{
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
int max=a[k-1], min=a[0];
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
if(A[i][j]==max) //Finding position of largest number in matrix
{
System.out.println("LARGEST NUMBER\t:"+max);
System.out.println("\t\tROW= "+i+"\n\t\tCOLUMN= "+j);
}
if(A[i][j]==min) //Finding position of smallest number in matrix
{
System.out.println("SMALLEST NUMBER\t:"+min);
System.out.println("\t\tROW= "+i+"\n\t\tCOLUMN= "+j);
}
P a g e | 111

}
}
System.out.println("REARRANGED MATRIX");
k=0;
for(i=0;i<M;i++) //Displaying sorted matrix
{
for(j=0;j<N;j++)
{
System.out.print(a[k]+"\t");
k++;
}
System.out.println();
}
}
}
}

Output:
1) Enter the dimensions of the matrix
3
4
Enter the elements of matrix
8
7
9
3
-2
0
4
5
P a g e | 112

1
3
6
-4
ORIGINAL MATRIX:
8 7 9 3
-2 0 4 5
1 3 6 -4
LARGEST NUMBER :9
ROW= 0
COLUMN= 2
SMALLEST NUMBER :-4
ROW= 2
COLUMN= 3
REARRANGED MATRIX
-4 -2 0 1
3 3 4 5
6 7 8 9

2) Enter the dimensions of the matrix


2
22
SIZE OUT OF RANGE
P a g e | 113

Question 25
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) 0201103311 = 10*0 + 9*2 + 8*0 + 7*1 + 6*1 + 5*0 + 4*3 + 3*3 + 2*1 +
1*1 = 55
Since 55 leaves no remainder when divisible by 11, hence it is a valid
ISBN.
2) 007462542X = 10*0 + 9*0 + 8*7 + 7*4 + 6*6 + 5*2 + 4*5 + 3*4 + 2*2 +
1*10 = 176
Since 176 leaves no remainder when divisible by 11, hence it is a valid
ISBN.
3) 0112112425 = 10*0 + 9*1 + 8*1 + 7*2 + 6*1 + 5*1 + 4*2 + 3*4 + 2*2 +
1*5 = 71
Since 71 leaves a remainder when divisible by 11, hence it is not a valid
ISBN.
P a g e | 114

Design a program to accept a ten digit code from the user. For an invalid
input, display an appropriate message. Verify the code for its validity in the
format specified below:
Test your program with sample data and some random data.
Example 1
INPUT CODE : 0201530821
OUTPUT : SUM = 99
LEAVES NO REMAINDER – VALID ISBN CODE
Example 2
INPUT CODE : 035680324
OUTPUT : INVALID INPUT
Example 3
INPUT CODE : 0231428031
OUTPUT : SUM = 122
LEAVES REMAINDER – INVALID ISBN CODE
ALGORITHM:
1) Accept the code and store it in a string variable.
2) Convert the string to integer type.
3) Check whether e last digit of the code is ‘X’ or some integer.
4) Find the sum of first nine digits.
5) If last digit is ‘X’, add 10 to the sum or if it is some integer, add that
integer to the sum.
6) If the sum divided by 11 leaves no remainder, it is a valid ISBN code
else it is invalid.
Source code:
import java.io.*;
class ISBN
{
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
P a g e | 115

BufferedReader br=new BufferedReader(isr);


System.out.println("Enter the code");
String I=br.readLine();
int d,sum=0,i,prod,is;
char ch;
if(I.length()==10) //Finding the length of ISBN
{
is=Integer.parseInt(I);
for(i=1;i<9;i++) //Finding sum of digits of code upto second last digit
{
d=is%10;
prod=d*i;
sum+=prod;
is=is/10;
}
if(I.charAt(9)=='X') //If last digit is X, it is equivalent to 10
sum+=10; //Adding 10 to sum i.e., value of 'X’
else
{
d=I.charAt(9);
sum+=d; //Adding the last number to sum
}
System.out.println("SUM = "+sum);
if(sum%11==0)
System.out.println("LEAVES NO REMAINDER-VALID ISBN CODE");
else
System.out.println("LEAVES REMAINDER-INVALID ISBN CODE");
}
else
System.out.println("INVALID INPUT");
P a g e | 116

}
}

Output:
1) Enter the code
0201530821
SUM = 99
LEAVES NO REMAINDER-VALID ISBN CODE

2) Enter the code


035680324
INVALID INPUT

3) Enter the code


0231428031
SUM = 122
LEAVES REMAINDER-INVALID ISBN CODE
P a g e | 117

Question 26
Write a program to declare a square matrix A[ ][ ] of order (MxM) 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:
a) Display the input matrix.
b) Create a mirror image matrix.
c) Display the mirror image matrix.
Test your program with the sample 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 4
Example 1: INPUT: M=22
OUTPUT: SIZE OUT OF RANGE
ALGORITHM:
1) Accept a size M and check if it satisfies the condition.
2) If true, create a square matrix of size M and accept the elements.
3) Print the original matrix.
4) Print the mirror image matrix, which is actually the original matrix
with the elements of each row displayed in the opposite order.
P a g e | 118

Source code:
import java.util.*;
class MirrorImage
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the dimension of the array");
int M=sc.nextInt();
if(M<=2||M>=20)
System.out.println("SIZE OUT OF RANGE");
else
{
int A[][]=new int[M][M]; //Square matrix of size M
int i,j;
System.out.println("Enter the elements");
for(i=0;i<M;i++) //Accepting the elements
{
for(j=0;j<M;j++)
{
A[i][j]=sc.nextInt();
} }
System.out.println("ORIGINAL MATRIX:");
for(i=0;i<M;i++) //Printing original matrix
{
for(j=0;j<M;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
P a g e | 119

}
System.out.println("MIRROR IMAGE MATRIX:"); //Printing mirror image
matrix
for(i=0;i<M;i++)
{
for(j=M-1;j>=0;j--)
{
System.out.print(A[i][j]+"\t"); //Elements in each row in reversed order
}
System.out.println();
} }
}
}
Output:
Enter the dimension of the array
3
Enter the elements
4
16
12
8
2
14
4
1
3
ORIGINAL MATRIX:
4 16 12
8 2 14
4 1 3
P a g e | 120

MIRROR IMAGE MATRIX:


12 16 4
14 2 8
3 1 4
Enter the dimension of the array
22
SIZE OUT OF RANGE
Enter the dimension of the array
3
Enter the elements
1
0
0
0
1
0
0
0
1
ORIGINAL MATRIX:
1 0 0
0 1 0
0 0 1
MIRROR IMAGE MATRIX:
0 0 1
0 1 0
1 0 0

Question 27
P a g e | 121

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:
(a) Display the count of palindromic words in the sentence.
(b)Display the palindromic words in the sentence.
Example of palindromic words:
MADAM, ARORA, NOON
Test your program with the sample data and some random data:
Example 1
INPUT : MOM AND DAD ARE COMING AT NOON.
OUTPUT : MOM DAD NOON
NUMBER OF PALINDROMIC WORDS : 3
Example 2
INPUT : NITIN ARORA USES LIRIL SOAP.
OUTPUT : NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS : 3
Example 3
INPUT : HOW ARE YOU?
OUTPUT : NO PALINDROMIC WORDS

ALGORITHM:
1) Accept a sentence and split into words by using StringTokenizer class.
2) Reverse each word and compare the reversed word with the original
word.
3) If the original word and the reversed word are the same, then print
the word and increment the count variable.
4) Print the number of palindromic words.

Source code:
import java.util.*;
class Palindrome
P a g e | 122

{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
s=s.toUpperCase();
StringTokenizer st=new StringTokenizer(s);
String str="",pal="";
char ch;
int i,c=0;
System.out.println(“OUTPUT:”);
while(st.hasMoreTokens())
{
str=st.nextToken(); //Taking word by word
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
pal=ch+pal; //Reversed word stored in pal
}
if(pal.equalsIgnoreCase(str)) //Checking if pal and the original word are equal
{
System.out.print(str+" ");
c++; //Counting the number of palindromic words
}
pal="";
}
System.out.println();
if(c==0)
System.out.println("NO PALINDROMIC WORDS");
P a g e | 123

else
System.out.println("NUMBER OF PALINDROMIC WORDS:"+c);
}
}
Output:
1) Enter a sentence
MOM AND DAD ARE COMING AT NOON
OUTPUT:
MOM DAD NOON
NUMBER OF PALINDROMIC WORDS:3

2) Enter a sentence
NITIN ARORA USES LIRIL SOAP
OUTPUT:
NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS:3

3) Enter a sentence
HOW ARE YOU?
OUTPUT:
NO PALINDROMIC WORDS

Question 28
A Composite Magic Number is a positive integer which is composite as well as
magic.
Composite Number:
P a g e | 124

A composite number is a number that has more than two factors.


Example: 10 Factors are: 1, 2, 5, 10.

Magic Number:
A magic number is a number in which the eventual sum of the digits is equal
to one.
Example: 28= 2 + 8 = 10 = 1 + 0 = 1
Accept two positive integers m and n, where m is less than n as user input.
Display the number of Composite Magic Integers that are in the range
between m and n (both inclusive) and output them along with the frequency,
in the format specified below.
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 INTEGRS 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 INTEGRS IS: 9
Example 3: INPUT: m=120 n=99
OUTPUT: INVALID INPUT.
ALGORITHM:
1) Accept a limit and check if the lower limit is less than upper limit.
2) Take the numbers from m to n in a loop.
3) Find the number of factors of each number. If it is two(including the
number itself), then the number is prime.
4) If the number is prime, check if it is magic number or not. If the
number obtained on successive addition is 1, it is magic number.
5) Display the composite magic number and find the frequency of
composite magic numbers.

Source code:
P a g e | 125

import java.util.*;
class CompositeMagic
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range");
int m=sc.nextInt(); //Inputting range
int n=sc.nextInt();
int i,j,count,c=0,num,d,sum=0;
if(m<n) //Checking whether m is less than n
{
System.out.println("THE COMPOSITE MAGIC INTEGERS ARE:");
for(i=m;i<=n;i++)
{
count=0;
for(j=2;j<i;j++)
{
if(i%j==0)
count++; //Counting the number of factors of the number
}
if(count>0) //If the number has more than one factors, it is prime
{
num=i;
sum=0;
while(num!=0) //Loop for finding sum of the number
{
d=num%10;
sum+=d;
num/=10;
P a g e | 126

if(num==0&&sum>9) /*If the sum has more than one digit sum is used as the number
for next iteration*/
{
num=sum;
sum=0;
}
}
if(sum==1) //if it is a magic number also
{
System.out.print(i+",");
c++; //Counting number of composite magic numbers
}
}
}
System.out.println();
System.out.println("FREQUENCY OF COMPOSITE MAGIC NUMBERS
IS:"+c);
}
else //If m is greater than n
System.out.println("INVALID INPUT");
}
}

Output:
1) Enter the range
10
100
THE COMPOSITE MAGIC INTEGERS ARE:
10,28,46,55,64,82,91,100,
P a g e | 127

FREQUENCY OF COMPOSITE MAGIC NUMBERS IS:8


2) Enter the range
1200
1300
THE COMPOSITE MAGIC INTEGERS ARE:
1207, 1216,1225,1234,1243,1252,1261,1270,1288,
FREQUENCY OF COMPOSITE MAGIC NUMBERS IS:9
3) Enter the range
120
99
INVALID INPUT

Question 29
Write a program to declare a square matrix A[ ] [ ] of order MxM where ‘M’
is the number of rows and columns, such that M must be greater than 2 and
less than 10. Accept the value of M as user input. Display an appropriate
message for an invalid input. Allow the user to input integers into this
matrix.
Perform the following tasks:
P a g e | 128

a) Display the original matrix.


b) Check if the given matrix is symmetric or not.
A square matrix is said to be Symmetric if the element of the ‘i’th row
and ‘j’th column is equal to element of ‘j’th row and ‘I’th column.
c) Find the sum of the elements of left diagonal and sum of elements of
right diagonal of matrix and display them.
Example 1: INPUT: M=3
1 2 3
2 4 5
3 5 6
OUTPUT: ORIGIANL MATRIX:
1 2 3
2 4 5
3 5 6
GIVEN MATRIX IS SYMMETRIC.
SUM OF LEFT DIAGONAL: 11
SUM OF RIGHT DIAGONAL:10
Example 1: INPUT: M=4
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
OUTPUT: ORIGIANL MATRIX:
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
GIVEN MATRIX IS NOT SYMMETRIC.
SUM OF LEFT DIAGONAL: 17
SUM OF RIGHT DIAGONAL:20
Example 1: INPUT: M=22
P a g e | 129

OUTPUT: SIZE OUT OF RANGE.


ALGORITHM:
1) Accept the dimension of the matrix and check if it is greater than 2
and less than 10.
2) Create a square matrix of size ‘M’ and accept the elements into it.
3) Display the original matrix.
4) Check if the element at ‘i’th row and ‘j’th column and the element at
‘j’th row and ‘i’th column are equal.
5) If so, display that the matrix is symmetric. Else it is unsymmetric.
6) Find the sum of left and right diagonal and display it.
Source code:
import java.util.*;
class SymmetricMatrix
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the dimensions");
int M=sc.nextInt(); //Dimension of the matrix
int i,j,count=0,sum=0;
if(M>2&&M<10) //Checking the condition
{
int A[][]=new int[M][M];
System.out.println("Enter the elements");
for(i=0;i<M;i++)
{
for(j=0;j<M;j++)
{
A[i][j]=sc.nextInt(); //Inputting the numbers in the array
}
}
P a g e | 130

System.out.println("ORIGINAL MATRIX");
for(i=0;i<M;i++)
{
for(j=0;j<M;j++)
{
System.out.print(A[i][j]+"\t"); //Printing the original matrix
}
System.out.println();
}
for(i=0;i<M;i++)
{
for(j=0;j<M;j++)
{
if(A[j][i]==A[i][j]) //Checking if matrix is symmetric
count++; //Counting the number of elements which satisfy the symmetric condition
}
}
if(count==M*M) //If all the elements satisfy symmetric condition
System.out.println("GIVEN MATRIX IS SYMMETRIC");
else
System.out.println("GIVEN MATRIX IS NOT SYMMETRIC ");
for(j=0,i=0;j<M;j++,i++)
{
sum+=A[j][i]; //Sum of left diagonal
}
System.out.println("SUM OF LEFT DIAGONAL:"+sum);
sum=0;
for(j=0,i=M-1;j<M;j++,i--)
{
sum+=A[j][i]; //Sum of left diagonal
P a g e | 131

}
System.out.println("SUM OF RIGHT DIAGONAL:"+sum);
}
else
System.out.println("SIZE OUT OF RANGE");
}
}
Output:
1) Enter the dimensions
3
Enter the elements
1
2
3
2
4
5
3
5
6
ORIGINAL MATRIX
1 2 3
2 4 5
3 5 6
GIVEN MATRIX IS SYMMETRIC
SUM OF LEFT DIAGONAL:11
SUM OF RIGHT DIAGONAL:10

2) Enter the dimensions


4
P a g e | 132

Enter the elements


7
8
9
2
4
5
6
3
8
5
3
1
7
6
4
2

ORIGINAL MATRIX
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
GIVEN MATRIX IS NOT SYMMETRIC
SUM OF LEFT DIAGONAL:17
SUM OF RIGHT DIAGONAL:20

3) Enter the dimensions


22
SIZE OUT OF RANGE
P a g e | 133

Question 30
Write a program to accept a sentence which may be terminated by either ‘?’
or ’.’ 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:
a) Accept the sentence and reduce all the extra blank space between two
words to a single blank space.
b) Accept a word from the user which is a 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:
P a g e | 134

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
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
AS YOU SOW, SO YOU REAP.
Example 3: INPUT: STUDY WELL##
OUTPUT: INVALID INPUT

ALGORITHM:
1) Accept a sentence and also the word to be deleted and also its
position in the sentence.
2) Add the words of the sentence to an array and replace the word at
the inputted sentence by an empty literal.
3) Print the remaining words in the array with only one space.

Source code:
import java.util.*;

class Delete

public static void main(String args[])

Scanner sc=new Scanner(System.in);


P a g e | 135

System.out.println("Enter a sentence");

String s=sc.nextLine();

s=s.toUpperCase(); //Converting the string to upper case

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

String word=sc.next(); //Accepting the word to be deleted

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

int pos=sc.nextInt(); //Accepting the position of the word to be deleted

int tok,i;

String a[]=s.split("[ .]+");

a[pos-1]="";

//Loop to print the words with a single blank space and without the word to be deleted

for(i=0;i<a.length;i++)

if(i!=(pos-1))

System.out.print(a[i]+" "); //Printing the word except the word at inputted position

Output:
1) Enter a sentence
A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
P a g e | 136

WORD TO BE DELETED:IS
WORD POSITION IN SENTENCE:6
A MORNING WALK IS A BLESSING FOR THE WHOLE DAY

2) Enter a sentence
AS YOU SOW, SO SO YOU REAP.
WORD TO BE DELETED:SO
WORD POSITION IN SENTENCE:4
AS YOU SOW, SO YOU REAP

Question 31
Write a program in java to input 10 different words and display the longest
word and the length of the word.

Sample Input: Computer


School
Delhi
Education
…………..
…………..
Sample Output: The longest word: ………………….
The length of the word: ………………..
P a g e | 137

ALGORITHM:
1) Accept ten words and store them in an array.
2) Consider the first element as the largest word and compare its length
with that of the other elements.
3) If there appears any element in the array longer than the first word,
then that word is considered as the longest word and the same
procedure is followed.
4) The largest word is printed along with its length.

Source code:
import java.util.*;
class LongestWord
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i,l,large,pos;
String a[]=new String[10];
System.out.println("Enter 10 different words");
for(i=0;i<10;i++)
{
a[i]=sc.next(); //Accepting the words into an array
}
large=a[0].length(); //Consider the first element as the longest word
pos=0;
for(i=0;i<10;i++)
{
l=a[i].length();
if(l>large) //Checking with other elements
{
large=l; //Finding the largest element
P a g e | 138

pos=i;
}
}
System.out.println("OUTPUT:”);
System.out.println("The longest word:"+a[pos]);
System.out.println("The length of the word:"+large);
}
}
Output:
1) Enter 10 different words
Computer
Science
Is
My
Favourite
Subject
Because
It
Is
Easy
OUTPUT:
The longest word: Favourite
The length of the word:9

2) Enter 10 different words


Java
Programming
Language
BlueJ
Environment
P a g e | 139

Inheritence
Abstraction
Polymorphism
Encapsulation
Class
The longest word: Encapsulation
The length of the word:13
P a g e | 140

Question 32
Write a program in java to input a string in mixed case and find the
frequency of each vowel.

Sample Input : Delhi Public School


Sample Output: The frequency of ‘a’ or ’A’: 0
The frequency of ‘e’ or ’E’: 2
The frequency of ‘i’ or ’I’: 2
The frequency of ‘o’ or ’O’: 2
The frequency of ‘u’ or ’U’: 1
ALGORITHM:
1) Accept a string and convert it into upper case.
2)Create two arrays: one to store the vowels and the other to count the
number of occurrence of a vowel at the corresponding position.
3)Print the vowels and their number of occurrence from the count array.

Source code:
import java.io.*;
class VowelFrequency
{
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter a sentence");
String s=br.readLine();
s=s.toUpperCase();
int i,j;
char ch;
int count[]={0,0,0,0,0}; //Array to hold the frequency of each vowel
P a g e | 141

char a[]={'A','E','I','O','U'}; //Array to hold the vowels


for(i=0;i<s.length();i++)
{
ch=s.charAt(i);
for(j=0;j<5;j++)
{
if(ch==a[j]) //If the character is a vowel
{
count[j]++; //Increment the number at the corresponding position in the count array
}
}
}
System.out.println("The frequeny of 'a' or 'A':"+count[0]);
System.out.println("The frequeny of 'e' or 'E':"+count[1]);
System.out.println("The frequeny of 'i' or 'I':"+count[2]);
System.out.println("The frequeny of 'o' or 'O':"+count[3]);
System.out.println("The frequeny of 'u' or 'U':"+count[4]);
}
}

Output:
Enter a sentence
The Delhi Public School.
The frequeny of 'e' or 'E':2
The frequeny of 'i' or 'I':2
The frequeny of 'o' or 'O':2
The frequeny of 'u' or 'U':1
P a g e | 142

Question 33
Write a program in java to accept a word and count the number of
characters, which differ to make the word palindrome.
Sample Input : DILIP
Reversed word : PILID
Sample Output: Number of characters which differ to make
palindrome word=2
ALGORITHM:
1) Accept a word and convert it to upper case.
2) Reverse the word and find the number of characters which are
different in the original word and the reversed word.
3) Display the reversed word and the number of words that differ to
make it palindrome.

Source code:
import java.util.*;
class ReversePalin
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the word");
String s=sc.next();
s=s.toUpperCase(); //Converting word to upper case
char ch,c;
String str="";
int l=s.length(),i,count=0;
for(i=0;i<l;i++)
{
P a g e | 143

ch=s.charAt(i);
str=ch+str; //Reversing the word
}
s=s.trim();
str=str.trim();
System.out.println("Reversed word:"+str);
for(i=0;i<l;i++)
{
ch=s.charAt(i);
c=str.charAt(i);
if(c!=ch) //Counting the number of words which differ to make it a palindrome
count++;
}
System.out.println("No.of characters which differ to make Palindrome
word:"+count);
}
}
Output:
1) Enter the word
DILIP
Reversed word:PILID
No.of characters which differ to make Palindrome word:2

2) Enter the word


SUMI
Reversed word:IMUS
No.of characters which differ to make Palindrome word:4
P a g e | 144

Question 34
Write a program in java to accept a name containing three words and write
the name in short form with the initial.
Sample Input : MAHINDRA SINGH DHONI
Sample Output: M. S. DHONI
ALGORITHM:
1) Accept the full name and split it into different parts using
StringTokenizer function.
2) Display the first character of each part except the last part.
3) Display the last part as it is.

Source code:
import java.util.*;
class Initials
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name");
String name=sc.nextLine();
name=name.toUpperCase(); //Converting name to upper case
int token,i;
String initials="",s;
char init;
StringTokenizer st=new StringTokenizer(name);
token=st.countTokens();
for(i=1;i<=token;i++)
{
s=st.nextToken(); //Taking each part of the name one by one
if(i!=token)
P a g e | 145

{
init=s.charAt(0); //The first character is displayed
initials+=init+".";
}
if(i==token) //The last part of the name
{
initials+=s;
}
}
System.out.println(initials);
}
}
Output:
1) Enter the name
Mahindra Singh Dhoni.
M.S.DHONI.

2) Enter the name


SAURAV GANGULY.
S.GANGULY.

Question 35
P a g e | 146

Write a program in java to input two strings. Display the words, whose
frequency is more than one in the String.
Sample Input:
MAHINDRA SINGH DHONI IS THE CAPTAIN OF INDIAN CRICKET TEAM.
SAURAV GANGULY IS THE EX-CAPTAIN OF THE INDIAN CRICKET TEAM.
Sample Output: THE
OF
INDIAN
CRICKET
TEAM
IS
ALGORITHM:
1) Accept a sentence and convert to upper case.
2)Count the number of words which are in common for both the
sentences and display them.
Source code:
import java.util.*;
class Common
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter two strings");
//Accepting two sentences and converting them to upper case
String s1=sc.nextLine();
String s2=sc.nextLine();
s1=s1.toUpperCase();
s2=s2.toUpperCase();
String str1,str2;
int count;
StringTokenizer st1=new StringTokenizer(s1," .");
P a g e | 147

while(st1.hasMoreTokens())
{
count=0;
str1=st1.nextToken(); //Words of the first sentence
StringTokenizer st2=new StringTokenizer(s2," .");
while(st2.hasMoreTokens())
{
str2=st2.nextToken(); //Words of the second sentence
if(str1.equalsIgnoreCase(str2))
count++; //Counting the number of words in common
}
if(count>=1) //If the word occurs in both sentences, print the word
System.out.println(str1);
}
}
}
Output:
Enter two strings
MAHINDRA SINGH DHONI IS THE CAPTAIN OF INDIAN CRICKET TEAM.
SAURAV GANGULY IS THE EX-CAPTAIN OF THE INDIAN CRICKET TEAM
IS
THE
OF
INDIAN
CRICKET
TEAM

Você também pode gostar