Vous êtes sur la page 1sur 106

Computer

Project
“2019 – 20”

EFFORTS BY:
ADITI CHAUDHRY
CLASS:12-‘F’
ROLL NO. : 4
INDEX
Serial Program Names Page Remarks
No. No.
00 Acknowledgement
01 WAP to accept a day number and
year to display the date. Also
accept ‘N’ to display the date
‘N’ days after it.
02 WAP to declare a matrix A[][]
and sort the boundary elements
in ascending order and calculate
their sum.
03 WAP to arrange the words
contained in the sentence
according to the length of the
words in ascending order.
04 WAP to input a date in six digit
number fomat . Test the validity
of the date and print the date
in full form.
05 WAP to accept a paragraph and
arrange the sentences in
alphabetical order of words and
separate the words which begin
with a vowel.
06 WAP to read a coded message and
decode it. It will contain only
alphabets and spaces.
07 WAP to display the intersection
and union of two sets.
08 WAP to determine minimum number
of +1 and *2 operations needed
to transform a into b.
09 WAP to accept n and print an
order n gray code.
10 WAP to input n and print the
natural numbers from 1 to n2 in
the form of a spiral which
should move in anti-clockwise
direction, starting from the
center.
11 WAP to accept an odd integer N
and print out an N-by-N magic
square. The square contains each
of the integers between 1 and
N^2 exactly once.
12 WAP to input the names of people
into two different arrays A and

1
B. Merge A and B into an array
C, such that the resulting array
is stored alphabetically.
13 WAP to input two binary numbers
in String format and perform
Binary addition.
14 WAP to accept a string and two
integers and to replace the
characters of words at the
position of the integers by the
ones after them in circular
fashion of alphabets.
15 WAP to input two valid datesand
calculate the days elapsed
between the two dates.
16 WAP to input two binary
numbers in String format and
perform Binary subtraction.
17 WAP to input two Hexadecimal
numbers in String format and
perform Hexadecimal subtraction.
18 WAP to any infix expression and
evaluate it and find its postfix
expression.
19 WAP to to input an integer of
more than 4 digits. If data is
less than 5 digits,ask to re-
enter. In the input last four
digits will be taken as year and
remaining digits as total
number of days . Display the
output as actual date followed
by month name and year.
20 WAP to input a string and
display the words vertically.
21 WAP to move all the upper case
letter to the right side of the
array without using any standard
sorting technique.
22 WAP to display the intersection
and union of two sets.
23 WAP to accept an integer ‘k’ and
a bit string ‘s’ and print out
all bit strings that have
Hamming distance at most ‘k’
from ‘s’.
24 WAP to get the biggest sum
possible by adding either the
no. below or on the right at
each step in a double

2
dimensional matrix starting from
top left corner.
25 WAP to transforme one matrix
into the other in a sequence of
steps if possible. In each step
any pair of columns can be
exchanged.
26 WAP to convert postfix
expression to infix.
27 WAP to input a string and count
no. of vowels and words in each
sentence.
28 WAP to input ‘n’ integers from
the user and find the longest
sub-sequence of numbers in
ascending order.
29 WAP to Design a program to
accept the amount and display
the break-up in descending order
of denominations along with the
total number of notes. Also
print the amount in words.
30 WAP to accept the size of a
string array 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.
31 WAP to accept N real number of
standard input, and partition
them into two groups so that
their difference is minimized.

3
Acknowledgement
I would like to express my special thanks of gratitude to my teacher
Mr.Rajeev Singh who gave me the golden opportunity to do this
wonderful project, which also helped me know many new things.

I am really thankful to them.

Secondly, I would also like to thank my parents and friends who


helped me a lot in finishing this project within the limited time.

THANKS AGAIN TO ALL WHO HELPED ME.

4
QUESTION 1
import java.util.*;
class Q1
{
public static void main(String args[])throws Exception
{
Scanner ob=new Scanner(System.in);
int n,y,m,mn,newn,dl=0,month[]={31,0,31,30,31,30,31,31,30,31,30,31};
String mon[]= {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November",
"December"};
System.out.print("Enter the number of days"+"\t");
n=ob.nextInt();
System.out.print("Enter the year"+"\t");
y=ob.nextInt();
System.out.println("Enter the number of days for future date between 1 and
100"+"\t");
newn=ob.nextInt();
m=n;
for(int z=0;z<2;z++)
{
if(y%100==0)
{
if(y%4==0&&y%400==0)
month[1]=29;
else
month[1]=28;
}
else
{
if(y%4==0)
month[1]=29;
else
month[1]=28;
}
int s=0,i=0;
while(n>s)
{
s=s+month[i];
i++;

5
}
mn=i;
i--;
s=s-month[i];
dl=n-s;
s=0;
if(z==1)
System.out.print("Date after"+" "+newn+" "+"days"+" "+ dl);
if(dl==1&&dl%10==1)
System.out.print("st"+" ");
else if(dl==2&&dl%10==2||dl==22)
System.out.print("nd"+" ");
else if(dl==3&&dl%10==3||dl==23)
System.out.print("rd"+" ");
else
System.out.print("th"+" ");
for(int p=1;p<=mon.length;p++)
{
if(p==mn)
System.out.print(mon[p-1]);
}
mn=0;
System.out.print(" "+y);
System.out.println();
if(newn>100)
{
System.out.println("Invalid input");
System.exit(0);
}
m=m+newn;
if(y%4==0)
{
month[1]=29;
if(m>366)
{
m=m-366;
y=y+1;
}
}
else
{

6
month[1]=28;
if(m>365)
{
m=m-365;
y=y+1;
}
}
n=m;
}
}

Sample Output:
1) Enter the number of days 233
Enter the year 2008
Enter the number of days for future date between 1 and 100 17
20th August 2008
Date after 17 days 6th September 2008

2) Enter the number of days 360


Enter the year 2008
Enter the number of days for future date between 1 and 100 45
25th December 2008
Date after 45 days 8th Febrary 2009

3) Enter the number of days 360


Enter the year 2099
Enter the number of days for future date between 1 and 100 45
26th December 2099
Date after 45 days 9th Febrary 2100

ALGORITHM
1) Define five variables of int type to store the input date, to store input year , to store
the number of days to be incremented and the last on eto store the output
int n,y,m,newn,s=0,dl=0.
2) Define an array that contains the names of months.
3) Make a funtion that returns leap if the year enterd is leap and not leap otherwise,
change the value of the month of feb accordingly.
4) Count the month using the date input and year by using a for loop
for(int i=0;i<n-1;i++).
5) Display the entered date in DD-MM-YYYY format.

7
6) Now using the day number entered increment the ouput date month and year.
7) To do so use a for loop to count month then using a switch statement store the
month name.
8) Now check whether increasing the number of days does or doesnot lead to a
increase
in the year.
9) Check whether the new year is leap or not and change the number of days in the
month of
feb accordingly.
10) At last display the date along with month name along with the year number.
11) END.
*/

VD Table

S. No. Name of variable Type Description

1.) n, m, y int To store the day,


month and year
respectively.

2.) mon[] int Array to store the


number of days in all
months.

3.) mon [] String Array to store the


name of all months.

4.) z, p int Used in loops.

8
QUESTION 2

import java.util.*;
class Q2
{
public static void main(String args[])throws Exception
{
Scanner ob=new Scanner(System.in);
int a[][],b[],sum=0,c=0,x=0,m,n,y=0;
System.out.println("Enter the rows and columns of array");
m=ob.nextInt();
n=ob.nextInt();
a=new int[m][n];
System.out.println("Enter the elements");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
a[i][j]=ob.nextInt();
}
System.out.println("The Original Matrix is"+" ");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
b=new int[(m*2)+((n-2)*2)];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||i==(m-1)||j==0||j==(n-1))
{
b[y]=a[i][j];
sum=sum+a[i][j];

9
y=y+1;
}
}
}
System.out.println();
for(int i=0;i<b.length;i++)
{
for(int j=0;j<b.length-i-1;j++)
{
if(b[j]>b[j+1])
{
int k=b[j];
b[j]=b[j+1];
b[j+1]=k;
}

}
}
System.out.println();
for(int i=0;i<1;i++)
{
for(int j=0;j<n;j++)
a[i][j]=b[x++];
for(int j=i+1;j<m-1;j++)
a[j][n-i-1]=b[x++];
for(int j=n-1;j>=0;j--)
a[m-i-1][j]=b[x++];
for(int j=m-2;j>0;j--)
a[j][i]=b[x++];
}
System.out.println();
System.out.println("The Rearranged Matrix is"+" ");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
System.out.println();
System.out.println("The Boundary elements are"+" ");
for(int i=0;i<m;i++)

10
{
for(int j=0;j<n;j++)
{
if(i==0||i==(a.length-1)||j==0||j==(a[0].length-1))
System.out.print(a[i][j]+" \t");
else
System.out.print("\t");
}
System.out.println();
}
System.out.println("The sum of the Boundary elements are"+" "+sum);
}
}

/*
Sample Output:
1) Enter the rows and columns of array
3
3
The Original Matrix is
1 7 4
8 2 5
6 3 9
The Rearranged Matrix is
1 3 4
9 2 5
8 7 6
The Boundary elements are
1 3 4
9 5
8 7 6
The sum of the Boundary elements are 43

2) Enter the rows and columns of array


4
3
The Original Matrix is
1 3 5
7 9 8

11
6 3 2
9 10 11
The Rearranged Matrix is
1 2 3
11 9 5
10 3 6
9 8 7
The Boundary elements are
1 2 3
11 5
10 6
9 8 7
The sum of the Boundary elements are 62

3) Enter the rows and columns of array


2
3
The Original Matrix is
7 1 6
8 9 2
The Rearranged Matrix is
1 2 6
9 8 7
The Boundary elements are
1 2 6
9 8 7
The sum of the Boundary elements are 33

ALGORITHM
1) Define variables int a[][],b[],sum=0,c=0,x=0,m,n,y=0 to store the sum , to store
number of rows and number of columns.
2) Declare an int a[][] type dd array and another sd b[] array to repectively store the
input array and the boundary elements.
3) Take input using for loop.
for(int i=0;i<m;i++)
4) Display the input matrix again by using a for loop.
5) Using a for loop nested in another for loop sort and simultaneously store the
boundary elements.
b[y]=a[i][j];//storing boundary elements
sum=sum+a[i][j];//clculating sum of boundary elements
6) Find the sum of boundary elements and store the sum.

12
7) Display the sorted matrix using a for loop for(int i=0;i<m;i++).
8) Finally display the boundary elements only along with the sum
system.out.print("sum").
9) END.
*/
VD Table

S. No. Name of variable Type Description

1.) m, n int To store the number


of rows and columns.
2.) a [][] int To input the array.

3.) b [] int To store the boundary


elements.
4.) i int Used in loops.

5.) sum int To store the sum of


border elements.

13
QUESTION 3
import java.io.*;
class Q3
{
public static void main(String args[])throws Exception
{
BufferedReader ob=new BufferedReader(new
InputStreamReader(System.in));
String str="",w="";
String word[];
int t=0,z,wc=0;
System.out.print("Input:"+" ");
System.out.println("Enter the string");
str=ob.readLine();
if((int)str.charAt(0)>=65&&(int)str.charAt(0)<=91)
str=((char)((int)str.charAt(0)+32))+str.substring(1);
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
if(i==0&&(ch==' '||ch=='.'))
continue;
if(ch==' '||ch=='.')
wc=wc+1;
}
word=new String[wc];
System.out.println(wc);
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
if(i==0)
{
if(ch==' '||ch=='.')
continue;
}
if(ch!=' '&&ch!='.')

14
w=w+ch;
else
{
word[t]=w;
t++;
w="";
}
}
for(int i=0;i<word.length;i++)
{
for(int j=0;j<word.length-1;j++)
{
if(word[j].length()>word[j+1].length())
{
String swap=word[j];
word[j]=word[j+1];
word[j+1]=swap;
}
}
}
for(int i=0;i<wc;i++)
{
if(i==0&&(word[i].charAt(0)>=97&&word[i].charAt(0)<=123))
word[i]=((char)((int)word[i].charAt(0)-32))+word[i].substring(1);
System.out.print(word[i]);
if(i!=wc-1)
System.out.print(" ");
}
System.out.print('.');
}
}
/*
Sample Output:
1) Input: Enter the string
This is a sentence.
4
A is this sentence.

2) Input: Enter the string


Program in java.
3

15
In java program.

ALGORITHM
1) Declare a string variable to store the entered string, an string array to store the
words.
2) Take the input fron the user and store in the str.
3) If first character of the sentence is capital make it small.
4) Using a for loop for(int i=0;i<str.length();i++) and a
if(word[j].length()>word[j+1].length()) condition statement in it to store the words in
the array also store the number of words.
5) Now by using bubble sorting and the ascii value of the first character and the length
of the words if(word[j].length()>word[j+1].length()) to sort the array containig the words.
6) Initialize a for loop for(int i=0;i<wc;i++) and print the words and at last make the first
character capital and end the sentence with a full stop.
7) END.
*/

VD Table
S. No. Name of variable Type Description

1.) str String To input the string.

2.) word [] String To store the words in


the string.

3.) i,j int Used in loops.

4.) wc int Number of words in


string.

16
QUESTION 4

import java.util.*;
class Q4
{
public static void main(String args [])throws Exception
{
Scanner ob=new Scanner(System.in);
String a[];
String str="";
int d=0,m=0;
System.out.print("Enter date in six digit format"+"\t");
str=ob.nextLine();
a=new String [3];
a[0]=str.substring(0,2);
a[1]=str.substring(2,4);
a[2]=str.substring(4,6);
for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);
if(i<2)
d=d*10+(int)ch-48;
if(i>=2&&i<4)
m=m*10+(int)ch-48;
}
if(m==01||m==03||m==05||m==07||m==8||m==10||m==12)
{
if(d>31)
{
System.out.println("Invalid Date");
d=00;
m=00;
}
}
if(m==04||m==06||m==9||m==11)

17
{
if(d>30)
{
System.out.println("Invalid Date");
d=00;
m=00;
}
}
if(m==02)
{
if(d>29)
{
System.out.println("Invalid Date");
d=00;
m=00;
}
}
if(m>12)
{
m=0;
System.out.println("Invalid Date");
}
if(d!=00&&m!=00)
{
System.out.print(d);
if(a[0].equals("01")||a[0].equals("21")||a[0].equals("31"))
System.out.print("st"+" ");
else if(a[0].equals("02")||a[0].equals("22"))
System.out.print("nd"+" ");
else if(a[0].equals("03")||a[0].equals("23"))
System.out.print("rd"+" ");
else
System.out.print("th"+" ");
switch(a[1])
{
case "01":System.out.print("January");
break;
case "02":System.out.print("Febrary");
break;
case "03":System.out.print("March");
break;

18
case "04":System.out.print("April");
break;
case "05":System.out.print("May");
break;
case "06":System.out.print("June");
break;
case "07":System.out.print("July");
break;
case "08":System.out.print("August");
break;
case "09":System.out.print("September");
break;
case "10":System.out.print("October");
break;
case "11":System.out.print("November");
break;
case "12":System.out.print("December");
break;
}
System.out.print(" "+","+a[2]);
System.out.println();
System.out.println("Valid date");
}
}
}
/*

Sample Output:
1) Enter date in six digit format 121212
12th December ,12
Valid date

2) Enter date in six digit format 341070


Invalid Date

3) Enter date in six digit format 080808


8th August ,08
Valid date

19
ALGORITHM
1) Define the variables and initialize them String a[]; To store the day year and month.
String str=""; To takeinput from user. int d=0,m=0; To store final day and month.
2) Check for the validity of the date and display the message.
System.out.println("Invalid Date").
3) Now using a switch statement switch(a[1]) find the month name.
4) Display the date along with month name and year
System.out.print(" "+","+a[2]).
5) At last print if the date was valid
System.out.println("Valid date").
6) END.
*/

VD Table

S. No. Name of variable Type Description

1.) str String To store the date.

2.) a[] String To store the day,


month, and year.
3.) d, m int To store the final
day and month.
4.) i int Used in loop.

20
QUESTION 5

import java.io.*;
class Q5
{
public static void main(String args[])throws IOException
{
String m,vw="",vow="aeiouAEIOU";
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the PARAGRAPH.");
m=br.readLine();
int n=0,k=0,h=0;
for(int i=0;i<m.length();i++)
{
if((m.charAt(i)==',')||(m.charAt(i)=='.')||(m.charAt(i)=='?')
||(m.charAt(i)=='!'))
n++;
}
String ar[]=new String[n];
for(int i=0;i<m.length();i++)
{

if((m.charAt(i)==',')||(m.charAt(i)=='.')||(m.charAt(i)=='?')||(m.charAt(i)=='!'))
{
ar[k]=m.substring(h,i+1);
h=i+2;
k++;
}
}
for(int q=0;q<n;q++)
{
int p=0,r=0,s=0;
for(int i=0;i<ar[q].length();i++)
{

21
if((ar[q].charAt(i)==' ') || (ar[q].charAt(i)==',') ||
(ar[q].charAt(i)=='.') ||(ar[q].charAt(i)=='?')||(ar[q].charAt(i)=='!'))
p++;
}
String arr[]=new String[p];
for(int i=0;i<ar[q].length();i++)
{
if((ar[q].charAt(i)==' ') || (ar[q].charAt(i)==',') ||
(ar[q].charAt(i)=='.') ||(ar[q].charAt(i)=='?')||(ar[q].charAt(i)=='!'))
{
arr[r]=ar[q].substring(s,i);
s=i+1;
r++;
}
}
for(int i=0;i<p;i++)
{
if((vow.indexOf(arr[i].charAt(0))>=0)&&(vw.indexOf(arr[i])<0))
vw=vw+arr[i]+' ';
}
for(int i=0;i<p-1;i++)
{
int index = i;
for (int j=i+1;j<p;j++)
{
if (arr[j].compareTo(arr[index])<0)
index = j;
}
String temp=arr[index];
arr[index]=arr[i];
arr[i]=temp;
}
char v=ar[q].charAt(ar[q].length()-1);
ar[q]="";
for(int i=0;i<p;i++)
{
if(ar[q].indexOf(arr[i])<0)
{
if(i!=p-1)
ar[q]=ar[q]+arr[i]+' ';
else

22
ar[q]=ar[q]+arr[i];
}
if(i==p-1)
{
if(ar[q].charAt(ar[q].length()-1)==' ')
ar[q]=ar[q].substring(0,ar[q].length()-1)+v;
else
ar[q]=ar[q]+v;
}
}
}
System.out.print("Output: ");
for(int i=0;i<n;i++)
System.out.print(ar[i]+' ');
System.out.println();
System.out.println("Vowels: "+vw);
}
}
/*
Sample Output:
1) Enter the PARAGRAPH.
HELLO! HOW ARE YOU? WHEN ARE YOU COMING? HOPE TO SEE YOU SOON.
Output: HELLO! ARE HOW YOU? ARE COMING WHEN YOU? HOPE SEE SOON TO YOU.
Vowels: ARE

2) Enter the PARAGRAPH.


THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.
Output: BROWN DOG FOX JUMPED LAZY OVER QUICK THE.
Vowels: OVER

3) Enter the PARAGRAPH.


Can you define plan as a loose sequence of manifestly inadequate observations and
conjectures, held together by panic, indecision and ignorance? If so, it was a very
good plan.
Output: Can and as conjectures define inadequate loose manifestly observations of
plan sequence you, by held panic together, and ignorance indecision? If so, a
good it plan very was.
Vowels: as of inadequate observations and indecision ignorance If it

ALOGRITHM

23
1) String type variables m,vw and vow are initialised to store the string
entered by user, words starting with vowels, and vowels respectively.
2) Integer type variables n, k and h are initialised to count the no. of sentences,
position of sentences in the String type array ar, which stores the sentences
from the para., and the position of the start of next sentence in the string
respectively.
3) The string is split into sentences which are stored as elements of the array ar
by using th following loop:
for(int i=0;i<m.length();i++)
{ if((m.charAt(i)==',')||(m.charAt(i)=='.')||(m.charAt(i)=='?')||(m.charAt(i)=='!'))
{ ar[k]=m.substring(h,i+1); h=i+2; k++;
} }
4) Integer type variables p, r and s are initialised in for loop for same functions as n,
k and h, but for splitting each sentence from ar into words, which are then stored in
string type array arr.
5) Words in arr are checked whether they are starting from a vowel. If they are, then
they are added to vw.
6) The words of the array arr are sorted by bubble sorting in alphabetical
order by using .compareTo function.
7) The sorted arr array is stored again as a single element in the ar array, thus storing
the sorted sentence in each element.
8) END.
*/

VD Table
S. No. Name of variable Type Description

1.) m String To store the


paragraph.
2.) n int To store the number
of sentences in the
paragraph.
3.) i, q int Used in loops.
4.) arr String To store the words
in the sentences.
5.) vw String To store words
starting with a
vowel.

24
QUESTION 6
import java.io.*;
class Q6
{
public static void main(String args[])throws IOException
{
BufferedReader ob=new BufferedReader(new
InputStreamReader(System.in));
String n="", str="",nstr="",w="";
int r=0;
System.out.println("Enter the encoded message");
n=ob.readLine();
for(int i=n.length()-1;i>=0;i--)
{
char ch=n.charAt(i);
nstr=nstr+ch;
}
for(int i=0;i<nstr.length();i++)
{
char ch=nstr.charAt(i);
int d=(int)ch-48;
r=r*10+d;
if(r>=65&&r<=90||r>=97&&r<=122||r==32)
{
System.out.print((char)r);
r=0;
}
else
continue;
}
}
}
/*

25
Sample Output:
1) Enter the encoded message
2312179862310199501872379231018117927
Have a Nice Day

2) Enter the encoded message


23511011501782351112179911801562340161171141148
Truth Always Wins
ALGORITHM
1) Declare variables
String n(to take input)
String str(to store the decoded message)
String nstr(to use temporarly store words and to print them)
2) Take input from the user.
3) Start a for loop for(int i=n.length()-1;i>=0;i--) and use it to
extact the words in coded form and then to reverse them.
4) Start another loop for(int i=0;i<nstr.length();i++)
and use it to decode the ecoded message.
5) To decode the message first store int ASCII value of the
extacted character and then check the following
if(r>=65&&r<=90||r>=97&&r<=122||r==32)
if true then we have encountered a character.
6) Now print the character and at the end the end the encoded message will
be printed in decoded form.
7) END.
*/

VD Table

S. No Name of variable Type Description

1.) n String To enter the coded


message.

2.) str String To store decoded


message.

26
3.) nstr String To store words
temporarily.

4.) i int Used in loop.

QUESTION 7
Import java.io.*;
import java.util.*;
class Q7
{
int arr[];
int n;
Q7(int nm)
{
n=nm;
arr=new int[n];
}
void input()throws IOException
{
Scanner imp=new Scanner(System.in);
System.out.println("Enter the elements");
for(int i=0;i<n;i++)
{
arr[i]=imp.nextInt();
}
}
void display()
{
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
System.out.println("");
}

27
Q7 intersection(Q7 obj)
{
int size=0;
if(n<obj.n)
size=n;
else
size=obj.n;
Q7 obj1=new Q7(size+100);
size=0;
int tep[]=new int[n];
int tep1[]=new int[obj.n];
for(int i=0;i<n;i++)
tep[i]=arr[i];
for(int i=0;i<obj.n;i++)
tep1[i]=obj.arr[i];
for(int i=0;i<n;i++)
{
for(int j=0;j<obj.n;j++)
{
if(tep[i]==tep1[j])
{
obj1.arr[size++]=tep[i];
tep[i]=tep[j]=0;
break;
}
}
}
obj1.n=size;
return obj1;
}
Q7 union(Q7 obj)
{
Q7 obj1=new Q7(n+obj.n);
int size=0;
Arrays.sort(arr);
Arrays.sort(obj.arr);
int a=0,b=0;
try
{
for(int i=0;i<(n+obj.n);i++)
{

28
if(a==n&&b!=obj.n)
{
obj1.arr[size++]=obj.arr[b];
b++;
}
else if(a!=n&&b==obj.n)
{
obj1.arr[size]=arr[a++];
size=size+1;
}
else if(arr[a]==obj.arr[b])
{
obj1.arr[size++]=arr[a++];
b++;
}
else if(arr[a]<obj.arr[b])
obj1.arr[size++]=arr[a++];
else
obj1.arr[size++]=obj.arr[b++];
}
}
catch(Exception e)
{
System.out.println();
}
obj1.n=size;
return obj1;
}
public static void main(String []args)throws IOException
{
Scanner imp=new Scanner(System.in);
System.out.println("Enter the size of first array less than 50");
Q7 obj1=new Q7(imp.nextInt());
obj1.input();
System.out.println("Enter the size of second array less than 50");
Q7 obj2=new Q7(imp.nextInt());
obj2.input();
Q7 obj3=obj1.intersection(obj2);
System.out.println("Intersection of the two arrays is:");
obj3.display();
obj3=obj1.union(obj2);

29
System.out.println("The union is:");
obj3.display();
}
}
/*
Sample Output:
1) Enter the size of first array less than 50
5
Enter the elements
1 4 5 68 9
Enter the size of second array less than 50
6
Enter the elements
1 3 4 88 66 99
Intersection of the two arrays is:
14
The union is:
1 3 4 5 9 66 68 88 99

2) Enter the size of first array less than 50


5
Enter the elements
5
4
3
2
1
Enter the size of second array less than 50
5
Enter the elements
5
6
7
8
9
Intersection of the two arrays is:
5
The union is:
123456789

30
ALGORITHM
1) Declare class variables int size(to store size),int arr[](to store the array elements).
2) Define two function one for intersection and other for union of the sets.
3) Both the functions are static and take class object as parameters. In intersection
function first sort the arrays of calling and passed objects.
4) Define another object of class type to store and to return the final array.
5) Find all the common elements by using the simple procedure of searching one
element in other array, if found then store it in the array of the object just declared.
6) Finally return the object with the intersection of the sets, take the address in
another declared object in the main function and call display.
7) Follow step 3 and 4 for the union function as well.
8) Now using variables and loops fill the union set ensuring that no duplicate element
comes in it.
9) Finally return the union object and follow step 6.
10) Display the reqired result.
11) END.
*/
VD Table

S. No Name of variable Type Description

1.) size int To store the size of


set.
2.) arr [] int To store the
elements of set.
3.) i, a, b int Used in loop.

31
QUESTION 8
import java.io.*;
class Q8
{
int a,b,c;
String q,w;
Q8(int s,int t)
{
a=s;
b=t;
c=t;
q=s+" ";
w="";
}
void cal()
{
while(c!=a)
{
if((c%2==0)&&(c/2>=a))
{
c=c/2;
w="* 2 "+w;
}
else
{
c--;

32
w="+ 1) "+w;
q='('+q;
}
}
}
void display()
{
System.out.println();
System.out.println("Output:");
System.out.println(b+" = "+q+w);
}
public static void main(String atgs[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value of a");
int l=Integer.parseInt(br.readLine());
System.out.println("Enter the value of b");
int m=Integer.parseInt(br.readLine());
if(l<=m)
{
Q8 obj=new Q8(l,m);
obj.cal();
obj.display();
}
else
System.out.println("Wrong Input");
}
}
/*
Sample Output:
1) Enter the value of a
4
Enter the value of b
65

Output:
65 = (4 * 2 * 2 * 2 * 2 + 1)

2) Enter the value of a


9

33
Enter the value of b
901

Output:
901 = (((((((9 + 1) + 1) + 1) + 1) + 1) * 2 * 2 * 2 * 2 + 1) * 2 * 2 + 1)

ALGORITHM
1) Declare variables int a,b,c to store the value passed on to the consructor and to
calculate the reqired sequence.
2) Declare two more String type variables q and w to respectively store the left brackets
and to store *2 and +1 along with right brackets.
3) Define a function named cal which will using if and nested in while will generate the
desired sequence.
4) The logic used is that if the number is odd the subtact one then it will become even
,divide the same by 2.
5) At the last check if any of the step 4 operation lead to a number greater than a ,then
change so as to get a by subtracting 1 in succession.
6) After all this print the result by calling display function
System.out.println(b+" = "+q+w).
7) END.
*/

VD Table

S. No Name of variable Type Description

1.) a, b int To store the values.


2.) q String To store the left
bracket.
3.) w String To store *2 and +1 ,
and right bracket.

34
QUESTION 9
import java.util.*;
import java.io.*;
public class Q9
{
static void yarg(String prefix, int n)
{
if (n == 0) System.out.println(prefix+", ");
else
{
gray(prefix + "1", n - 1);
yarg(prefix + "0", n - 1);
}
}

static void gray(String prefix, int n)


{
if (n == 0) System.out.print (prefix+", ");
else
{
gray(prefix + "0", n - 1);
yarg(prefix + "1", n - 1);
}
}
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

35
System.out.println("Enter the number");
int N = Integer.parseInt(br.readLine());
gray("", N);
}

}
/*
Sample Output:
Enter the number
4
0000, 0001, 0011, 0010, 0110, 0111, 0101, 0100, 1100, 1101, 1111, 1110, 1010, 1011, 1001,
1000
*/

VD Table

S. No Name of variable Type Description

1.) N int To store the


number.
2.) prefix String To store the gray
code.

36
QUESTION 10
import java.io.*;
class Q10
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter n (1<n<12).");
int n=Integer.parseInt(br.readLine());
int k=1,ar[][]=new int[n][n],p,r,c;
if(n%2==0)
{
p=n/2;
r=p;
}
else
{
p=(n+1)/2;
r=p-1;
}
c=p-1;
for(int i=0;i<p;i++)
{
for(int j=0;j<(i+1)*2;j++)
{

37
if(k<=n*n)
ar[r][c++]=k++;
}
c--;
for(int l=0;l<(i*2)+1;l++)
{
if(k<=n*n)
ar[--r][c]=k++;
}
for(int m=0;m<(i+1)*2;m++)
{
if(k<=n*n)
ar[r][--c]=k++;
}
for(int s=0;s<(i*2)+1;s++)
{
if(k<=n*n)
ar[++r][c]=k++;
}
r++;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(ar[i][j]+" ");
System.out.println();
}
}
}
/*
Sample Output:
1) Enter n (1<n<12).
5
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23 24 25

2) Enter n (1<n<12).
7

38
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49

ALGORITHM
1) Integer type variable n is entered by the user as the size of the square matrix.
2) Integer type double dimensional array ar is initialised along with integer type
variables r and c for the row and column no. of next entry. Their initial value is calculated by
using integer type variable p.
3) A steadily increasing integer type variable k from 1 to n^2 is feeded as the element
of the array ar in a anti-clockwise spiral pattern starting from middle by using nested for
loops and periodically incrementing or decrementing the value of position variables r and c.
4) The array ar is printed, thus giving the required output.
5) END.
*/

VD Table

S. No. Name of variable Type Description

1.) n int To store the


number.
2.) ar [][] int To store numbers in
spiral form.
3.) k int Variable whose
value increases from
1 to n^2.
4.) r, c int To store the row
and column number
of next entry.

39
QUESTION 11

import java.util.*;
class Q11
{
int magic[][];
int N;
Q11(int n)
{
N=n;
magic=new int[n][n];
}
void create()
{
int row=N-1;
int col=N/2;
magic[row][col]=1;
for(int i=2;i<=N*N;i++)
{
if(magic[(row+1)%N][(col+1)%N]==0)
{
row=(row+1)%N;
col=(col+1)%N;
}
else

40
row=(row-1+N)%N;
magic[row][col]=i;
}
}
void display()
{
System.out.println("The magic square of order"+" "+N);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
System.out.print(magic[i][j]+"\t");
System.out.println();
}
}
public static void main(String args[])throws Exception
{
Scanner ob=new Scanner(System.in);
System.out.print("Enter order N of Magic Square(odd)"+" "+"="+" ");
int N=ob.nextInt();
if(N%2==0)
{
System.out.println("Wrong Input.N must be odd.Cannot continue");
System.exit(0);
}
Q11 obj=new Q11(N);
obj.create();
obj.display();
}
}
/*
Sample Output:

1) Enter order N of Magic Square(odd) = 3


The magic square of order 3
4 9 2
3 5 7
8 1 6

2) Enter order N of Magic Square(odd) = 5


The magic square of order 5
11 18 25 2 9

41
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15

3) Enter order N of Magic Square(odd) = 7


The magic square of order 7
22 31 40 49 2 11 20
21 23 32 41 43 3 12
13 15 24 33 42 44 4
5 14 16 25 34 36 45
46 6 8 17 26 35 37
38 47 7 9 18 27 29
30 39 48 1 10 19 28

ALGORITHM
1) The size of the array is stored in N.For making a magic square the order/size of the
array must be odd.
2) First step is checking if N is not odd .
3) Number of variables taken is five.
4) magic[][]:is an integer type duble dimensional array. N and n are integer type
variables . row and column are integer type storing the array index of input number.
5) Object of the class is created . Constructor is invoked initializing N to n and array
magic[][].
6) After initialization void create() function is invoked which assigns the integer 1 to
N^2 in ascending order, starting at the bottom middle cell.
row=N-1
col=N/2
magic[row][col]=1
7) Repeatedly assign the next integers to the cell adjacent diagonally to the right and
down.
for(int i=2;i<=N*N;i++)
if(magic[(row+1)%N][(col+1)%N]==0)
{
row=(row+1)%N
col=(col+1)%N
}
magic[row][col]=i
8) If the cell has alredy been assign the another integer, instead use the cell adjacently
above, do not change the column.
if(magic[(row+1)%N][(col+1)%N]!=0)

42
row=(row-1+N)%N
9) When the for() loop terminates magic[][] is completely filled with integer, such that
all row sums, column sums and diagonal sums are equal.
10) Display() function is invoked and the resultant matrix is displayed.
11) END.
*/

QUESTION 12
import java.io.*;
class Q12
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static String a[],b[],c[];
int m,n,p;
Q12(int s,int t)
{
m=s;
n=t;
p=s+t;
a=new String[s];
b=new String[t];
c=new String[p];
}
void enter()throws IOException
{
System.out.println("Enter the names for 1st array.");
for(int i=0;i<m;i++)
{
a[i]=br.readLine();
c[i]=a[i];
}
System.out.println("Enter the names for 2nd array.");
for(int j=0;j<n;j++)

43
{
b[j]=br.readLine();
c[m+j]=b[j];
}
}
void sort(String k[],int v)
{
int g=k.length;
for(int i=0;i<g;i++)
{
String small=k[i];
int p=i;
for(int j=i+1;j<g;j++)
{
if(small.compareTo(k[j])>0)
{
small=k[j];
p=j;
}
}
String temp=k[i];
k[i]=small;
k[p]=temp;
}
if(v==1)
a=k;
else if(v==2)
b=k;
else
c=k;
}
void display(String f[])
{
int g=f.length;
for(int i=0;i<g;i++)
System.out.println(" "+f[i]);
}
public static void main(String atgs[])throws IOException
{
System.out.print("Enter the size of a :");
int l=Integer.parseInt(br.readLine());

44
System.out.println("Enter the size of b :");
int h=Integer.parseInt(br.readLine());
Q12 obj=new Q12(l,h);
obj.enter();
obj.sort(a,1);
obj.sort(b,2);
obj.sort(c,3);
System.out.println();
System.out.println("Sorted Merged array:");
obj.display(c);
System.out.println();
System.out.println("Sorted first array:");
obj.display(a);
System.out.println();
System.out.println("Sorted second array:");
obj.display(b);
}
}

/*
Sample Output:
Enter the size of a :2
Enter the size of b :3
Enter the names for 1st array.
Suman
Anil
Enter the names for 2nd array.
Usha
Sachin
John
Sorted Merged array:
Anil
John
Sachin
Suman
Usha

45
Sorted first array:
Anil
Suman
Sorted second array:
John
Sachin
Usha

ALGORITHM
1) Three String type array a[],b[],c[].
a[] to store names of first array.
b[] to store names of second array.
c[] to store the names of merged a[] and b[] in ascending order.
integer type variables l and h to store the size of a[] and b[]
2) Object obj of the class is created thereby invoking constructor .
3) The constructor initializes
m=l(size of first array)
n=h(size of second array)
p=l+h(size of the merged array)
arrays a[],b[],c[] are initialized by m,n,p;
4) enter() function is invoked.
5) It takes input of names in two arrays.
6) At the same time array c[] is also being filled.
7) sort() function is invoked. This function is invoked 3 times each time passing a String
array with it.
8) The array passed is sorted by bubble sorting technique and the control is return.
9) After all the arrays are sorted, display() function is invoked 3 times, printing the
array.
10) END.
*/

46
QUESTION 13

import java.io.*;
class Q13
{
public static void main(String args[])throws IOException
{
InputStreamReader inp=new InputStreamReader(System.in);
BufferedReader ob=new BufferedReader(inp);
String s1="",s2="",r="",v="01";
int m=0,c=0;
System.out.println("Enter the first Binary number");
s1=ob.readLine();
System.out.println("Enter the second Binary number");
s2=ob.readLine();
while(s1.length()!=s2.length())
{
if(s1.length()>s2.length())
s2='0'+s2;
if(s1.length()<s2.length())
s1='0'+s1;
}
s1='0'+s1;
s2='0'+s2;
for(int i=s1.length()-1;i>=0;i--)

47
{
m=c+v.indexOf(s1.charAt(i))+v.indexOf(s2.charAt(i));
r=v.charAt(m%2)+r;
c=m/2;
}
System.out.println("The result is"+"\t"+r);
}
}
/*
Sample Output:
1) Enter the first Binary number
1111
Enter the second Binary number
1111
The result is 11110

2) Enter the first Binary number


1001
Enter the second Binary number
1101
The result is 10110

ALGORITHM

1) s1, s2, r are String type variables to store the two binary numbers and to store their
their sum.
m and c are integer type variables to store the sum and carry of each digit of the
binary number at each iteration.
2) The while loop executes till the length of both the binary numbers are not equal.
'0' is added at the front to the smaller string.This addition if '0' takes place until both
are of same length.
3) If both the binary numbers are of same length then also '0' is added at the front.
4) for() loop starts from last digit of each binary number.
5) initially m and c equal to zero.v is string storing 0,1.
6) At each itiration the m=c+v.indexOf(s1.charAt(i))+v.indexOf(s2.charAt(i)).{storing the
sum of the indexes of charAt(i)in v.}
The maximum value of m can be 3.
r=v.charAt(m%2)+r [m is divided by 2 and remainder is added to the result.]
c=m/2;[stores the dividend as carry];
7) This process continues till all the complete addition is done.

48
8) At the end resulting string is printed.
9) END.
*/

QUESTION 14
import java.io.*;
class Q14
{
public static void main(String args[])throws IOException
{
String m,ar[];
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the Sentence :");
m=br.readLine();
int n=0,k=0,h=0;
for(int i=0;i<m.length();i++)
{
if((m.charAt(i)==' ')||(m.charAt(i)=='.'))
n++;
}
ar=new String[n];
for(int i=0;i<m.length();i++)
{
if((m.charAt(i)==' ')||m.charAt(i)=='.')
{
ar[k]=m.substring(h,i);
h=i+1;
k++;
}

49
}
System.out.println("Input Integers-");
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
a--;
b--;
for(int i=0;i<ar[a].length();i++)
{
char y=ar[a].charAt(i);
if(y=='Z')
y='A';
else if(y=='z')
y='a';
else
y=(char)(((int)y)+1);
if(i==0)
ar[a]=y+ar[a].substring(1);
else
ar[a]=ar[a].substring(0,i)+y+ar[a].substring(i+1);
}
if(a!=b)
{
for(int i=0;i<ar[b].length();i++)
{
char y=ar[b].charAt(i);
if(y=='Z')
y='A';
else if(y=='z')
y='a';
else
y=(char)(((int)y)+1);
if(i==0)
ar[b]=y+ar[b].substring(1);
else
ar[b]=ar[b].substring(0,i)+y+ar[b].substring(i+1);
}
}
System.out.print("The output is :");
for(int i=0;i<n;i++)
{
if(i==n-1)

50
System.out.print(ar[i]+'.');
else
System.out.print(ar[i]+' ');
}
System.out.println();
}
}
/*
Sample Output:
1) Enter the Sentence :He has good Books.
Input Integers-
2
4
The output is :He ibt good Cpplt.

2) Enter the Sentence :Time and tide waits for none.


Input Integers-
3
3
The output is :Time and ujef waits for none.

ALGORITHM
1) String type variable m and array ar are initialised to store the string as entered by the
user and to store the words in the string.
2) No. of words in the string are calculated by counting no of spaces and fullstops. then
this no is assigned as the size of array ar, in which the words are stored by splitting the
string from one space to another space or fullstop.
3) Position of the desired words, to be encrypted, are entered by the user in integer
type variables a & b.
4) The characters of the word at position a in array ar are changed by the next charcter
in a cyclic order by using the following loop:
for(int i=0;i<ar[a].length();i++)
{
char y=ar[a].charAt(i);
if(y=='Z')
y='A';
else if(y=='z')
y='a';
else
y=(char)(((int)y)+1);

51
if(i==0)
ar[a]=y+ar[a].substring(1);
else
ar[a]=ar[a].substring(0,i)+y+ar[a].substring(i+1);
}
5) Its then checked if b is equal to a. If it is then no other change takes place, if not then
word at position b is encrypted in the same manner as a.
6) Display the modified array ar as output.
7) END.
*/

QUESTION 15
import java.io.*;
class Q15
{
static int d1,m1,y1,d2,m2,y2,a[];
Q15()
{
d1=0;m1=0;y1=0;d2=0;m2=0;y2=0;;
a=new int[]{31,0,31,30,31,30,31,31,30,31,30,31};
}
int leap(int x)
{
if((x%100==0&&x%400!=0)||(x%4!=0))
return 28;
else
return 29;
}
void enter(int k)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter DAY");

52
int b=Integer.parseInt(br.readLine());
System.out.println("Enter MONTH");
int c=Integer.parseInt(br.readLine());
System.out.println("Enter YEAR");
int d=Integer.parseInt(br.readLine());
if(k==1)
{
d1=b;
m1=c;
y1=d;
}
else
{
d2=b;
m2=c;
y2=d;
}
}
void arrange()
{
if((y2<y1)||(y2==y1&&m2<m1)||(y2==y1&&m2==m1&&d2<d1))
{
int t1=d1;
int t2=m1;
int t3=y1;
d1=d2;
m1=m2;
y1=y2;
d2=t1;
m2=t2;
y2=t3;
}
}
int count()
{
int j=0;
for(int i=y1;i<y2;i++)
{
if(leap(i)==28)
j+=365;
else

53
j+=366;
}
for(int i=0;i<m2-1;i++)
j+=a[i];
j+=d2;
for(int i=0;i<(m1-1);i++)
j-=a[i];
j-=d1;
return j;
}
boolean check()
{
a[1]=leap(y1);
if(d1>a[m1-1]||d1<0||d2<0||m1<0||m2<0||y1<0||y2<0||m1>12||m2>12)
return false;
a[1]=leap(y2);
if(d2>a[m2-1])
return false;
return true;
}
public static void main(String args[])throws IOException
{
Q15 obj=new Q15();
obj.enter(1);
obj.enter(2);
if(obj.check())
{
obj.arrange();
int n=obj.count();
System.out.println("OUTPUT: "+n);
}
else
System.out.println("Wrong Input");
}
}
/*
Sample Output:
1) Enter DAY
24
Enter MONTH
09

54
Enter YEAR
1960
Enter DAY
08
Enter MONTH
12
Enter YEAR
1852
OUTPUT: 39371

2) Enter DAY
10
Enter MONTH
01
Enter YEAR
1952
Enter DATE
16
Enter MONTH
10
Enter YEAR
1952
OUTPUT: 280

3) Enter DAY
17
Enter MONTH
12
Enter YEAR
1996
Enter DATE
6
Enter MONTH
01
Enter YEAR
2015
OUTPUT: 6595

55
ALGORITHM
1) Integer type variables d1, m1, y1, d2, m2, y2, and array ar are initialised for storing
days of first date, month no. of first date, year no. of first date,days of second date,
month no. of second date, year no. of second date, and no. of days in each month
respectively.
2) Constructor is called to enter the no. of days in each month in ar and intitial value of
other variables as 0.
3) The fuction enter() is called twice with parameters 1 and 2 to enter the first and
second dates in d1, m1, y1 and d2, m2, y2 as entered by the user.
4) It is checked whether the dates are valid using boolean type function check(). If they
are valid then they are swaped if the first date is smaller than the second by calling
function arrange().
5) Now function count() is called. It calculates the no. of days elapsed between the two
dates by first adding all the days of the years in between the dates including the first year
and checking if the are leap. Then it adds the no. of days of passed months of second
year and the days of the second date and subtract the days of the passed months of first
year and the days of the first date. The result is then returned and is stored in the integer
type variable n in the main class.
6) n is printed thus giving the desired output.
7) END.
*/

56
QUESTION 16
import java.io.*;
class Q16
{
static String a,b,c;
Q16(String x,String y)
{
a=x;
b=y;
c="";
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String m,n;
System.out.println("Enter First binary no.");
m=br.readLine();
System.out.println("Enter Second binary no.");
n=br.readLine();
Q16 obj=new Q16(m,n);
if(b.length()>a.length())
System.out.println("Wrong Input");

57
else
{
int k=b.length();
for(int i=0;i<a.length()-k;i++)
b='0'+b;
if(a.indexOf('0')<b.indexOf('0'))
System.out.println("Wrong Input");
else
{
obj.sub();
obj.disp();
}
}
}
void sub()
{
for(int i=a.length()-1;i>=0;i--)
{
char e=a.charAt(i);
char f=b.charAt(i);
if(e=='1'&&f=='0')
c=c+'1';
else if(e==f)
c=c+'0';
else
{
int t=0;
while(a.charAt(i-t)!='1')
{
a=a.substring(0,i-t)+'1'+a.substring(i-t+1);
t++;
}
a=a.substring(0,i-t)+'0'+a.substring(i-t+1);
c=c+'1';
}
}
String g="";
for(int i=c.length()-1;i>=0;i--)
g=g+c.charAt(i);
c=g;
}

58
void disp()
{
if(c=="")
System.out.println("Wrong Input");
else
{
System.out.println("The Result is");
System.out.println(c);
}
}
}
/*
Sample Output:
1) Enter First binary no.
1101
Enter Second binary no.
1001
The Result is
0100

2) Enter First binary no.


1111
Enter Second binary no.
1111
The Result is
0000

3) Enter First binary no.


1110
Enter Second binary no.
0111
The Result is
0111

ALGORITHM
1) The first and second binary nos. are entered by the user which are then stored in
String type variables a and b by calling the constructor.
2) It is checked whether the second binary no. is greater than the first binary no. by
first checking their lengths and then checking the index of first 0 in them. If then 2nd no.
is found to be greater then wrong output is printed and the program ends.

59
3) Now one by one the characters of both a and b are taken from the back end to the
front into character type variables e and f.
4) If e is equal to f then 0 is added to the stringtype variable c.
5) If e is 1 and f is 0 then 1 is added to c.
6) If e is 0 and f is 1 then 1 is added to c and all the zeroes in a just before and including
this position of e are replaced by 1 and the first 1 before them is replaced by 0. Thus
performing the concept of carry-forward.
7) Now c is reversed to give the result of subtraction.
8) c is printed. Thus giving the desired output.
9) END.
*/

QUESTION 17
import java.io.*;
class Q17
{
int htod(String hexadecimal)
{
int h=hexadecimal.length()-1;int d=0;int n=0;
for(int i=0;i<hexadecimal.length();i++)
{
char ch=hexadecimal.charAt(i);boolean flag=false;
switch(ch)
{
case '1':
n=1;
break;
case '2':
n=2;
break;
case '3':
n=3;
break;
case '4':

60
n=4;
break;
case '5':
n=5;
break;
case '6':
n=6;
break;
case '7':
n=7;
break;
case '8':
n=8;
break;
case '9':
n=9;
break;
case 'A':
n=10;
break;
case 'B':
n=11;
break;
case 'C':
n=12;
break;
case 'D':
n=13;
break;
case 'E':
n=14;
break;
case 'F':
n=15;
break;
default:
flag=true;
}
if(flag)
{
System.out.println("Wrong Entry");

61
break;
}
d=(int)(n*(Math.pow(16,h)))+(int)d;
h--;
}
return d;
}
String dtoh(int t)
{
String str = Integer.toHexString(t);
return str;
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter First Hexadecimal Number");
String a=br.readLine();
System.out.println("Enter Second Hexadecimal Number");
String b=br.readLine();
Q17 obj=new Q17();
int m=obj.htod(a);
int n=obj.htod(b);
if(m>n)
{
int p=m-n;
String q=obj.dtoh(p);
System.out.println("The Result is:");
System.out.println(q.toUpperCase());
}
else
System.out.println("Wrong Input");
}
}
/*
Sample Output:
1) Enter First Hexadecimal Number
AAAA
Enter Second Hexadecimal Number
9999
The Result is:

62
1111

2) Enter First Hexadecimal Number


FFFF
Enter Second Hexadecimal Number
AAAA
The Result is:
5555

3) Enter First Hexadecimal Number


FAFD
Enter Second Hexadecimal Number
1234
The Result is:
E8C9

ALGORITHM
1) User enters the two Hexadecimal nos. in String type variables a and b.
2) Integer type function htod() is called twice with a and b as parameters. htod()
converts a and b from hexadecimal to decimal nos. by adding the value of each character in
the strings with their value in decimal nos. It then returns the decimal value to main class
where it gets stored in integer type variables m and n.
3) if m is smaller than n then wrong input is printed and the program ends.
4) n is subtracted from m and the result is then stored in integer type variable p.
5) String type function dtoh() is called with p as parameter. It converts the value of p
from decimal no. to Hexadecimal string by using Integer.toHexString() statement, and
returns the result to main class where it gets stored in string type variable q.
6) q is printed as the required output.
7) END.
*/

63
QUESTION 18
import java.io.*;
public class Q18
{
public static void main(String args[])throws IOException
{
String n,r="",t="",m="";
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the infix expression: ");
n=br.readLine();
int l=n.length();
for(int i=0;i<l;i++)
{
char x=n.charAt(i);
if(x!='('&&x!=')'&&x!='*'&&x!='/'&&x!='+'&&x!='-')
m=m+x;
}
int a[]=new int[m.length()];
for(int i=0;i<m.length();i++)
{
System.out.print("Enter the value of "+" "+(m.charAt(i))+" ");
a[i]=Integer.parseInt(br.readLine());

64
}
n="("+n+")";
for(int i=0;i<n.length();i++)
{
char x=n.charAt(i);
if(x!='('&&x!=')'&&x!='*'&&x!='/'&&x!='+'&&x!='-')
r=r+x;
if(x=='*'||x=='/'||x=='+'||x=='-')
t=x+t;
if(x==')')
{
r=r+t.charAt(0);
t=t.substring(1);
}
}
System.out.print("The Postfix Operation is: "+r);
int k=0;
for(int i=0;i<r.length();i++)
{
char x=r.charAt(i);
if(x=='*')
a[++k]=a[k-1]*a[k];
else if(x=='/')
a[++k]=a[k-1]/a[k];
else if(x=='+')
a[++k]=a[k-1]+a[k];
else if(x=='-')
a[++k]=a[k-1]-a[k];
}
System.out.println("The Result is "+a[k]);
}
}
/*
Sample Output:
Enter the infix expression: (a+b)/c
Enter the value of a 10
Enter the value of b 5
Enter the value of c 3
The Postfix Operation is: ab+c/
The Result is 5

65
ALGORITHM
1) str stores the infix expression. Parenthesses are added to the front and rear of the
expression. stack[] is initialized of size str.length().
2) ch stores character while extracting. If ch is left paranthesses it will go to the stack.
3) If ch is an operand it will go to the postfix string p.
4) If ch is right paranthesses then pop out all the symbols from the stack and append
these in the postfix string till left paranthesses is encountered.
5) If ch is an operator pop out all the symbols from the top of the stack whose
precedence is more or same as that of the scanned symbol.
6) The current scanned symbol will go to the stack.
7) Print the resultant postfix expression p.
8) The value of the variables is entered by the user in an array a.
9) The operators in the string are now checked and their respective functions are
executed with the elements of array a.
10) The result gets stored in the last element, from where it is printed as the output.
*/

QUESTION 19
import java.io.*;
class Q19
{
static BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
static String str="";
static int n,d,y;
static int m[]={31,0,31,30,31,30,31,31,30,31,30,31};
static String mo[]={"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
public static void main(String args[])throws IOException
{
System.out.print("Enter the data"+"\t"+':');
n=Integer.parseInt(ob.readLine());
str=String.valueOf(n);
if(str.length()>=4)
y=Integer.parseInt(str.substring(str.length()-4));
do
{
if((y<1900)||(y>3000)||(str.length()<6))
{
System.out.print("Wrong Input.Please reenter"+" "+':');
n=Integer.parseInt(ob.readLine());

66
str=String.valueOf(n);
if((str.length())>=4)
y=Integer.parseInt(str.substring(str.length()-4));
else
continue;
}
}
while((y<1900)||(y>3000)||(str.length()<6));
d=Integer.parseInt(str.substring(0,str.length()-4));
if(y%100==0)
{
if(y%4==0&&y%400==0)
m[1]=29;
else
m[1]=28;
}
else
{
if(y%4==0)
m[1]=29;
else
m[1]=28;
}
int sumd=0,mn=0;
while(d>sumd)
{
sumd=m[mn]+sumd;
mn=mn+1;
}
mn=mn-1;
sumd=sumd-m[mn];
d=d-sumd;
System.out.print("Output"+"\t"+':'+d+" "+mo[mn]+" "+y);
}
}
/*
Sample Output
1) Enter the data :272005
Output :27 January 2005

2) Enter the data :3602700

67
Output :26 December 2700

AGORITHM
1) Integer type variable n- to store the long date data.
d- stores the number of days.
y- stores the year number.
mn-stores the month number.
2) m[] and mo[] are arrays storing the number of days in each month and the name of
each month.
3) The year y is checked if its a leap year .
4) The loop while() loop executes till number of days is greater than sumd.
5) At each iteration the the number of days starting from January is added to sumd and
mn is incremented by one.
sumd=m[mn]+sumd; mn=mn+1
6) At last d will store the number of number of days elapsed in mn th month.
7) Finally d(date in the month),mo[mn](the month name)and y(the year) is printed.
8) END.
*/

68
QUESTION 20
import java.io.*;
import java.util.*;
class Q20
{
public static void main(String []args)throws IOException
{
Scanner imp=new Scanner(System.in);
System.out.print("Enter the sentence: ");
String sen=imp.nextLine();
StringTokenizer st=new StringTokenizer(sen);
int row=0;
int now=st.countTokens();
String aa[]=new String[now];
for(int i=0;i<now;i++)
{
int a=0;
if((a=(aa[i]=st.nextToken()).length())>row)
row=a;
}
char asd[][]=new char[row][now];
String temp;
for(int i=0;i<now;i++)

69
{
for(int j=0;j<aa[i].length();j++)
{
asd[j][i]=aa[i].charAt(j);
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<now;j++)
{
if((int)asd[i][j]>33)
System.out.print(asd[i][j]+" ");
else
System.out.print(" ");
}
System.out.println("");
}
}
}

/*
Sample Output:
1) Enter the sentence: This is a program

T i a p
h s r
i o
s g
r
a
m

2) Enter the sentence: Enter the sentence

E t s
n h e
t e n
e t

70
r e
n
c
e

ALGORITHM
1) Define String sen to store the input string.
2) Take the input in the varible sen.
3) Using StringTokenizer break the input into words.
4) Define int now to store the number of words.
5) Define array String aa[]=new String[now] to store the words.
6) In int row store the largest length of the words.
7) Define char asd[][]=new char[row][now] that will store the each character of each
word using for loop
for(int i=0;i<now;i++)
{
for(int j=0;j<aa[i].length();j++)
{
asd[j][i]=aa[i].charAt(j);
}
}
8) Now print the elements of char[][] in matrix form in such a manner that the palces
that have no characters are filled with spaces.
9) END.
*/

71
QUESTION 21
import java.io.*;
class Q21
{
char s[];
int size;
Q21()
{
size=0;
s=new char[0];
}
Q21(char c[])
{
s=c;
size=c.length;
}
void displayarray()
{
for(int i=0;i<size;i++)
System.out.print(s[i]+' ');
}
void move()
{

72
char t;
for(int i=0;i<size;i++)
{
if(Character.isUpperCase(s[i]))
{
for(int j=size-1;Character.isUpperCase(s[j]);j--)
{
if(j<i)
break;
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the size.");
int q=Integer.parseInt(br.readLine());
char p[]=new char[q];
System.out.println("Enter the characters.");
for(int i=0;i<q;i++)
p[i]=(char)br.read();
Q21 obj=new Q21(p);
obj.displayarray();
obj.move();
System.out.print("Output : ");
obj.displayarray();
}
}
/*
Sample Output:
1) Enter the size.
7
Enter the characters.
t
D
f

73
s
X
v
d
t D f s X v d
Output : t d f s v X D

2) Enter the size.


7
Enter the characters.
u
E
g
t
Y
x
e
u E g t Y x e
Output : u e g t x Y E

ALGORITHM
1) Integer type variable size and character type array s are initialised.
2) Integer type variable q is initialised in main method with value entered
by the user.
3) Character type array p is initialised in main method with q as size.
4) char type elements for array p are entered by the user.
5) Object is made and thus constructor is called with p as parameter.
6) Array s is assigned the elements of p and size is assigned the value of q.
7) Initial elements of array s are displayed by calling the function
displayarray().
8) Function move() is called which moves all the upper case letters to the
right side of the array without using any standard sorting technique.
9) Final elements of array s are displayed by calling the function
displayarray(), thus giving the desired output.
10) END.
*/

74
QUESTION 22
import java.io.*;
import java.util.*;
class Q22
{
int arr[];
int n;
Q22(int nm)
{
n=nm;
arr=new int[n];
}
void input()throws IOException
{
Scanner imp=new Scanner(System.in);
System.out.println("Enter the elements");
for(int i=0;i<n;i++)
arr[i]=imp.nextInt();
}
void display()
{
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");

75
System.out.println("");
}
Q22 intersection(Q22 obj)
{
int size=0;
if(n<obj.n)
size=n;
else
size=obj.n;
Q22 obj1=new Q22(size+100);
size=0;
int tep[]=new int[n];
int tep1[]=new int[obj.n];
for(int i=0;i<n;i++)
tep[i]=arr[i];
for(int i=0;i<obj.n;i++)
tep1[i]=obj.arr[i];
for(int i=0;i<n;i++)
{
for(int j=0;j<obj.n;j++)
{
if(tep[i]==tep1[j])
{
obj1.arr[size++]=tep[i];
tep[i]=tep[j]=0;
break;
}
}
}
obj1.n=size;
return obj1;
}
Q22 union(Q22 obj)
{
Q22 obj1=new Q22(n+obj.n);
int size=0;
Arrays.sort(arr);
Arrays.sort(obj.arr);
int a=0,b=0;
try
{

76
for(int i=0;i<(n+obj.n);i++)
{
if(a==n&&b!=obj.n)
{
obj1.arr[size++]=obj.arr[b];
b++;
}
else if(a!=n&&b==obj.n)
{
obj1.arr[size]=arr[a++];
size=size+1;
}
else if(arr[a]==obj.arr[b])
{
obj1.arr[size++]=arr[a++];
b++;
}
else if(arr[a]<obj.arr[b])
obj1.arr[size++]=arr[a++];
else
obj1.arr[size++]=obj.arr[b++];
}
}
catch(Exception e)
{
System.out.println();
}
obj1.n=size;
return obj1;
}
public static void main(String []args)throws IOException
{
Scanner imp=new Scanner(System.in);
System.out.println("Enter the size of first array less than 50");
Q22 obj1=new Q22(imp.nextInt());
obj1.input();
System.out.println("Enter the size of second array less than 50");
Q22 obj2=new Q22(imp.nextInt());
obj2.input();
Q22 obj3=obj1.intersection(obj2);
System.out.println("Intersection of the two arrays is:");

77
obj3.display();
obj3=obj1.union(obj2);
System.out.println("The union is:");
obj3.display();
}
}
/*
Sample Output:
1) Enter the size of first array less than 50
5
Enter the elements
1 4 5 68 9
Enter the size of second array less than 50
6
Enter the elements
1 3 4 88 66 99
Intersection of the two arrays is:
14
The union is:
1 3 4 5 9 66 68 88 99
2) Enter the size of first array less than 50
5
Enter the elements
5
4
3
2
1
Enter the size of second array less than 50
5
Enter the elements
5
6
7
8
9
Intersection of the two arrays is:
5
The union is:
123456789

78
ALGORITHM
1) Declare class variables int size(to store size),int arr[](to store the array elements).
2) Define two function one for intersection and other for union of the sets.
3) Both the functions are static and take class object as parameters. In intersection
function first sort the arrays of calling and passed objects.
4) Define another object of class type to store and to return the final array.
5) Find all the common elements by using the simple procedure of searching one
element in other array if found then store it in the array of the object just declared.
6) Finally return the object with the intersection of the sets, take the address in
another declared object in the main funtion and call display.
7) Follow step 3 and 4 for the union funtion as well.
8) Now using variables and loops fill the union set ensuring that no duplicate element
comes in it.
9) Finally return the union object and follow step 6.
10) Display the reqired result.
*/

QUESTION 23
import java.io.*;
import java.util.*;
class Q23
{
static String ss[];
static int flag=0;
static void yarg(String prefix, int n)
{
if (n == 0)
ss[flag++]=prefix;
else
{
gray(prefix + "1", n - 1);
yarg(prefix + "0", n - 1);
}
}
static void gray(String prefix, int n)
{
if (n == 0)
ss[flag++]=prefix;
else
{

79
gray(prefix + "0", n - 1);
yarg(prefix + "1", n - 1);
}
}
public static void main(String args[])throws Exception
{
int k,size=0,size2=0;
String s;
String sss[];
Scanner imp = new Scanner(System.in);
System.out.println("Enter the hammer distance followed by gray code string
deparated by spaces:");
k=imp.nextInt();
s=imp.next();
ss=new String[(size=(int)Math.pow(2,s.length()))];
sss=new String[(int)Math.pow(2,s.length())];
gray("",s.length());
String qw="01";
for(int i=0;i<size;i++)
{
int temp=0;
flag=0;
while(temp<s.length())
{
flag+=qw.indexOf(ss[i].charAt(temp++));
if(flag>k)
break;
if(temp==s.length()&&flag==k)
sss[size2++]=ss[i];
}
}
for(int i=0;i<size2;i++)
{
System.out.println(sss[i]);
}
}
}
/*
Sample Output:
Enter the hammer distance followed by gray code string deparated by spaces:
2 0000

80
0011
0110
0101
1100
1010
1001
*/

QUESTION 24
import java.io.*;
class Q24
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the no. of rows and columns.");
int r=Integer.parseInt(br.readLine());
int t=Integer.parseInt(br.readLine());
int f[][]=new int[r][t];
int s[][]=new int[r][t];
System.out.println("Enter the elements");
for(int i=0;i<r;i++)
{
for(int j=0;j<t;j++)
f[i][j]=Integer.parseInt(br.readLine());
}
for(int i=0;i<r;i++)
{
for(int j=0;j<t;j++)
System.out.print(f[i][j]+" ");

81
System.out.println();
}
for(int i=0;i<r;i++)
{
for(int j=0;j<t;j++)
{
if(j>0&&i>0)
{
int max=s[i][j-1];
if(max<s[i-1][j])
max=s[i-1][j];
s[i][j]=f[i][j]+max;
}
else if(j>0)
s[i][j]=f[i][j]+s[i][j-1];
else if(i>0)
s[i][j]=f[i][j]+s[i-1][j];
else
s[i][j]=f[i][j];
}
}
System.out.println("Output: "+s[r-1][t-1]);
}
}
/*
Sample Output:
1) Enter the no. of rows and columns.
2
5
Enter the elements
2
5
6
3
1
1
2
3
0
8

82
2 5 6 3 1
1 2 3 0 8
Output: 25

2) Enter the no. of rows and columns.


3
5
Enter the elements
1
2
3
4
5
6
7
8
9
0
11
12
13
14
15

1 2 3 4 5
6 7 8 9 0
11 12 13 14 15
Output: 72
ALGORITHM
1)The no. of rows and columns are entered by user in integer type variable r and t.
2)Two integer type double dimensional arrays f and s are initialised both with size r by t
3)User enters the no. of apples at each position as elements of f.
4)f matrix is printed.
5)A nested for loop is created. The outer loop running with i increasing from 0 to r-1, and
inner loop running with j increasing from 0 to t-1. Within inner loop if i is greater than 0
and j is also greater than 0 then the larger one of s[i][j-1] and s[i-1][j] is added with
f[i][j] and stored into s[i][j], if only i is greater than 0 then s[i-1][j] is added with f[i][j]
and stored into s[i][j], if only j is greater than 0 then s[i][j-1] is added with f[i][j] and
stored into s[i][j], and if both i and j are equal to 0 then simply f[i][j] is stored in s[i][j].
6)The sum of path with the highest sum while only moving either down or right gets stored
in the last element of s i.e., s[r-1][t-1].

83
7)s[r-1][t-1] is printed as the required output.
8) END.
*/

QUESTION 25
import java.io.*;
import java.util.*;
class Q25
{
public static void main(String args[])throws Exception
{
Scanner imp = new Scanner(System.in);
int m=0,n=0;
System.out.println("Enter the size of matrix press enter then enter the
elements:");
int or[][]=new int[(m=imp.nextInt())][(n=imp.nextInt())];
String oor[]=new String[m];
String ocr[]=new String[m];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
or[i][j]=imp.nextInt();
}
System.out.println("Enter the elements of second matrix:");
int oc[][]=new int[(m)][(n)];
for(int i=0;i<m;i++)

84
{
for(int j=0;j<n;j++)
oc[i][j]=imp.nextInt();
}
int a=0;
try
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
ocr[a]=(oc[j][i])+"";
oor[a]=(or[j][i])+"";
a=a+1;
}
}
}
catch(Exception e)
{}
int flag=0;
for(int i=0;i<m;i++)
{
flag=0;
for(int j=0;j<m;j++)
{
if(ocr[i].equals(oor[j]))
flag=1;
}
if(flag==0)
break;
}
if(flag==0)
System.out.println("Not possible");
else
System.out.println("Possible");
}
}
/*
Sample Output:
1) Enter the size of matrix press enter then enter the elements:
43

85
1234
1234
1234
Enter the elements of second matrix:

4321
4321
4321
Possible

2) Enter the size of matrix press enter then enter the elements:
22

55
67
Enter the elements of second matrix:

45
67
Not possible

ALGORITHM
1)Declare the variables
int m=0,n=0 to store the size of the matrix.
int or[][]=new int[(m=imp.nextInt())][(n=imp.nextInt())]
this array is to store the input of matrix.
int oc[][]=new int[(m)][(n)] to store the second matrix.
2) tring oor[]=new String[m]
to store the column in string form.
String ocr[]=new String[m]
3) Take input from the user using for loop and using the size entered initialize the
matrix.
4) Take input from the second matrix.

86
5) Our aim is to check if wrt to each column in the first there is a colunm in second
matrix or not.
6) To check this find each element of oor[] in ocr[] if all elements of first are present
if(ocr[i].equals(oor[j])) in second then it means that it is possible.
7) Display approprite message along with the matrices.
8) END.
*/

QUESTION 26
import java.io.*;
class Q26
{
public static void main(String args[])throws IOException
{
InputStreamReader inp=new InputStreamReader(System.in);
BufferedReader ob=new BufferedReader(inp);
String post="",v="-+*/^",op1="",op2="",str[];
int top=-1;
System.out.print("Enter the Postfix Expression: ");
post=ob.readLine();
str=new String[post.length()];
for(int i=0;i<post.length();i++)
{
if(v.indexOf(post.charAt(i))!=-1)
{
op2=str[top--];
op1=str[top--];
String t="("+op1+post.charAt(i)+op2+")";

87
str[++top]=t;
}
else
str[++top]=""+post.charAt(i);
}
System.out.println("The Infix Expression is: "+str[0]);
}
}
/*
Sample Output:
1) Enter the Postfix Expression :ab+cd+e-a+-
The Infix Expression is :((a+b)-(((c+d)-e)+a))

2) Enter the Postfix Expression :ab*cd/e^a-/


The Infix Expression is :((a*b)/(((c/d)^e)-a))

ALGORITHM
1) post stores the postfix expression entered by the user.
2) op1 and op2 stores the two operands stored in the stack.
3) If the scanned symbol is an operand it will go in the stack. If the scanned symbol is an
operator pop out op1 and op2 from the stack and add them string t in infix order.
4) Now the str[top] has the resultant infix expression.
5) This extraction continues till all the elements of post have been scanned .
6) At last we get the final infix expression at str[0].
7) END.
*/

88
QUESTION 27
import java.io.*;
import java.util.*;
class Q27
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int cou[], words[]=new int[10], vel[]=new int[10];
String qq[];
String ww[]=new String [10];
System.out.println("Enter the sentnces:");
int size=1;
StringTokenizer st=new StringTokenizer(br.readLine());
cou=new int[st.countTokens()];
cou[0]=-1;
qq=new String [st.countTokens()];
int qwe=st.countTokens();
for(int i=0;i<qwe;i++)
{
qq[i]=st.nextToken();
if(qq[i].charAt(0)<64)

89
cou[size++]=i;
}
cou[size]++;
int q=0;
for(int i=1;i<size;i++)
{
vel[i-1]=0;
words[i-1]=-1;
int flag=0;
for(int j=cou[i-1]+1;j<=cou[i];j++)
{
words[i-1]++;
if(flag==0)
ww[i-1]=qq[q++];
else
ww[i-1]=ww[i-1]+qq[q++];
flag =1;
}
}
String vuo="AEIOUaeiou";
for(int i=0;i<size-1;i++)
{
for(int j=0;j<ww[i].length();j++)
{
if(vuo.indexOf(ww[i].charAt(j))>=0)
vel[i]++;
}
}
for(int i=0;i<size-1;i++)
{
System.out.println("The sentence "+(i+1)+"contains "+vel[i]+" vowels
and "+words[i]+" words.");
for(int j=0;j<vel[i];j++)
System.out.print("VVV");
System.out.println();
for(int j=0;j<words[i];j++)
System.out.print("WWW");
System.out.println();
}
}
}

90
/*
Sample Output:
1) Enter the sentnces:
He is good . He is nice ? bad day.
The sentence 1contains 4 vowels and 3 words.
VVVVVVVVVVVV
WWWWWWWWW
The sentence 2contains 4 vowels and 3 words.
VVVVVVVVVVVV
WWWWWWWWW
The sentence 3contains 2 vowels and 2 words.
VVVVVV
WWWWWW
2) Enter the sentnces:
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF LUCK.
The sentence 1contains 2 vowels and 1 words.
VVVVVV
WWW
The sentence 2contains 5 vowels and 3 words.
VVVVVVVVVVVVVVV
WWWWWWWWW
The sentence 3contains 8 vowels and 4 words.
VVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWW
The sentence 4contains 3 vowels and 3 words.
VVVVVVVVV
WWWWWWWWW

ALGORITHM
1) Declare five arrays three of int type to store words
int cou[];
int words[]=new int[10];
int vel[]=new int[10];
String qq[];
String ww[]=new String [10];
vowels and the positions of signs. The other two of String type to store the input
sentence and the sentences.
2) Take input and and break it into tokens using string tokenizer. StringTokenizer
st=new StringTokenizer(br.readLine());

91
3) Store the number of words int total and the positions of signs using for loop going
from 0 to the number of tokens in total.
4) Run a loop that many times which us equal to the number of sentences in total.
Whitin this loop count the number if vowels in each sentence and stroe it in for(int
i=0;i<size-1;i++) the already made for the purpose.
5) We already have the no of words in each sentnece so display them along with the
sentence number.
6) Display pictorial representation of the number of words and vowels by using another
two for loops nested
for(int j=0;j<vel[i];j++)
System.out.print("VVV");
System.out.println();
for(int j=0;j<words[i];j++)
System.out.print("WWW");
System.out.println();
in the last loop.
*/

QUESTION 28
import java.io.*;
class Q28
{
static int[] findLis(int[] arr)
{
int[] is = new int[arr.length];
int index = 0;
is[0] = index;
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < arr[is[index]])
{
for (int j = 0; j <= index; j++)
{
if (arr[i] < arr[is[j]])
{
is[j] = i;
break;
}
}
}

92
else if (arr[i] != arr[is[index]])
is[++index] = i;
}
int[] lis = new int[index + 1];
lis[index] = arr[is[index]];
for (int i = index - 1; i >= 0; i--)
{
if (is[i] < is[i + 1])
lis[i] = arr[is[i]];
else
{
for (int j = is[i + 1] - 1; j >= 0; j--)
{
if (arr[j] > arr[is[i]] && arr[j] < arr[is[i + 1]])
{
lis[i] = arr[j];
is[i] = j;
break;
}
}
}
}
return lis;
}
public static void main(String[] args)throws IOException
{
int n,arr[];
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Q28 obj=new Q28();
System.out.println("Enter Size of array.");
n=Integer.parseInt(br.readLine());
arr= new int[n];
System.out.println("Enter the elements.");
for(int j=0;j<n;j++)
arr[j]=Integer.parseInt(br.readLine());
int p[]=obj.findLis(arr);
for (int i=0;i<p.length;i++)
System.out.print(p[i]+" ");
System.out.println();
}

93
}
/*
Sample Output:

1) Enter Size of array.


10
Enter the elements.
9
1
2
35
14
9
20
25
30
21
1 2 9 20 25 30

2) Enter Size of array.


5
Enter the elements.
3
5
7
9
11
3 5 7 9 11

ALGORITHM
1) Integer type variable n and integer type array arr are initialised.
2) User enters the size of the array in variable n.
3) n is assigned as the size of array arr.
4) User enters the elements of array arr.
5) Function findLis() is called with array arr as the parameter.
6) Function findLis() finds the the longest sub-sequence of numbers in ascending order
and returns the result to the main method as an array.
7) The result of findLis() is stored in an integer type array p.
8) Array p is displayed as the required output.
9) END.

94
*/

QUESTION 29
import java.io.*;
class Q29
{
public static void main(String args[])throws IOException
{
InputStreamReader inp=new InputStreamReader(System.in);
BufferedReader ob=new BufferedReader(inp);
int n,am[],w[]={0,1,2,3,4,5,6,7,8,9},df[]={1000,500,100,50,20,10,5,2,1};
String str="", ams="", wor[]={"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE",
"SIX", "SEVEN", "EIGHT", "NINE"};
System.out.print("Enter the amount"+" "+':');
n=Integer.parseInt(ob.readLine());
if(n>99999)
{
System.out.println("INVALID AMOUNT");
System.exit(0);
}
str=String.valueOf(n);
am=new int[str.length()];
for(int i=0;i<str.length();i++)
{

95
am[i]=((int)str.charAt(i)-48);
for(int j=0;j<w.length;j++)
{
if(am[i]==w[j])
{
ams=ams+wor[j];
ams=ams+" ";
}
}
}
System.out.println(ams);
while(n>0)
{
if(n>df[0])

System.out.println("1000*"+n/df[0]+"="+(1000*(n/df[0])));n=n%df[0];}
else if(n>df[1])
System.out.println("500*"+n/df[1]+"="+(500*(n/df[1])));n=n%df[1];
else if(n>df[2])
System.out.println("100*"+n/df[2]+"="+(100*(n/df[2])));n=n%df[2];
else if(n>df[3])
System.out.println("50*"+n/df[3]+"="+(50*(n/df[3])));n=n%df[3];
else if(n>df[4])
System.out.println("20*"+n/df[4]+"="+(20*(n/df[4])));n=n%df[4];
else if(n>df[5])
System.out.println("10*"+n/df[5]+"="+(10*(n/df[5])));n=n%df[5];
else if(n>df[6])
System.out.println("5*"+n/df[6]+"="+(5*(n/df[6])));n=n%df[6];
else if(n>df[7])
System.out.println("2*"+n/df[7]+"="+(2*(n/df[7])));n=n%df[7];
else
System.out.println("1*"+n/df[8]+"="+(1*(n/df[8])));n=n%df[8];
}
}
}
/*
Sample Output:

1) Enter the amount :14836


ONE FOUR EIGHT THREE SIX
1000*14=14000

96
500*1=500
100*3=300
20*1=20
10*1=10
5*1=5
1*1=1

2) Enter the amount :235005


INVALID AMOUNT

ALGORITHM
1) Integer type variable n to store the amount. w[] to store number from 1-9.df[] to
store the denomination factor. wor[] store all the numbers from 1-9 in word.am[] to
store each digit of the amount. ams to store the amount in String.
2) n is converted to string type and each character is extracted and matched for its
word form in wor[].
3) When found the element of wor[] is added to ams.
4) For denomination of the amount the while loop executes till amount is greater than
0.
5) When the denominating factor is able to divide the amount then the denomination
is printed.
6) END.
*/

97
QUESTION 30
import java.io.*;
class Q30
{
static InputStreamReader inp=new InputStreamReader(System.in);
static BufferedReader ob=new BufferedReader(inp);
static String str[],nstr="",estr="",e1str="";
static String
v="ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
static int n;
public static void main(String args[])throws Exception
{
Q30 obj=new Q30();
System.out.print("Enter size of the array :");
n=Integer.parseInt(ob.readLine());
str=new String[n];
obj.input();
for(int i=1;i<=n;i++)
{
if(i%2!=0)
{

98
nstr=encrypt(str[i-1]);
str[i-1]=nstr;
nstr="";
}
else
{
nstr=reverse(str[i-1]);
str[i-1]=nstr;
nstr="";
}
}
System.out.println("THE ENCRYPTED CODE IS:");
for(int i=0;i<n;i++)
System.out.println(str[i]);
}
void input()throws Exception
{
System.out.println("Enter "+n+" sentences :");
for(int i=0;i<n;i++)
str[i]=ob.readLine();
}
static String encrypt(String x)
{
estr="";
for(int i=0;i<x.length();i++)
{
if(x.charAt(i)!=' '&&x.charAt(i)!='.')
estr=estr+v.charAt((v.indexOf(x.charAt(i))+2));
else if(x.charAt(i)==' ')
estr=estr+" ";
else
estr=estr+".";
}
return(estr);
}
static String reverse(String y)
{
String w="",q[];
int wc=0,t=0;e1str="";
for(int i=0;i<y.length();i++)
{

99
if(i==0&&(y.charAt(i)==' '&&y.charAt(i)=='.'))
continue;
if(y.charAt(i)==' '||y.charAt(i)=='.')
wc=wc+1;
}
q=new String[wc];
for(int i=0;i<y.length();i++)
{
if(y.charAt(i)==' '||y.charAt(i)=='.')
{
q[t]=w;
t=t+1;
w="";
}
else
w=w+y.charAt(i);
}
for(int i=wc-1;i>=0;i--)
{
e1str=e1str+q[i];
if(i==0)
e1str=e1str+".";
else
e1str=e1str+" ";
}
wc=0;
q=new String[wc];
return(e1str);
}
}
/*
Sample Output:

1) Enter size of the array :4


Enter 4 sentences :
IT IS CLOUDY.
IT MAY RAIN.
THE WEATHER IS FINE.
IT IS COOL.

THE ENCRYPTED CODE IS:

100
KV KU ENQWFA.
RAIN MAY IT.
VJG YGCVJGT KU HKPG.
COOL IS IT.

2) Enter size of the array :4


Enter 4 sentences :
YOU HAVE NO POWER HERE.
YOU SHALL NOT PASS.
CONSTANT VIGILANCE.
IMAGINATION EXCEEDS KNOWLEDGE.

THE ENCRYPTED CODE IS:


AQW JCXG PQ RQYGT JGTG.
PASS NOT SHALL YOU.
EQPUVCPV XKIKNCPEG.
KNOWLEDGE EXCEEDS IMAGINATION.

ALGORITHM
1) Integer type variable n-to store the number of sentences to be entered in the String
type array str[]. nstr store one sentence at a time. v stores all the alphabets in cyclic
order. w stores a particular word of a sentence.q[] is String type and stores a word of a
sentence at each index.
2) Object of the class is created .Sentences are entered.
3) The encrypt() function is invoked when control reaches to an odd numbered
sentence (first sentence will be numbered as 1 and so on.) For even numbered
sentence reverse() is invoked.
4) The encrypt() function increments each letter of a sentence by two.
5) The reverse() function reverses the order of words in a sentence.
6) Each of the modified sentence is stored at its initial index in str[].
7) str[] is displayed at last.
8) END.
*/

101
QUESTION 31
import java.io.*;
class Q31
{
static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
void moves(int n,double a[],double b[])
{
if(n==0)
return;
moves(n-1,a,b);
a[n]=-a[n];
a[0]+= 2*a[n];
if(Math.abs(a[0])<Math.abs(b[0]))
for(int i=0;i<a.length;i++)
b[i]=a[i];
moves(n-1,a,b);
}
public static void main(String[] args)throws IOException
{
Q31 obj=new Q31();
System.out.println("Enter the size");

102
int N=Integer.parseInt(br.readLine());
double[]a=new double[N+1];
double[]b=new double[N+1];
System.out.println("Enter the numbers");
for(int i=1;i<=N;i++)
a[i]=Double.parseDouble(br.readLine());
for(int i=1;i<=N;i++)
a[0]+=a[i];
b[0]=a[0];
obj.moves(N, a, b);
Double c[]=new Double[N];
Double d[]=new Double[N];
int g=0,h=0;
for(int i=1;i<=N;i++)
{
if(b[i]<0)
c[g++]=(-1)*b[i];
else
d[h++]=b[i];
}
System.out.println("The first group is");
for(int i=0;i<g;i++)
System.out.print(c[i]+", ");
System.out.println();
System.out.println("The second group is");
for(int i=0;i<h;i++)
System.out.print(d[i]+", ");
System.out.println();
if(b[0]<0)
b[0]=(-1)*b[0];
System.out.println("Difference: "+ b[0]);
}
}
/*
Sample Output:

1) Enter the size


10
Enter the numbers
1
2

103
3
4
5
6
7
8
9
10
The first group is
2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
The second group is
1.0, 8.0, 9.0, 10.0,
Difference: 1.0

2) Enter the size


7
Enter the numbers
12
19
51
28
65
41
79
The first group is
12.0, 19.0, 51.0, 65.0,
The second group is
28.0, 41.0, 79.0,
Difference: 1.0

ALGORITHM
1) User enters the no. of numbers in integer type variable N.
2) Double type array a and b are initialised with their size as N+1.
3) User enters the desired nos. in the array a in positions 1 to N.
4) The sum of all the nos. is stored in a[0] and b[0].
5) Recursive function moves() is called with variable n, array a and array b as the
parameters. Function moves() stores the nos. for the first group as positive nos. while the
nos. for the second group as negative nos. in the array b after position 0, at which it
stores the difference of the two groups.

104
6) Double type array c and d are initialised with size N and the positive nos. n array b
i.e., the first group is stored in c while the negative nos. i.e., the second group is
stored in d.
7) Array c and d are printed as the first nd second group and b[0] is printed as the
difference between them, thus giving the desired output.
8) END.

105

Vous aimerez peut-être aussi