0% found this document useful (0 votes)
14 views

project computer mock

Uploaded by

kyb.faisal.8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

project computer mock

Uploaded by

kyb.faisal.8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

Question 1

Given the two positive integers p and q, where p < q. Write a program to determine how
many Kaprekar numbers are there in the range between 'p' and 'q' (both inclusive)
About 'Kaprekar' number:
A positive whole number 'n' that has 'd' number of digits is squared and split into 2 pieces, a
right hand piece that has 'd' digits and a left hand piece that has remaining 'd' or 'd-1' digits.
If sum of the pieces is equal to the number then it's a Kaprekar number.
Example 1 Example 2
9 45
92 = 81, right hand piece of 81 = 1 and left 452 = 2025, right hand piece of 2025 = 25
hand piece of 81 = 8 and left hand piece of 2025 = 20
Sum = 1 + 8 = 9, i.e. equal to the number Sum = 25 + 20 = 45, i.e. equal to the
number
SAMPLE DATA:
INPUT:
p=1 Q=1000
OUTPUT:
THE KAPREKAR NUMBERS ARE:
1, 9, 45, 55, 99, 297, 703, 999
FREQUENCY OF KAPREKAR NUMBERS IS: 8
Class details are given below
Class Name: Kaprekar
Data members:
Int p, q: Integer type variable to store the numbers
Int count: Variable use to store total no of Kaprekar number between p & q
Member functions:
Kaprekar ( ): Constructor to assign 0 to p, q and count
Void input ( ): To accept value of p & q
Void swap ( ): Function to swap value of p & q if p> q
int square (int a): Returns square of the parameter passed
int check (int n): Function to check if n is Kaprekar number and return 1 else return 0.
void display( ): Function to display the output in given format along with the frequency of
Kaprekar numbers.
ALGORITHIM
START
STEP 1: TAKE THE LIMITS IN DATA MEMBERS ‘p’ AND ‘q’.
STEP 2: IF p>q GO TO STEP 3 ELSE GO TO STEP 4.
STEP 3: SWAP THE VALUES OF p AND q.
STEP 4: LET A DATA MEMBER ‘I’ BE p.
STEP 5: IF ‘I’ IS LESS THAN q GO TO STEP 6 ELSE GO TO STOP.
STEP 6: SQUARE THE NUMBER ‘I’ AND STORE IT IN DATA MEMBER ‘N’.
1
STEP 7: BREAK THE NUMBER N IN TWO PARTS SUCH THAT LEFT HAND SIDE HAS EQUAL NUMBER OF
DIGITS AS OF RIGHT HAND SIDE OR ONE LESS.
STEP 8: IF THE SUM OF TWO PARTS IS ‘I’ DISPLAY ’I’ IS A Kaprekar NUMBER.
STEP 9: INCREMENT ‘I’ BY 1. GO TO STEP 5
STOP

PROGRAM
import java.io.*;
class ques1
{
public static void main(String args[ ])throws IOException
{
Kaprekar obj = new Kaprekar( );
obj.input( );
obj.display( );
}
}
class Kaprekar
{
int p,q;
int count;
Kaprekar ( )
{
p=0;
q=0;
count=0;
}
void input( )throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the limits");
p=Integer.parseInt(k.readLine( ) );
q=Integer.parseInt(k.readLine( ) );
}
void swap( )
{
int t=0;
if(p>q)
{
t=p;

2
p=q;
q=t;
}
}
int square(int n)
{
int sq=0;
sq=n*n;
return sq;
}
int check(int n)
{
int sq=0,num=0,d=0,r=0,l=0,t=0,flag=0;
sq=square(n);
num=n;
while(num!=0)
{
d++;
num=num/10;
}
num=n;
t=(int)Math.pow(10,d);
r=sq%t;
l=sq/t;
if((r+l)==num)
flag=1;
return flag;
}
void display( )
{
int i=0,flag=0;
swap( );
System.out.println("THE Kaprekar NUMBERS ARE: ");
for(i=p; i<=q; i++)
{
flag= check(i);
if (flag==1)
{
count++;

3
System.out.print(i+",");
}
}

System.out.println( );
System.out.println("FREQENCY OF KAREKAR NUMBER IS: "+count);
}
}
Output:
Enter the limits
1
100
THE KAPREKAR NUMBERS ARE :
1,9,45,55,99,
FREQENCY OF KAPREKAR NUMBERS IS: 5

Question 2
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 2. 4937775
Sum of the digits are (6+6+6) =18 Prime factors are 3, 5, 5 and 65837
Sum of the digit of the factors (2+3+3+ Sum of the digits are (4+9+3+7+7+5)=42
(3+7)) =18 Sum of the digit 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

Class Name : Smith


Data Members
int n : integer to check for smith number
Member Functions

4
smith (int num): Constructor to initialize n = num.
int check (int) : To check if no is single digit or not.
int sum (int p) : To find the sum of the digits of number p.
void display( ) : To display the output whether number is Smith or not.
Specify the class format and also write the main( ) function.

ALGORITHIM
START
STEP 1: STORE THE NUMBER IN ‘N’
STEP 2: FIND OUT THE PRIME FACTORS OF ‘N’
STEP 3: CALCULATE SUM OF DIGITS OF PRIME FACTORS.STORE IT IN F.
STEP 4: CALCULATE SUM OF DIGITS OF N. STORE IT IN S
STEP 5: IF F=S, GO TO STEP 6 ELSE STEP 7
STEP 6: DISPLAY “SMITH NUMBER”.GO TO STOP
STEP 7: DISPLAY “NOT SMITH NUMBER”
STOP

PROGRAM
import java.io.*;
class ques2
{
public static void main(String args[ ])throws IOException
{
long num1;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number to be checked for a smith number or
not");
num1=Integer.parseInt(in.readLine( ));
smith obj=new smith(num1);
obj.display( );
}
}
class smith
{
long num1;
smith(long num)
{
num1=num;
}
int check(int x)
5
{
int flag=0,digits=0;
if(x<=9)
{
flag=1;
return flag;
}
else
{
flag=0;
return flag;
}
}
long sum(long p)
{
long s=0,i,d;
for(i=p; i> 0; i=i/10)
{
d=i%10;
s=s+d;
}
return s;
}
void display( )
{
long count=0,sum1=0,sum2=0;
long num=num1;
sum1=sum(num);
for(int i=2; i<num1; i++)
{
count=0;
for(int j=1; j<=i; j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2&&(num%i==0))

6
{
long ans=sum(i);
sum2=sum2+ans;
num=num/i;
i=2;
}
}
if(sum1==sum2)
{
System.out.println(num1+" is a smith number");
}
else
{
System.out.println(num1+" is not a smith number");
}
}
}
Output:
enter the number to be checked for a smith number or not
666
666 is a smith number

Question 3
WAP to store ‘N’ different numbers in SDA where ‘N’ is always odd. Arrange them in such a
way that the highest element should be in the middle position, second highest element to the
left side of it, third highest to the right hand side and so on...
Example
Input: 71, 40, 69, 56, 19, 31, 85, 99, 23, 91, 59
Output: 23, 40, 59, 71, 91, 99, 85, 66, 56, 31, 19

Class members are specified below:


Class Name: arrange
Data member
arr[ ] : integer type
size : integer type variable to store size of array
Member Function
Arrange(int n): parameterized constructor to initialize n to size
Void input( ) : function to input an array of specified size.

7
Void arrange( ): to arrange them in such a way that the element should be in the middle
position, second highest element to the left side of it, third highest to the
right hand side and so on...
Void display( ) : function to display the array before and after arrangement.
Specify the class arrange and also write the main( ) function.

ALGORITHM
START
STEP 1: INPUT THE ARRAY IN ARR[ ]
STEP 2: CREATE ANOTHER ARRAY B[ ] DUPLICATE OF ARR[ ]
STEP 3: SORT B[ ] IN ASCENDING ORDER
STEP 4: NOW PLACE ELEMENTS OF B[ ] IN ARR[ ] IN WAY REQUIRED.
STEP 5: DISPLAY ARR[ ]
STOP

PROGRAM
import java.io.*;
class ques3
{
public static void main(String args[ ])throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of ODD array");
int n=Integer.parseInt(in.readLine( ));
Arrange obj=new Arrange(n);
obj.input( );
System.out.println("INPUT");
obj.display( );
obj.arrange( );
System.out.println("OUTPUT");
obj.display( );
}
}
class Arrange
{ int arr[ ]; int size;
Arrange(int n)
{ size=n;
arr =new int[size];
}
8
void input( )throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements of the array");
for(int i=0; i<size; i++)
arr[i]=Integer.parseInt(in.readLine( ));
}
void arrange( )
{
int i=0,pos=0,j=0,temp=0,c=0;
for(i=0; i<size-1; i++)
{ for(j=i+1; j<size; j++)
{ if(arr[j]>arr[i])
{ temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
int b[ ]=new int[size];
for(i=0; i<size; i++)
{ b[i]=arr[i];
}
i=0;
for(c=0; c<=(size/2); c++)
{ arr[(size/2)-c]=b[i++];
if(c==0)
i--;
arr[(size/2)+c]=b[i++];
}
}
void display( )
{ for(int i=0; i<size; i++)
System.out.print(arr[i]+" ");
System.out.println( );
}
}
Output:
Enter the size of ODD array
3

9
Enter the elements of the array
5
6
7
INPUT
567
OUTPUT
675
Question 4
Start with any positive number of 2 or more digits. Obtain another positive number by
reversing the digits of the starting number. Add the two numbers together. Repeat the whole
procedure with the sum as the starting number till you get a sum which is a Palindrome
number. Program to calculate the palindrom of a given number in maximum 15 terms.
Assume that the starting number is not a Palindrome.
Sample Input : 87
Sample Output: 4884
Steps : 4

A class palinNumber is declared to perform the above operations.some of the members of


class are given below
Class Name: palinNumber
Data members:
n: long integer to store number
Member functions:
palinNumber( ) : constructor to store 0 to n
palinNumber(int nx) : constructor to initialize n=nx
Boolean isPalindrom( ) : it checks and returns tru if n is able to generate a palindrome
number upto 15 steps otherwise returns false
Void show( ) : to print original number, palindrome number and number of
steps that n took to generate the palindrome number other wise
print suitable message.
Specify the class palinNumber giving details of constructors and functions. Write the main( )
function to create an object of palinNumber type and print the desired result.

ALGORITHM
START
STEP 1: INPUT THE NUMBER
STEP 2: SET C=0
STEP 3: IF C<15 GO TO STEP 4 ELSE GO TO STOP

10
STEP 4: IF REVERSE OF NUMBER=NUMBER GO TO STEP 7; ELSE STEP 5
STEP 5: NUMBER=NUMBER +REVERSE
STEP 6: INCREMENT C BY 1 GO TO STEP 3
STEP 7: DISPLAY PALINGDROME NUMBER WITH C AS NUMBER OF STEPS
STOP

PROGRAM
import java.io.*;
class ques4
{
public static void main(String args[ ])throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int N;
System.out.println("enter the number");
N=Integer.parseInt(in.readLine( ));
palinNumber obj=new palinNumber(N);
obj.show( );
}
}
class palinNumber
{ long n;
palinNumber(long nx)
{ n=nx;
}
Boolean Ispalindrome( )
{ Boolean flag=false;
long num=0; long f;
f=n;
int new1=1;
num=n;
int steps=0;
long temp=0,t=0;
long r=0,l=0,s;
while(steps<16)
{ num=f;
r=0;
t=0;
while(num!=0)
{ r=num%10;

11
t=(t*10)+r;
num=num/10;
}
steps++;
f+=t;
l=0;
num=f;
temp=0;
while(num!=0)
{ l=num%10;
temp=(temp*10)+l;
num=num/10;
}
if(temp==f)
{ new1=0;
flag=true;
System.out.println("palindrome number is "+temp);
System.out.println("number of steps= "+steps);
System.out.println("original number="+n);
break;
}
if(new1==0)
break;
}
return flag;
}
void show( )
{ Boolean flag=Ispalindrome( );
if(flag==false)
System.out.println("number is not able to generate a palindrome number
within 15 steps");
}
}
Output:
enter the number
15873
palindrome number is 12455421
number of steps= 6
original number=15873

12
Question 5
A class Date has been defined to handle Date related functions i.e. finding the future date n
days after the current date ie. Date 32 days after 01 - 01 will be 02 - 02. Finding the number
of days between the current date and date on which a project ends.
Example: If a project started 01-01 and finished on 02-02, the number of days would be 32.
You may assume that all the dates are in the year 2012 only and are valid dates. To make
calculations easy each date can be converted to its equivalent date number. Date number is
the number of days between 1st January (01-01) and the given date (dd-mm).
Example: Date (dd-mm) date number
01 – 01 1
20 - 01 20
02 - 02 33
03 - 03 62
….

31 - 12 366

Some of the functions/methods in Date are shown below:


Class Name : Date
Data members : dd - day; mm - month
Member functions/methods
Date(int nd, int nm) : constructor to initialize dd=nd, mm=nm
int dateTodateNumber( ) : returns the dateNumber equivalent to the current Date
object

Date dateNumberToDate(int dn): returns the Date equivalent to the given dateNumber dn
Date futureDate(int n) : returns the Date that occurs n days after the current Date
object.
You may assume that the future date will be in the year 2012 only.
Write the main function.

ALGORITHM
START
STEP 1: CREATE AN ARRAY ARR[ ] TO STORE NO. OF DAYS IN A MONTH RESPECTIVELY
STEP 2: INPUT THE DATE AND MONTH
STEP 3: SET DATE NUMBER=ARR[MONTH-2]+ DATE
STEP 4: INCREMENT DN BY NO. OF DAYS TO BE ADDED
STEP 5: CONVERT DATE NUMBER TO DATE AND MONTH
STEP 6: DISPLAY DATE AND MONTH.

13
STOP

PROGRAM
import java.io.*;
class prg5
{
public static void main(String args[ ])throws IOException
{ BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter date and month");
int dd=Integer.parseInt(k.readLine( ));
int mm=Integer.parseInt(k.readLine( ));
Date obj=new Date(dd,mm);
System.out.println("enter no of days to be increased");
int m=Integer.parseInt(k.readLine( ));
obj= obj.futureDate( m);
System.out.println("new date and month is");
System.out.println("Date"+obj.dd);
System.out.println("Month"+obj.mm);
}
}
class Date
{
int dd; int mm; int arr[ ]={31,29,31,30,31,30,31,31,30,31,30,31};
Date(int nd,int nm)
{ dd=nd;
mm=nm;
}
int dateTodateNumber( )
{ int dn=0,i;
for(i=0; i<mm-1; i++)
{ dn=dn+arr[i];
}
dn=dn+dd;
return dn;
}
Date dateNumberToDate(int dn)
{ int pos=0;
while(dn>=arr[pos])
{ dn=dn-arr[pos];

14
pos++;
}
pos++;
Date obk=new Date(0,0);
obk.mm=pos;
obk.dd=dn;
return obk;
}
Date futureDate(int n)
{ int dn=0;
Date obk=new Date(dd,mm);
dn=obk.dateTodateNumber( );
//System.out.println(dn);
dn+=n;
obk =dateNumberToDate(dn);
return obk;
}
}
Output:
enter date and month
7
7
enter no of days to be increased
139
new date and month is
DATE23
Month11

Question 6
Class Ascending contains integers. Some of the member functions of ascending are given
below:
Class Name: Ascending
Data Members:
int a[ ]: an array to store integers
int size: size of array
Member Functions:
Ascending(int n): constructor to create an array of size n
void input( ) : to input array
void sort( ) : to sort the list

15
void displaylist( ) : to display list of integers
Ascending merge(Ascending a[ ]): to merge the Ascending list al with the current Ascending
list which is sorted in ascending order
Note: while generating the final Ascending list both the original ascending lists must be
scanned only once. Elements common to the two lists should appear only once in the third
ascending list.
Specify the class Ascending giving the details of the functions. Write main( ) function also.

ALGORITHM
START
STEP 1: TAKE THE INTEGERS IN APROPPRIATE TWO ARRAYS.
STEP 2: SORT BOTH THE ARRAYS IN ASCENDING ORDER.
STEP 3: DISPLAY BOTH THE ARRAYS.
STEP 4: MERGE BOTH THE ARRAYS INTO ONE.
STEP 5: DELETE THE COMMON ELEMENTS SO THAT THEY APPPEAR ONLY ONCE.
STEP 6: SORT THIS ARRAY.
STOP

PROGRAM
import java.io.*;
class ques6
{
public static void main(String args[ ])throws IOException
{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" input size of first array");
int p = Integer.parseInt(in.readLine( ));
Ascending obj1 = new Ascending(p);
System.out.println(" input first array");
obj1.input( );
System.out.println(" input size of second array");
int q = Integer.parseInt(in.readLine( ));
Ascending obj2 = new Ascending(q);
System.out.println("please input second array");
obj2.input( );
Ascending obj = new Ascending(0);
obj = obj1.merge(obj2);
obj.displaylist( );
}
}
class Ascending
16
{ int a[ ];
int size;
Ascending(int n)
{ size = n;
a = new int[size];
}
void input( )throws IOException
{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for(int i=0; i<size; i++)
{ a[i] = Integer.parseInt(in.readLine( ));
}
}

void sort( )
{ int t;
for(int i=0; i<size; i++)
{ for(int j=0; j<(size -1); j++)
{ if(a[j]>a[j+1])
{ t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
void displaylist( )
{ for(int i=0; i<size; i++)
{ System.out.print(a[i]+" ");
}
}
Ascending merge(Ascending al)
{ int l1 = size;
int l2 = al.size;
int l = l1 + l2;
int t = 0;
Ascending m = new Ascending (l);
for(int i=0; i<l1; i++)
{ m.a[i] = a[i];
}
for(int j = l1; j<l; j++)
17
{ m.a[j] = al.a[t++];
}
m.sort( );
for(int k=0; k<(m.size-1); k++)
{ if((m.a[k])==(m.a[k+1]))
{ for(int z=k; z<(m.size-1); z++)
{ m.a[z] = m.a[z+1];
}
k--;
m.size--;
}
}
return m;
}
}
Output:
input size of first array
3
input first array
2
4
8
input size of second array
2
please input second array
6
5
2 4 5 6 8

Question 7
A class quad contains the following data members and member functions to find the roots of
a quadratic equation.
Class Name: quad
Data members: a, b, c, x1, x2 (float type)
Member functions:
quad(float, float, float): constructor to assign values to the data members.
float discriminant( ) : to return the discriminant [ b2 – 4ac ]
void root_equal( ) : to display the root if both roots are equal
void imag( ) : to display the roots, if roots are imaginary

18
void root_real( ) : to display the two real, unequal roots
void root( ) : to call other appropriate functions to find the solution of the problem.
If ax2 + bx + c = 0 is the quadratic equation, then if b2 – 4ac > 0 – roots are real, unequal
where x1 = -b + √ (b2 – 4ac )/2a
x2 = -b - √ (b2 – 4ac )/2a
If b2 – 4ac = 0 - roots are real, equal since x1 = x2 = -b / 2a
If b2 – 4ac < 0 – roots are imaginary.
Specify the class quad giving details of the functions quad(float, float, float ), float discriminant( ),
void root_equal( ), void root_real( ), void imag( ), void root( ).
Write the main function.

ALGORITHM
START
STEP 1: TAKE THE VALUE OF ‘a’ , ’b’, ’c’ IN PROPER VARIABLES.
STEP 4: CALCULATE THE VALUE OF (b^2-4*a*C) AND STORE IT IN d.
STEP 5: CALCULATE THE ROOTS USING FORMULA GIVEN IN THE QUESTION.
STEP 5: IF THE VALUE OF d=0 THEN DISPLAY THE ROOTS ARE EQUAL AND GO TO STOP
OTHERWISE GO TO STEP 6
STEP 6: IF THE VALUE OF d IS LESS THAN ZERO THEN DISPLAY THAT ROOTS ARE
IMAGINARY. GO TO STOP ELSE STEP 7
STEP 7: DISPLAY ROOTS ARE REAL AND UNEQUAL
STOP

PROGRAM
import java.io.*;
class ques7
{
public static void main(String args[ ])throws IOException
{ float x,y,z;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the values of x,y,z");
x=Float.parseFloat(in.readLine( ));
y=Float.parseFloat(in.readLine( ));
z=Float.parseFloat(in.readLine( ));
quad obj=new quad(x,y,z);
obj.root( );
}
}
class quad
{ float a,b,c,x1,x2;
19
quad(float x,float y,float z)
{ a=x; b=y; c=z;
}
float discriminant( )
{ float dis; dis=(b*b)-(4*a*c); return (dis);
}
void root( )
{ float x1,x2;
x1=-b+(int) (Math.sqrt((b*b)-(4*a*c)));
x2=+b-(int) (Math.sqrt((b*b)-(4*a*c)));
System.out.println("first root=="+ x1);
System.out.println("second root="+ x2);
root_equal( );
imag( );
root_real( );
}
void root_equal( )
{ float ans=discriminant( );
if(ans==0)
{ System.out.println("roots are equal");
}
}
void imag( )
{float ans=discriminant( );
if(ans<0)
{ System.out.println("roots are imaginary");
}
}
void root_real( )
{ float ans=discriminant( );
if(ans>0)
{ System.out.println("roots are real");
}
}
}
Output:
enter the values of x,y,z
1
4

20
4
first root==-4.0
second root=4.0
roots are equal

Question 8
A principal of a school needs to find the highest and lowest marks scored by the student and
also merit list on marks from highest to lowest in a class of 50 students. The classes student
and merit list are declared for above activities with following details where student is base
class and merit list is derived class
Class Name : student
Data members:
Tot[ ] : (DOUBLE) an array to store total marks of 50 students out of 500 each
stud[ ] : string array to store name of 50 students of a class
Member functions:
void readdetails( ) :to input names and marks of 5 students. Marks are given out of 500
each.
void printresult ( ) :to print students scoring highest and lowest marks in the class along
with names of students.
Class Name: meritlist
Data members: None
Member functions
void printmerit ( ): to print merit list of 50 students in two columns in the following format:
NAME MARKS SCORED
XXXX XXXXXX
XXXX XXXXXX
Also write main( ).
ALGORITHM
START
STEP 1: CREATE ARRAYS MARKS[ ] &NAME[ ] OF SIZE 50.
STEP 2: INPUT MARKS & NAME
STEP 3: SORT THE ARRAY MARKS[ ] IN DESCENDING ORDER & NAME[ ] ACCORDINGLY
STEP 4: DISPLAY HIGHEST AS NAME[0]&MARKS[0]
STEP 5: DISPLAY LOWEST AS NAME[49]&MARKS[49]
STEP 6: DISPLAY NAME[ ] AND MRKS[ ] AS MERIT LIST
STOP

PROGRAM
import java.io.*;

21
class ques8
{ public static void main(String args[ ])throws IOException
{ meritlist obj=new meritlist( );
obj.printmeritlist( );
}
}
class student
{ int i; Double tot[ ]=new Double[50]; String stud[ ]=new String[50];
void readdetails( )throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the names and marks of 3 students out of 500 each");
for(i=0; i<3; i++)
{ tot[i]=Double.parseDouble(in.readLine( ));
stud[i]=in.readLine( );
}
}
void printresult( )
{ System.out.println("highest marks are"+tot[0]+" "+stud[0]);
System.out.println("lowest marks are"+tot[2]+" "+stud[2]);
}
}
class meritlist extends student
{ void printmeritlist( )throws IOException
{ int i,j,k;
Double t; String temp;
readdetails( );
for(i=0; i<3; i++)
{ for(j=0; j<2; j++)
{ if(tot[j]<tot[j+1])
{ t=tot[j]; temp=stud[j];
tot[j]=tot[j+1]; stud[j]=stud[j+1];
tot[j+1]=t; stud[j+1]=temp;
}
}
}
printresult( );
System.out.println("names"+" "+"marks scored");
for(i=0; i<3; i++)
{ System.out.println(stud[i]+" "+tot[i]);

22
}

}
}
enter the names and marks of 3 students out of 500 each
496
cv
490
dsr
483
dj
highest marks are496.0 cv
lowest marks are483.0 dj
names marks scored
cv 496.0
dsr 490.0
dj 483.0

Question 9
A set is a collection in which there is no duplication of elements. A multiset is a collection in
which elements can be duplicate.
Example:
S = {1,2,3,4} is a set with integer element, while ms={1,2,3, 1,3} is a multiset with integer
elements following are some member functions of class multiset (which defines multiset
with integer elements)
Class Name – Set
Data members:
int arr[ ]: integers array of size n
int n: size
Members functions:
Set( )- Constructor to assign 0 to n.
Set(int nn) – Constructor to assign n=nn
void readlist( ) – to input integers
int isset( set s)- returns 1(one) if the multiset object is a set and 0(zero) other
wise
Set intersection(Set s1 ,Set s2)-returns intersection elements of s1,s2 assume that s1 and s2
are sets .
void displaylist( ) – to display the intersection elements if both are sets. Else display
“multiset”.

23
ALGORITHM
START
STEP 1: INPUT BOTH THE SETS IN S1[ ] AND S2[ ]
STEP 2: IF S1[ ] HAS ANY DUPLICATE ELEMENT GO TO STEP 6 ELSE GO TO STEP 3
STEP 3: IF S2[ ] HAS ANY DUPLICATE ELEMENT GO TO STEP 6 ELSE GO TO STEP 4
STEP 4: CREATE AN INTERSCTION OF S1[ ] & S2[ ] IN S3[ ]
STEP 5: DISPLAY INTERSECTION SET S1[ ].GO TO STOP
STEP 6: DISPLAY” MULTISET”
STOP

PROGRAM
import java.io.*;
class ques9
{ public static void main(String args[ ])throws IOException
{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
set obj=new set( );
obj.displaylist( );
}
}
class set
{ int arr[ ]; int n;
set( )
{ n=0;
}
set(int nn)
{ n=nn;
arr=new int[n];
}
void readlist( )throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int i;
for(i=0; i<n; i++)
{ arr[i]=Integer.parseInt(in.readLine( ));
}
}
int isset(set s)
{ int i,j,l=s.arr.length,flag=-999;
for(i=0; i<l; i++)
{ for(j=i+1; j<l-1; j++)

24
{ if(s.arr[i]==s.arr[j])
{ return (0);
}
}
}
return (1);
}
set intersection(set s1,set s2)
{ int l1=s1.arr.length,l2=s2.arr.length,i,j,t=0;
set obj=new set(l1+l2);
for(i=0; i<l1; i++)
{ for(j=0; j<l2; j++)
{ if(s1.arr[i]==s2.arr[j])
obj.arr[t++]=s1.arr[i];
}
}
obj.n=t;
System.out.print("intersection elements are"+" ");
for(n=0; n<t; n++)
{ System.out.print(obj.arr[n]+" ");
}
System.out.println( );
return(obj);
}
void displaylist( )throws IOException
{ int p,q;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the size of first set");
p=Integer.parseInt(in.readLine( ));
set obj1=new set(p);
System.out.println("enter the elements of first set");
obj1.readlist( );
System.out.println( );
System.out.println("enter the size of second set");
q=Integer.parseInt(in.readLine( ));
set obj2=new set(q);
System.out.println( );
System.out.println("enter the elements of second set");
obj2.readlist( );

25
set obj3=new set( );
int ans1=isset(obj1);
int ans2=isset(obj2);
if(ans1==(1)&&ans2==(1))
{ obj3=intersection(obj1,obj2);
if(obj3.n==0)
System.out.println("no elements ");
}
else
{ System.out.println("multiset");
}
}
}
Output:
enter the size of first set
3
enter the elements of first set
1
3
5
enter the size of second set
2
enter the elements of second set
1
9
intersection elements are 1

Question 10
Declare a class “point” which contains following-
Data members: a double dimensional array, row size, col size, row index,
Col index and other data members as required.

Member functions:
void get_array( ): to input a double dimensional array in the form of matrix of given rows
and columns.
void display_mat( ): to print the entered matrix.
void check_saddle( ): to find and print the saddle point from the entered matrix (a saddle
point from any matrix exists in all the rows if and only if the smallest
element from each row should be greatest in the corresponding column).
Example
26
Input matrix
3 5 7 4
1 6 4 9
2 4 7 5
The output should be as – saddle point is 3 (row=0 and column =0).
Also write main

ALGORITHM
START
STEP 1: INPUT THE MATRIX IN A[ ][ ]
STEP 2: SET I=0
STEP 3: IF I<SIZE OF ROW GO TO STEP 4 ELSE STOP
STEP 4: SEARCH FOR SMALLEST ELEMENT IN ROW
STEP 5: IF ELEMENT IS GREATEST IN ITS COLUMN GO TO STEP 6 ELSE STEP 7
STEP 6: DISPLAY “SADDLE POINT “WITH POSITION
STEP 7: INCREMENT I BY 1GO TO STEP 3
STOP

PROGRAM
import java.io.*;
class ques10
{ public static void main(String args[ ])throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int r,c;
System.out.println("enter the row size");
r=Integer.parseInt(in.readLine( ));
System.out.println("enter the column size");
c=Integer.parseInt(in.readLine( ));
point obj=new point(r,c);
System.out.println("enter the array elements");
obj.get_array( );
obj.display_mat( );
obj.check_saddle( );
}
}
class point
{ int a[ ][ ];
int rs,cs,ri,ci;
point (int R,int C)
{ rs=R;
27
cs=C;
a=new int[R][C];
}
void get_array( )throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int i,j;
for(i=0; i<rs; i++)
{ for(j=0; j<cs; j++)
{ a[i][j]=Integer.parseInt(in.readLine( ));
}
}
}
void display_mat( )
{ int i,j;
for(i=0; i<rs; i++)
{ for(j=0; j<cs; j++)
{ System.out.print(a[i][j]+" ");
}
System.out.println( );
}
}
void check_saddle( )
{ int i,j,flag=0,mr=0,mc=0,k;
for(i=0; i<rs; i++)
{ for(j=0; j<cs; j++)
{ mr=i; mc=j;
for(k=0; k<cs; k++)
{ if(a[i][k]<a[mr][mc])
{ mc=k;
}
}
for(k=0; k<rs; k++)
{ if(a[k][j]>a[mr][mc])
{ mr=k;
}
}
System.out.println("");
if(i==mr&&mc==j)
{ flag=1;

28
System.out.println("saddle point is "+a[mr][mc]);
System.out.println(" row= "+i+" column= "+j);
}
}
}
if(flag==0)
System.out.println("no saddle point found");
}
}
Output:
enter the row size
2
enter the column size
3
enter the array elements
2
6
7
1
4
9
267
149
saddle point is 2
row= 0 column= 0

Question 11
Define class 'MyNumber' with following specifications:-
Data Members:-
n - to store no
Member Functions:-
readdata( ): to input n
boolean palindrome( ): to return true if no. is palindrome otherwise false
boolean automorphic( ): to return true if no. is automorphic otherwise false
boolean armstrong( ): to return true if no. is armstrong otherwise false
boolean magical( ): to return true if no. is magical otherwise false
voidshowall( ): to display whether the no. one of the above

PROGRAM
import java.io.*;
29
class MyNumber
{
int n;
void readdata( )throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter no.: ");
n = Integer.parseInt(in.readLine( ));
}
boolean palindrome( )
{
int a=n,b=0;
for(; a>0; b=b*10+a%10,a/=10);
if(n==b)
return true;
else
return false;
}
boolean magical( )
{
int a=n;
for(; a>9; a=a%10+a/10);
if(a==1)
return true;
else
return false;
}
boolean automorphic( )
{
int a=n,b=n,j=10,k=0;
for(; a>0; k=(b*b)%j,j*=10,a/=10);
if(k==b)
return true;
else
return false;
}
boolean armstrong( )
{
int a=n,c=0;

30
for(; a>0; c+=(int)Math.pow(n%10,3),a/=10);
if(n==c)
return true;
else
return false;
}
void showall( )
{
if(magical( ))
System.out.println("no. is magical: ");
if(palindrome( ))
System.out.println("no. is palindrome: ");
if(automorphic( ))
System.out.println("no. is automorphic: ");
if(armstrong( ))
System.out.println("no. is armstrong: ");
}
}
class number
{
public static void main(String args[ ])throws Exception
{
MyNumber a=new MyNumber( );
a.readdata( );
a.showall( );
}
}
Output Of Program
Enter no.: 1
no. is magical:
no. is palindrome:
no. is automorphic:
no. is armstrong:

Question 12
WAP to input String. Display the words, whose frequency is more than one in the String.
Sample Input: MAHINDRA SINGH DHONI IS THE CAPTAIN OF THE INDIAN CRICKET TEAM.
SAURAV GANGULY IS THE EX - CAPTAIN OF THE INDIAN CRICKET TEAM.
Sample Output: THE , OF , INDIAN , CRICKET , TEAM , IS,CAPTAIN.

31
A class find is declared to perform the above operations. Some of the members of class are
given below
Class Name: find
Data members:
Str: String type to store the sentence
Word[ ]: string type array to store words
Len: to store length of string
Member functions:
Void input( ) : function to input the string
Void delete(String) : to delete the duplicate words
Void print( ) : to print the words whose frequency is more than one.
Specify the class find giving details of constructors and functions. Write the main( ) function
to create an object of find type and print the desired result.

PROGRAM
import java.io.*;
class ques12
{ public static void main(String args[ ])throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
find obj=new find( );
obj.input( );
obj.print( );
}
}
class find
{ String str; int len; String word[ ]=new String[50];
void input( )throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the sentence");
str=in.readLine( );
len=str.length( );
}
void delete(String s)
{ int f=0;
for(int i=0; i<len; i++)
{ if(word[i].compareTo(s)==0)
{ for(int n=i; n<(len-1); n++)
{ word[n]=word[n+1];
}
i--;
32
len--;
}
}
}
void print( )
{ int f=0;
int t=0;
str=str+" ";
String temp="";
for(int i=0; i<=len; i++)
{ char ch=str.charAt(i);
if(ch!=' ')
{ temp+=ch;
}
else
{ word[t]=temp; ;
t++;
temp="";
}
}
len=t;
for(int j=0; j<(len-1); j++)
{ f=1;
for(int k=j+1; k<len; k++)
{ if((word[j].compareTo(word[k]))==0)
f++;
}
if(f>1)
{ System.out.println(word[j]+" ");
delete(word[j]);
}
}
}
}
Output:
enter the sentence
This is a test run. A test of the program is required.
is
test

33
Question 13
WAP to display magical matrix of given size

PROGRAM
import java.io.*;
class magicalodd
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("\n\tEnter size: ");
int n = Integer.parseInt(in.readLine( ));
int a[ ][ ] = new int[n][n],i,r=0,c=n/2,r1,c1;
for(i=1; i<=n*n; i++)
{ a[r][c] = i;
r1=r; c1 = c;
r--;
c++;
if(r==-1)
r = n-1;
if(c>n-1)
c = 0;
if(a[r][c]!=0)
{
r = r1;
c = c1;
r++;
if(r>n-1)
r = 0;
}
}
System.out.println("\n\tMAGICAL MATRIX: ");
for(r=0; r<n; r++)
{
for(c=0; c<n; c++)
System.out.print("\t"+a[r][c]);
System.out.println( );
}
}

34
}
Output Of Program
Enter size: 3
MAGICAL MATRIX:
816
357
492

Question 14
Define a class digit with following data members
Class Name: Digit
Data Members: int n
Member functions:
void input( ): to input max 3 digit number
int check(int y): returns 1 if y is positive else it return 0
int length(int u): returns length of u.
void print( ): check that number is of valid length and print in following format
Example
Input: 176
Output: positive One Hundred and Seventy Six
Input: -96
Output: negative Ninety Six

PROGRAM
import java.io.*;
class ques14
{ public static void main(String args[ ])throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
digit obj=new digit( );
obj.input( );
obj.print( );
}
}
class digit
{ int n;
void input( )throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number of maximum 3 digit");
n=Integer.parseInt(in.readLine( ));
35
}
int check(int y)
{ if(y>=0)
{
return 1;
}
else
{
return 0;
}
}
int length(int u)
{
int c=0,r=0;
while(u!=0)
{ u=u/10;
c++;
}
return c;
}
void print( )
{
int t=n;
int l,ans,n1,n2,n3,n4,n5;
ans=check(t);
if(ans==1)
{
System.out.print("positive"+" ");
System.out.println( );
}
else
{
System.out.print("negative"+" ");
t=t*-1;
System.out.println( );
}
l=length(t);
String a[ ]={" ","one","two","three","four","five","six","seven","eight","nine"};

36
String b[ ]= {"
“,"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eightee
n","ninteen"};
String c[ ]= {"
","ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
if(l==1)
{
System.out.print(a[t]+" ");
System.out.println( );
}
if(l==2)
{
n1=t%10;
n2=t/10;
if(t>10&&t<20)
System.out.print(b[n1]);
else
System.out.print(c[n2]+" "+a[n1]+" ");
System.out.println( );
}
if(l==3)
{
n1=t%10;
n2=t/10;
n3=n2%10;
n4=n2/10;
n5=t%100;
if(t%100==0)
System.out.println(a[n4]+" hundred ");
else if(n5>10&&n5<20)
System.out.print(a[n4]+" hundred and"+" "+b[n5-10]+" ");
else
System.out.print(a[n4]+" hundred and"+" "+c[n3]+" "+a[n1]+" ");
System.out.println( );
}
}
}
Output:
enter the number of maximum 3 digit

37
777
positive
seven hundred and seventy seven

Question 15
WAP to search an element using linear searching

PROGRAM
import java.io.*;
class linearsearch
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("\n\n\tEnter size: ");
int i,a[ ] = new int[Integer.parseInt(in.readLine( ))];
System.out.print("\n\tStart Entering elements:\n");
for(i=0; i<a.length; i++)
a[i] = Integer.parseInt(in.readLine( ));
System.out.print("\n\tEnter Key:");
int key = Integer.parseInt(in.readLine( ));
for(i=0; i<a.length; i++)
if(a[i]==key)
{
System.out.println("\n\tKey at position: "+(i+1));
System.exit(0);
}
System.out.print("\n\tKey doesn't occur");
}
}
Output Of Program
Enter size: 3
Start Entering elements:
3
2
1
Enter Key:4
Key doesn't occur

38
Question 16
Define a class Dequeue
Class Name : Dequeue
Data members:
job[ ] : array to integers to hold dequeue elements
Newjob : To add a new job into the array
Capacity : The maximum capacity of the integer array
Front : To point to the index of the front
Rear : To point to the index of the last
Member Functions:
Dequeue( int n) : Constructor to initialize the data member Capacity = n, Front = Rear=-1
and call the function createJob ( )
void createJob ( ) : To create an array to hold the dequeue elements.
void addLast ( ) : Adds the new printing job to the end of the last job, if possible,
otherwise displays the message “job is full, cannot add anymore”
void removelast( ) : Removes the job from the last if the job is not empty, otherwise
displays the message “job is empty”
void addFirst ( ) : Adds the new printing job to the first index if possible, otherwise
displays the message “job is full, cannot add anymore”
void removeFirst ( ): Removes the printing job from the front if the job is not empty,
otherwise displays the message “job is empty”
also write main( ) for above class.

PROGRAM
import java.io.*;
class prg16
{ public static void main(String args[ ])throws IOException
{ BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER THE SIZE OF THE QUEUE");
int size=Integer.parseInt(k.readLine( ));
Dequeue obj=new Dequeue(size);
int flag=1;
do
{ System.out.println("ENTER THE ACTION YOU WANT TO TAKE");
System.out.println("1: ENTER ELEMENT FROM REAR OF THE QUEUE");
System.out.println("2: REMOVE ELEMENT FROM REAR OF THE QUEUE");
System.out.println("3: ENTER ELEMENT FROM FRONT OF THE QUEUE");
System.out.println("4: REMOVE ELEMENT FROM FRONT OF THE QUEUE");
int choice=Integer.parseInt(k.readLine( ));

39
switch (choice)
{ case 1:
System.out.println("ENTER THE ELEMENT TO BE ADDED");
int n1=Integer.parseInt(k.readLine( ));
obj.Newjob=n1;
obj.addLast( );
break;
case 2:
obj.removeLast( );
break;
case 3:
System.out.println("ENTER THE ELEMENT TO BE ADDED");
int n2=Integer.parseInt(k.readLine( ));
obj.Newjob=n2;
obj.addFirst( );
break;
case 4:
obj.removeFirst( );
break;
default:
System.out.println("WRONG CHOICE");
}
System.out.println("FOR AGAIN PERFORMING OPERATIONS ENTER 1 FOR ENDING
ENTER 0");
flag=Integer.parseInt(k.readLine( ));
}
while(flag==1);
}
}
class Dequeue
{ int job[ ];
int Newjob;
int Capacity;
int Front;
int Rear;
Dequeue(int n)
{ Capacity=n;
Front=-1;
Rear=-1;

40
createJob( );
}
void createJob( )
{ job=new int[Capacity];
}
void addLast( )
{ if(Rear==Capacity-1)
{ System.out.println("JOB IS FULL ,CANNOT ADD ANY MORE");
}
else
{ if((Rear==-1)&&(Front==-1))
{ Rear++;
Front++;
}
else
Rear++;
}
job[Rear]=Newjob;
}

void removeLast( )
{ if((Rear==-1)&&(Front==-1))
{ System.out.println("JOB IS EMPTY");
}
else
{ if(Front==Rear)
{ Front=-1;
Rear=-1;
}
else
Front--;
}
}
void addFirst( )
{ if(Front<=0)
{ System.out.println("JOB IS FULL ,CANNOT ADD ANY MORE");
}
else
{ Front--;
job[Front]=Newjob;
41
}
}
void removeFirst( )
{ if((Rear==-1)&&(Front==-1))
{ System.out.println("JOB IS EMPTY");
}
else
{ if(Front==Rear)
{
Front=-1;
Rear=-1;
}
else
{
Front++;
}
}
}
}
Output:
ENTER THE SIZE OF THE QUEUE
3
ENTER THE ACTION YOU WANT TO TAKE
1: ENTER ELEMENT FROM REAR OF THE QUEUE
2: REMOVE ELEMENT FROM REAR OF THE QUEUE
3: ENTER ELEMENT FROM FRONT OF THE QUEUE
4: REMOVE ELEMENT FROM FRONT OF THE QUEUE
1
ENTER THE ELEMENT TO BE ADDED
5
FOR AGAIN PERFORMING OPERATIONS ENTER 1 FOR ENDING
ENTER 0
1
ENTER THE ACTION YOU WANT TO TAKE
1: ENTER ELEMENT FROM REAR OF THE QUEUE
2: REMOVE ELEMENT FROM REAR OF THE QUEUE
3: ENTER ELEMENT FROM FRONT OF THE QUEUE
4: REMOVE ELEMENT FROM FRONT OF THE QUEUE
1

42
ENTER THE ELEMENT TO BE ADDED
6
FOR AGAIN PERFORMING OPERATIONS ENTER 1 FOR ENDING
ENTER 0
1
ENTER THE ACTION YOU WANT TO TAKE
1: ENTER ELEMENT FROM REAR OF THE QUEUE
2: REMOVE ELEMENT FROM REAR OF THE QUEUE
3: ENTER ELEMENT FROM FRONT OF THE QUEUE
4: REMOVE ELEMENT FROM FRONT OF THE QUEUE
2
FOR AGAIN PERFORMING OPERATIONS ENTER 1 FOR ENDING
ENTER 0
0

Question 17
Define a class Trr with following data members:
int arr [4][4]
And following functions:
void input( ): to input a 4X4 matrix
void transpose( Trr M): to print transpose of matrix M
void print( ): to print the matrix.
Also write main( ) for above class

PROGRAM
import java.io.*;
class ques17
{ public static void main(String args[ ])throws IOException
{ BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
Trr obj=new Trr( );
System.out.println("enter the matrix to be transposed");
Trr obj2=new Trr( );
obj2.input( );
obj.transpose(obj2);
}
}
class Trr
{ int arr[ ][ ]=new int[4][4];
void input( )throws IOException
43
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int i,j;
for(i=0; i<4; i++)
{ for(j=0; j<4; j++)
{ arr[i][j]=Integer.parseInt(in.readLine( ));
}
}
}
void transpose(Trr M)
{ int i,j,k,l;
for(i=0; i<4; i++)
{ for(j=0; j<4; j++)
{ M.arr[i][j]=M.arr[j][i];
}
}
System.out.println("The transposed array is");
System.out.println( );
for(k=0; k<4; k++)
{ for(l=0; l<4; l++)
{ System.out.print(M.arr[k][l]+" ");
}
System.out.println( );
}
}
void print( )
{ int i,j;
for(i=0; i<4; i++)
{ for(j=0; j<4; j++)
{ System.out.print(arr[i][j]+" ");
} System.out.println( );
}
}
}
Output:
enter the matrix to be transposed
1
2
3
4

44
5
6
7
8
9
10
11
12
13
14
15
16
The transposed array is
1 5 9 13
5 6 10 14
9 10 11 15
13 14 15 16

Question 18
Define a class Matrix with the following specifications:
Class Name: Matrix
Data Members:
int N  order of matrix
int arr[ ][ ]  matrix of order NXN
Member Functions:
Matrix(int size): constructor to assign size to N
void input( ): to input matrix of order NXN
Matrix add(Matrix A): to return sum of matrix A and the current object matrix.
int SumBoundaryEle( ):to return the sum of boundary element of current object matrix.
void print( ): to print the matrix
Also write main function.

PROGRAM
import java.io.*;
class prg18
{ public static void display( )throws IOException
{ BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER THE SIZE OF FIRST MATRIX");
int N1=Integer.parseInt(k.readLine( ));
Matrix obj1=new Matrix(N1); obj1.input( );
45
System.out.println(" ENTER THE SIZE OF SECOND MATRIX");
int N2=Integer.parseInt(k.readLine( ));
Matrix obj2=new Matrix(N2); obj2.input( );
System.out.println("first matrix"); obj1.print( );
System.out.println("second matrix"); obj2.print( );
obj2=obj1.add(obj2);
System.out.println("add matrix"); obj2.print( );
int s=obj1.SumBoundaryEle( );
System.out.println("sum of boundary elements of first matrix="+s);
}
}
class Matrix
{ int N; int arr[ ][ ];
Matrix(int size)
{ N=size;
arr=new int[N][N];
}
void input( )throws IOException
{ BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER THE MATRIX");
for(int i=0; i<N; i++)
{ for(int j=0; j<N; j++)
arr[i][j]=Integer.parseInt(k.readLine( ));
}
}
Matrix add(Matrix A)
{ Matrix obj=new Matrix(N);
if(A.N!=N)
System.out.println("Addition Not valid");
else
{ for(int i=0; i<N; i++)
{ for(int j=0; j<N; j++)
obj.arr[i][j]=arr[i][j]+A.arr[i][j];
}
}
return obj;
}
int SumBoundaryEle( )
{ int sum=0;

46
for(int i=0; i<N; i++)
{ for(int j=0; j<N; j++)
{ if ((i==0)||(j==0)||(i==N-1)||(j==N-1))
sum+=arr[i][j];
}
}
return sum;
}
void print( )
{ for(int i=0; i<N; i++)
{ for(int j=0; j<N; j++)
System.out.print(arr[i][j]);
System.out.println( );
}
}
}
Output:
ENTER THE SIZE OF FIRST MATRIX
2
ENTER THE MATRIX
1
2
5
4
ENTER THE SIZE OF SECOND MATRIX
2
ENTER THE MATRIX
9
8
5
6
first matrix
12
54
second matrix
98
56
add matrix
110

47
110
sum of boundary elements of first matrix=12

Question 19
PROGRAM
import java.io.*;
class ATM
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("Enter amount to change: ");
int n = Integer.parseInt(in.readLine( )),d=0,k=0,i=0;
int a[ ] = {1000,500,100,50,20,10,5,2,1};
while(n>0)
{
while(n>a[i]||d!=0&&n>=a[i])
{
n -= a[i];
k++;
d++;
}
if(k>0)
System.out.println("Rs. "+a[i]+"--->"+k+" notes");
k=0;
i++;
}
}
}
Output Of Program
Enter amount to change: 5
Rs. 2--->2 notes
Rs. 1--->1 notes

Question 20
Define a class Duplicate to pack an array of 10 integers which are sorted (To pack means to
remove all duplicates from the array).
Example
If the given array has the following sorted numbers:
Input: 1 2 3 3 4 4 4 5 6 6 the resultant array should contain each elements ones.
48
Output: 1 2 3 4 5 6

Some of the members of the class are given below: -


Class Name: Duplicate
Data members
num[ ]: integer array with 10 integers sorted
Functions/methods:
void readList( ): to enter elements of the array in sorted order.
void packList( ): to remove the duplicates from the array.
void dispList( ): to display the array of integers without the duplicates.

Specify the class Duplicate giving the details of the function void readList( ), void packList( )
and void dispList( ). The main function need not be written.

PROGRAM
import java.io.*;
class ques20
{ public static void main(String args[ ])throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
duplicate obj=new duplicate( );
obj.readlist( );
obj.packlist( );
obj.displist( );
}
}
class duplicate
{ int num[ ]=new int[10];
void readlist( )throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the array elements in sorted order");
System.out.println( );
int i;
for(i=0; i<10; i++)
{ num[i]=Integer.parseInt(in.readLine( ));
}
}
void packlist( )
{ int i,j,k; int len=num.length;
for(i=0; i<len-1; i++)
49
{ for(j=i+1; j<len; j++)
{ if(num[i]==num[j])
{ for(k=j; k<(len-1); k++)
{ num[k]=num[k+1];
len--;
j--;
}
}
}
}
}
void displist( )
{
System.out.println("The deleted array is= ");
System.out.print(num[0]+" ");
int i;
for(i=1; i<num.length; i++)
{
if(num[i-1]==num[i])
break;
System.out.print(num[i]+" ");
}
}
}
Output:
enter the array elements in sorted order
1
2
3
4
4
5
6
7
7
8
The deleted array is=
12 3 6

50
Question 21
Define a class 'Stack' with following specification:-
Data Members:-
a[ ]: array to store elements
size: to store size of array
top: to store and delete element at top position
Member functions:-
Stack(int s): to initiallise array with size & top=-1
boolean isEmpty( ): to return true if array is empty
boolean isFull( ): to return true if array is full
void Push(int item): to push item at top position
void Pop( ): to pop element at top position
void display( ): to display elements from top to 0

PROGRAM
import java.io.*;
class Stack
{
int size,top,a[ ];
Stack(int s)
{
size = s;
a = new int[s];
top = -1;
}
boolean isEmpty( )
{
if(top==-1)
return true;
return false;
}
boolean isFull( )
{
if(top==size-1)
return true;
return false;
}
void Push(int item)
{

51
if(isFull( ))
System.out.println("Filled Upto The Brim");
else
a[++top] = item;
}
void Pop( )
{
if(isEmpty( ))
System.out.println("Asking From Beggar");
else
top--;
}
void display( )
{
System.out.print("Stack is:----> ");
for(int i=top; i>=0; i--)
System.out.print(a[i]+"\t");
System.out.println( );
}
}
class teststack
{
public static void main(String args[ ])throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter size: ");
Stack a = new Stack(Integer.parseInt(in.readLine( ))); int n;
System.out.println("1. Insert\n2. Delete\n3. Display\n4. Exit");
do
{
System.out.print("Enter choice: ");
n=Integer.parseInt(in.readLine( ));
switch(n)
{
case 1:
System.out.print("Enter item: ");
a.Push(Integer.parseInt(in.readLine( )));
break;
case 2:

52
a.Pop( );
break;
case 3:
a.display( );
break;
case 4:
System.exit(0);
}
} while(n!=4);
}
}
Output Of Program
Enter size: 1
1. Insert
2. Delete
3. Display
4. Exit
Enter choice: 1
Enter item: 2
Enter choice: 1
Enter item: 3
Filled Upto The Brim
Enter choice: 3
Stack is:----> 2
Enter choice: 2
Enter choice: 2
Asking From Beggar

Question 22
Define a class 'Queue' with following specification:-
Data Members:-
a[ ]: array to store elements
size: to store size of array
rear: store position of push
front: store position of pop
Member functions:-
Stack(int s): Parameterised Constructor
boolean isEmpty( ): to return true if array is empty
boolean isFull( ): to return true if array is full

53
void Push(int item): to push item at rear position
void Pop( ): to pop element at front position
void display( ): to display elements from front to rear

PROGRAM
import java.io.*;
class Queue
{
int size,front,rear,a[ ];
Queue(int s)
{
size = s; a = new int[s]; front = rear = -1;
}
boolean isEmpty( )
{
if(front==-1 || front==rear+1)
return true;
return false;
}
boolean isFull( )
{
if(rear==size-1)
return true;
return false;
}
void Push(int item)
{
if(isFull( ))
System.out.println("Filled Upto The Brim");
else
{
if(rear==-1)
rear = front = 0;
else
++rear;
a[rear] = item;
}
}
void Pop( )
{
54
if(isEmpty( ))
{
front = rear= -1;
System.out.println("Asking From Beggar");
}
else
front++;
}
void display( )
{
System.out.print("Queue is:----> ");
if(front>-1)
{
for(int i=front; i<=rear; i++)
System.out.print(a[i]+"\t");
}
System.out.println( );
}
}
class testqueue
{
public static void main(String args[ ])throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter size: ");
Queue a=new Queue(Integer.parseInt(in.readLine( ))); int n;
System.out.println("1. Insert\n2. Delete\n3. Display\n4. Exit");
do
{
System.out.print("Enter choice: ");
n = Integer.parseInt(in.readLine( ));
switch(n)
{
case 1:
System.out.print("Enter item: ");
a.Push(Integer.parseInt(in.readLine( )));
break;
case 2:
a.Pop( );

55
break;
case 3:
a.display( );
break;
case 4:
System.exit(0);
}
} while(n!=4);
}
}
Output Of Program
Enter size: 1
1. Insert
2. Delete
3. Display
4. Exit
Enter choice: 1
Enter item: 2
Enter choice: 1
Enter item: 3
Filled Upto The Brim
Enter choice: 3
Queue is:----> 2
Enter choice: 2
Enter choice: 2
Asking From Beggar
Enter choice: 1
Enter item: 3
Enter choice: 4

Question 23
Define a class 'Angle' with following classification:-
Data Member:-
deg: an integer to degrees of angle
min: an integer to minutes of angle
sec: an integer to seconds of angle
Member Function:-
Angle( ): Default constructor
Angle(int d,int m,int s): Parameterised constructor

56
void readAngle( ): to input angle
void showAngle( ): to display angle
int isValidAngle: to return 1 if angle is valid else 0
Angle add(Angle a): to return an Angle with sum of 'a' and calling object
Angle Diff(Angle a): to return an Angle with difference of 'a' and calling object
int compare(Angle a): to return 1 if calling angle is greater or else -1 if 'a' greater
otherwise 0

PROGRAM
import java.io.*;
class Angle
{
int deg,min,sec;
Angle( )
{
deg = min = sec = 0;
}
Angle(int d,int m,int s)
{
deg = d;
min = m;
sec = s;
}
void readAngle( ) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n\n\tEnter Data About An Angle");
System.out.print("\n\tEnter Degrees:");
deg = Integer.parseInt(in.readLine( ));
System.out.print("\tEnter Minutes:");
min = Integer.parseInt(in.readLine( ));
System.out.print("\tEnter Seconds:");
sec = Integer.parseInt(in.readLine( ));
}
void showAngle( )
{ System.out.print("\n\n\tAngle Is:"+deg+
(char)248+min+"'"+sec+"\"");
}
int isValidAngle( )
{ if(deg<0 || min>59 || min<0 || sec>59 || sec<0)
57
return 0;
return 1;
}
int compare(Angle a)
{ long s1 = deg*3600+min*60+sec,s2=a.deg*3600+a.min*60+a.sec;
if(s1>s2)
return 1;
if(s1<s2)
return -1;
return 0;
}
Angle add(Angle a)
{ Angle ret = new Angle( );
ret.sec = sec+a.sec;
ret.min = min+a.min+ret.sec/60;
ret.deg = deg+a.deg+ret.min/60;
ret.sec %= 60;
ret.min %= 60;
return ret;
}
Angle Diff(Angle a)
{
int s = (deg*3600+min*60+sec)-(a.deg*3600+a.min*60+a.sec);
if(s<0)
s = s*-1;
return new Angle(s/3600,(s%3600)/60,(s%3600)%60);
}
}
class Angle
{ public static void main(String args[ ])throws Exception
{
Angle a = new Angle( ),b = new Angle( );
a.readAngle( );
b.readAngle( );
a.showAngle( );
b.showAngle( );
a.Diff(b).showAngle( );
}
}

58
Output Of Program
Enter Data About An Angle
Enter Degrees:10
Enter Minutes:20
Enter Seconds:30
Enter Data About An Angle
Enter Degrees:20
Enter Minutes:30
Enter Seconds:40
Angle Is:10ø20'30"
Angle Is:20ø30'40"
Angle Is:10ø10'10"

Question 24
Define a 'Binomial' class with following specification:-
Data Members:-
x: to store value of x in (x + a)^n
a: to store value of a in (x + a)^n
n: to store limit
Member Functions:-
void readdata( ): To input x,a,n
long factorial(int):To return factorial of n
long nCr(int,int): To return nCr
void sumseries( ):To return value of (x+a)^n

PROGRAM
import java.io.*;
class Binomial
{
int x,a,n;
void readdata( )throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter limit: ");
n = Integer.parseInt(in.readLine( ));
System.out.print("Enter value of x:");
x = Integer.parseInt(in.readLine( ));
System.out.print("Enter value of a:");
a = Integer.parseInt(in.readLine( ));
}
59
long factorial(int b)
{ if(b==0 || b==1)
return 1;
else return b*factorial(b-1);
}
long nCr(int l,int r)
{ return factorial(l)/(factorial(r)*factorial(l-r));
}
void sumseries( )
{ long sum=0;
for(int i=0; i<=n; i++)
{ sum += nCr(n,i)*(long)Math.pow(x,n-i)*(int)Math.pow(a,i);
}
System.out.println("Sum of "+"("+x+"+"+a+")"+"^"+n+" is: "+sum);
}
}
class Bin
{ public static void main(String args[ ])throws Exception
{ Binomial a=new Binomial( );
a.readdata( );
a.sumseries( );
}
}
Output Of Program
Enter limit: 6
Enter value of x:2
Enter value of a:1 Sum of (2+1)^6 is: 729 */

Question 25
Define a class 'complex' with following specification:-
Data Member:-
real: to store real part
imag:to store imaginary part
Member Function:-
complex(double x,double y): Parameterised constructor
complex add(complex z): to return 'this' plus z as complex
complex sub(complex z): to return 'this' minus z as complex
complex multiply(complex z):to return 'this' product z as complex
complex divide(complex z): to return 'this' division z as complex

60
void display( ): to display 'this' in complex number format

PROGRAM
class complex
{
double real,imag;
complex( )
{
real = imag = 0;
}
complex(double x,double y)
{
real = x;
imag = y;
}
void display( )
{
if(imag>0)
System.out.println(real+"+"+imag+"i\n");
else
System.out.println(real+""+imag+"i\n");
}
complex add(complex z)
{
return new complex(real+z.real,imag+z.imag);
}
complex sub(complex z)
{
return new complex(real-z.real,imag-z.imag);
}
complex multiply(complex z)
{
return new complex(real*z.real-imag*z.imag,
real*z.imag+imag*z.real);
}
complex divide(complex z)
{
complex temp = new complex(real,imag);
complex conjugate = new complex(z.real,-(z.imag));
z = z.multiply(conjugate);
61
temp=temp.multiply(conjugate);
temp.real /= z.real;
temp.imag /= z.real;
return temp;
}
}
class compl
{
public static void main(String args[ ])
{
complex a = new complex(3,2),b = new complex(2,-3);
a.display( );
b.display( );
System.out.print("Sum is: ");
a.add(b).display( );
System.out.print("Difference is: ");
a.sub(b).display( );
System.out.print("Product is: ");
a.multiply(b).display( );
System.out.print("Division is: ");
a.divide(b).display( );
}
}
Output Of Program
3.0+2.0i
2.0-3.0i
Sum is: 5.0-1.0i
Difference is: 1.0+5.0i
Product is: 12.0-5.0i
Division is: 0.0+1.0i

Question 26
Define Class 'Conversion' with following specifications:-
Member Functions:-
void deci2ne( ): to convert decimal no into base equivalent
void ne2deci( ): to convert base no. to decimal equivalent
void ne2ne( ): to convert any base no. to any base
void hexa2binary( ): to convert hexadecimal no. to binary equivalent
void octal2binary( ): to convert octal no. to binary equivalent

62
void binary2hexa( ): to convert binary no. to hexadecimal equivalent
void binary2octal( ): to convert binary no. to octal equivalent

PROGRAM
class Conversion
{
void deci2ne(int n,int b)
{
String sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String s = "";
for(; n>0; s=sym.charAt(n%b)+s,n/=b);
System.out.println(s);
}
void ne2deci(String s,int b)
{
String sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int l=0,n=0;
for(; l<s.length( ); n=n*b+sym.indexOf(s.charAt(l)),l++);
System.out.println(n);
}
void ne2ne(String s,int b1,int b)
{
String sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String ans = ""; int n=0,l=0;
for(; l<s.length( ); n=n*b1+sym.indexOf(s.charAt(l)),l++);
for(; n>0; ans=sym.charAt(n%b)+ans,n/=b);
System.out.println(ans);
}
void hexa2binary(String s)
{
String sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String hexa[ ]={"0000","0001","0010","0011","0100","0101","0110",
"0111","1000","1001","1010","1011","1100","1101","1110","1111"};
int l=0;
String ans="";
for(; l<s.length( ); ans=ans+hexa[sym.indexOf(s.charAt(l))],l++);
System.out.println(ans);
}
void octal2binary(String s)
{
63
String sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String octal[ ] = {"000","001","010","011","100","101","110","111"};
int l=0;
String ans="";
for(; l<s.length( ); ans=ans+octal[sym.indexOf(s.charAt(l))],l++);
System.out.println(ans);
}
void binary2octal(String s)
{
String oct[ ] = {"000","001","010","011","100","101","110","111"};
String ans="",s1=""; int i=0,j=0;
while(s.length( )%3!=0)
s='0'+s;
while(s.length( )!=0)
{
s1 = s.substring(0,3);
for(j=0; j<8; j++)
{
if(s1.equals(oct[j]))
ans = ans+j;
}
s = s.substring(3);
}
System.out.println(ans);
}
void binary2hexa(String s)
{
String sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String hexa[ ]={"0000","0001","0010","0011","0100","0101","0110",
"0111","1000","1001","1010","1011","1100","1101","1110","1111"};
String ans="",s1=""; int i=0,j=0;
while(s.length( )%4!=0)
s='0'+s;
while(s.length( )!=0)
{
s1 = s.substring(0,4);
for(j=0; j<16; j++)
{
if(s1.equals(hexa[j]))

64
ans = ans+sym.charAt(j);
}
s = s.substring(4);
}
System.out.println(ans);
}
}
class aconversion
{
public static void main(String args[ ])
{
Conversion a = new Conversion( );
System.out.print("(41567359,35):deci2ne:"); a.deci2ne(41567359,35);
System.out.print("(ROHIT,35): ne2deci: "); a.ne2deci("ROHIT",35);
System.out.print("(ROHIT,35,10):ne2ne: "); a.ne2ne("ROHIT",35,10);
System.out.print("(ABC): hexa2binary: "); a.hexa2binary("ABC");
System.out.print("(345): octal2binary: "); a.octal2binary("345");
System.out.print("(1010011): binary2octal: ");
a.binary2octal("1010011");
System.out.print("(101010111100): binary2hexa: ");
a.binary2hexa("101010111100");
}
}
Output Of Program
(41567359,35): deci2ne: ROHIT
(ROHIT,35): ne2deci: 41567359
(ROHIT,35,10): ne2ne: 41567359
(ABC): hexa2binary: 101010111100
(345): octal2binary: 011100101
(1010011): binary2octal: 123
(101010111100): binary2hexa: ABC

Question 27
Define a class 'Dec_Bin' with following specifications:-
Data Members:-
n: to store decimal no.
s: to store equivalent binary no
i: incremental value of power
Member Functions:-

65
void getdata( ): to input decimal no
void recursive( ): recursive method to compute binary of no
void display( ): to display decimal no and its binary equivalent

PROGRAM
import java.io.*;
class Dec_Bin
{
int n,s,i;
void getdata( )throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a no.: ");
n = Integer.parseInt(in.readLine( ));
recursive(n);
display( );
}
void recursive(int n)
{
if(n>0)
{
s = s+(n%2)*(int)Math.pow(10,i++);
recursive(n/2);
}
}
void display( )
{
System.out.print("Decimal no.: "+n+" "+"
\nBinary equaivalent is: "+s);
}
}
class dec_bin
{
public static void main(String args[ ])throws Exception
{
Dec_Bin a=new Dec_Bin( );
a.getdata( );
}
}

66
Output Of Program
Enter a no.: 14
Decimal no.: 14
Binary equaivalent is: 1110

Question 28
Define class 'duplicate' with following specifications:-
Data Members:-
arr[ ]: to store sorted elements
size: to store size of array
Member Functions:-
void readList( ): to enter elements
void packList( ): to remove duplicates
void dispList( ): to display array the array

PROGRAM
import java.io.*;
class duplicate
{
int arr[ ],size;
void readList( )throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter size: ");
size=Integer.parseInt(in.readLine( ));
System.out.println("Enter elements: ");
arr = new int[size];
for(int i=0; i<size; i++)
arr[i] = Integer.parseInt(in.readLine( ));
}
void packList( )
{
int i,j=0;
for(i=0; i<size-1; i++)
{
if(arr[i]!=arr[i+1])
arr[j++] = arr[i];
}
arr[j++] = arr[i];
size = j;
67
}
void dispList( )
{
System.out.print("Array is: ");
for(int i=0; i<size; i++)
System.out.print(arr[i]+" ");
System.out.println( );
}
}
class dupli
{
public static void main(String args[ ])throws Exception
{
duplicate b=new duplicate( );
b.readList( );
b.dispList( );
b.packList( );
b.dispList( );
}
}
Output Of Program
Enter size: 4
Enter elements:
4
3
2
2
Array is: 4 3 2 2
Array is: 4 3 2

Question 29
Define a class 'Fraction' with following classification:-
Data Member:-
num: an integer to store numerator
den: an integer to store denominator
Member Functions:-
void readFraction( ): to input Fraction
void showFraction( ): to display Fraction
int hcf(int a,int b): to return HCF of a & b

68
int lcm(int a,int b): to return LCM of a & b
void reduce( ): to reduce the fraction to co-prime factor
Fraction addFraction(Fraction f): to return sum of 'f' and calling object as a Fraction
int compare(Fraction f): to return 1 if calling fraction is greater or else -1 if 'f'
greater otherwise 0

PROGRAM
import java.io.*;
class Fraction
{
int num,den=0;
void readFraction( ) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n\n\tEnter Numerator:");
num = Integer.parseInt(in.readLine( ));
while(den==0)
{
System.out.print("\n\tEnter Denominator(<>0):");
den = Integer.parseInt(in.readLine( ));
}
if(den<0)
{
num = num*-1;
den = den*-1;
}
}
void showFraction( )
{
if(den==0)
System.out.print("\n\tFraction Is Undefined");
else
{
System.out.print("\n\tFraction Is:"+num);
if(den!=1)
System.out.print("/"+den);
}
}
int lcm(int a,int b)
{
69
int c=a,d=b;
while(a!=b)
if(a<b)
a = a+c;
else
b = b+d;
return a;
}
int hcf(int a,int b)
{
while(a!=b)
if(a<b)
b = b - a;
else
a = a - b;
return a;
}
void reduce( )
{
int cut = hcf((int)Math.abs(num),den);
num = num/cut;
den = den/cut;
}
Fraction addFraction(Fraction f)
{
Fraction ret = new Fraction( );
ret.num = num*(lcm(den,f.den)/den)+ f.num*(lcm(den,f.den)/f.den);
ret.den = lcm(den,f.den);
ret.reduce( );
return ret;
}
int compare(Fraction f)
{
if(num*f.den>f.num*den)
return 1;
if(num*f.den<f.num*den)
return -1;
return 0;
}

70
}
class Fract
{
public static void main(String args[ ])throws Exception
{
Fraction a=new Fraction( ),b=new Fraction( );
a.readFraction( ); b.readFraction( );
a.reduce( ); a.showFraction( );
b.reduce( ); b.showFraction( );
a.addFraction(b).showFraction( );
}
}

Output Of Program
Enter Numerator:1000
Enter Denominator(<>0):3000
Enter Numerator:2000
Enter Denominator(<>0):3000
Fraction Is:1/3
Fraction Is:2/3
Fraction Is:1

Question 29
Define class 'GPseries' with following specifications:-
Date Members:-
a: to store first term
r: to store common ratio
n: to store limit
Member Functions:-
void readdata( ): to input a,d,n
long nThterm(int): to return nTh term of the series
long sum( ): to return sum of the series
void showseries( ): to display the series and sum

PROGRAM
import java.io.*;
class GPseries
{
int a,r,n;
void readdata( )throws Exception
71
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter first term: ");
a = Integer.parseInt(in.readLine( ));
System.out.print("Enter common ratio: ");
r = Integer.parseInt(in.readLine( ));
System.out.print("Enter limit: ");
n = Integer.parseInt(in.readLine( ));
}
long nThterm(int b)
{
return a*(int)Math.pow(r,b-1);
}
long sum( )
{
return a*(int)(Math.pow(r,n)-1)/(r-1);
}
void showseries( )
{
for(int i=1; i<=n; i++)
System.out.print(nThterm(i)+" ");
System.out.println("\nSum: "+sum( ));
}
}
class gp
{
public static void main(String args[ ])throws Exception
{ GPseries a=new GPseries( );
a.readdata( );
a.showseries( );
}
}
Output Of Program
Enter first term: 2
Enter common ratio: 2
Enter limit: 5
2 4 8 16 32
Sum: 62

72
Question 30
Define class 'lucas' with following specifications:-
Date Members:-
n: to store no
Member Functions:-
void readdata( ): to input n
int nThterm(int): to return nTh term of the series
int sum( ): to return sum of the series
void showseries( ): to display the series

PROGRAM
import java.io.*;
class lucas
{
int n;
void readdata( )throws Exception
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter limit: ");
n = Integer.parseInt(in.readLine( ));
}
int nThterm(int m)
{
if(m>3)
return nThterm(m-1)+nThterm(m-2)+nThterm(m-3);
return m;
}
void showseries( )
{
System.out.println("Series: ");
for(int i=1; i<=n; i++)
System.out.print(nThterm(i)+" ");
}
}
class luca
{ public static void main(String args[ ])throws Exception
{
lucas a = new lucas( );
a.readdata( );

73
a.showseries( );
}
}
Output Of Program
Enter limit: 10
Series:
1 2 3 6 11 20 37 68 125 230

Question 31
Define a class with ' MyMath ' with following specifications:-
Data Members:-
x: to store value of theta
Member Functions:-
MyMath(double nx): Parameterised constructor
double abs(double y): to return modulus of x
double cos( ): to return cos x if x lies in 0 and PI/2
double sec( ): to return sec x if x lies in 0 and PI/2

PROGRAM
import java.io.*;
class MyMath
{
double x;
MyMath(double nx)
{
x = nx;
}
double abs(double y)
{
if(y<0)
return -1*y;
return y;
}
double cos( )
{ if(x<0 || x>Math.PI/2)
return 999999.9;
int i,j,s=-1,f; double cosv=1,term=1;
for(i=2; i<=10; i+=2)
{ f = 1;
for(j=1; j<=i; f*=j,j++);
74
term = (Math.pow(x,i)/f)*s;
cosv = cosv+term; s*=-1;
}
return 1-cosv;
}
double sec( )
{ if(cos( )==999999.9)
return cos( );
return 1/cos( );
}
}
class math
{ public static void main(String args[ ])throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter value of theta in radians: ");
double x = Double.parseDouble(in.readLine( ));
MyMath a = new MyMath(x);
System.out.println("cos x: "+a.cos( ));
System.out.println("sec x: "+a.sec( ));
System.out.println("Absolute value of x: "+a.abs(x));
}
}
Output Of Program
Enter value of theta in radians: 0
cos x: 0.0
sec x: Infinity
Absolute value of x: 0.0

Question 32
Define a class ' Matrix ' with following specifications:-
Data Members:-
mat[ ][ ]: an array to store matrix
row: to store no of rows
col: to store no of columns
Member Functions:-
Matrix(int r, int c): Parameterised constructor
readMatrix( ): to input matrix
showMatrix( ): to display the matrix

75
Matrix Transpose( ): to return the transpose matrix
Matrix Add(Matrix m): to add matrix and return resultant
Matrix Subtract(Matrix m):to subtract two matrices and return resultant
Matrix Multiply(Matrix m):to multiply matrices and return resultant

PROGRAM
import java.io.*;
class Matrix
{
int mat[ ][ ],row,col;
Matrix(int r,int c)
{
row = r;
col = c;
mat = new int[row][col];
}
void readMatrix( )throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Start Entering elements: ");
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
mat[i][j] = Integer.parseInt(in.readLine( ));
}
}
void showMatrix( )
{
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
System.out.print(mat[i][j]+"\t");
System.out.println( );
}
}
Matrix Transpose( )
{
Matrix t = new Matrix(col,row);
for(int i=0; i<row; i++)
{
76
for(int j=0; j<col; j++)
t.mat[j][i] = mat[i][j];
}
return t;
}
Matrix Add(Matrix m)
{ Matrix t = new Matrix(row,col);
if(row!=m.row || col!=m.col)
return t;
for(int i=0; i<row; i++)
{ for(int j=0; j<col; j++)
t.mat[i][j] = mat[i][j]+m.mat[i][j];
}
return t;
}
Matrix Subtract(Matrix m)
{ Matrix t = new Matrix(row,col);
if(row!=m.row || col!=m.col)
return t;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
t.mat[i][j] = mat[i][j]-m.mat[i][j];
}
return t;
}
Matrix Multiply(Matrix m)
{ Matrix t = new Matrix(row,m.col);
if(col!=m.row)
return t;
for(int i=0; i<row; i++)
{ for(int j=0; j<m.col; j++)
{ t.mat[i][j] = 0;
for(int k=0; k<col; k++)
t.mat[i][j] += mat[i][k]*m.mat[k][j];
}
}
return t;
}

77
}
class matrix
{ public static void main(String args[ ])throws Exception
{ Matrix a = new Matrix(2,2);
a.readMatrix( ); a.showMatrix( );
System.out.println("Transpose: "); a.Transpose( ).showMatrix( );
System.out.println("Sum: "); a.Add(a.Transpose( )).showMatrix( );
System.out.println("Subtraction: ");
a.Subtract(a.Transpose( )).showMatrix( );
System.out.println("Multiplication: ");
a.Multiply(a.Transpose( )).showMatrix( );
}
}
Output Of Program
Start Entering elements:
1
2
3
4
12
34
Transpose:
13
24
Sum:
25
58
Subtraction:
0 -1
10
Multiplication:
5 11
11 25

Question 33
PROGRAM ON INHERITANCE. Define a class 'Account' with two extended classes ‘Simple’ &
‘Compound’ for calculating interest:-
PROGRAM
import java.io.*;

78
class Account
{
protected int accountNumber;
protected double principal;
Account( )
{
accountNumber = 0;
principal = 0;
}
Account(int acn,double np)
{
accountNumber=acn;
principal=np;
}
void display( )
{
System.out.println("Account Number: "+accountNumber);
System.out.println("Principal: "+principal);
}
}
class Simple extends Account
{
protected double time,rate;
Simple( )
{
time = 0;
rate = 0;
}
Simple(int acn,double np,double nt,double nr)
{
super(acn,np);
time = nt;
rate = nr;
}
void display( )
{
super.display( );
System.out.println("Rate: "+rate);
System.out.println("Time: "+time);

79
System.out.println("Interest: "+interest( ));
}
double interest( )
{
return principal*rate*time/100;
}
}
class Compound extends Account
{
protected double time,rate;
Compound( )
{
time = 0;
rate = 0;
}
Compound(int acn,double np,double nt,double nr)
{
super(acn,np);
time = nt;
rate = nr;
}
void display( )
{
super.display( );
System.out.println("Rate: "+rate);
System.out.println("Time: "+time);
System.out.println("Interest: "+interest( ));
}
double interest( )
{
return principal*(Math.pow(1+rate/100,time)-1);
}
}
class testaccount
{
public static void main(String args[ ])throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Account a=new Account( );

80
System.out.print("Enter Acc#: ");
int acn = Integer.parseInt(in.readLine( ));
System.out.print("Enter principal: ");
double p = Double.parseDouble(in.readLine( ));
System.out.print("Enter rate: ");
int r = Integer.parseInt(in.readLine( ));
System.out.print("Enter time: ");
int t = Integer.parseInt(in.readLine( ));
System.out.print("Enter type of account (S/C): ");
if(in.readLine( ).charAt(0)=='S')
a = new Simple(acn,p,t,r);
else
a = new Compound(acn,p,t,r);
a.display( );
}
}
Output Of Program
Enter Acc#: 4
Enter principal: 10
Enter rate: 1
Enter time: 1
Enter type of account (S/C): S
Account Number: 4
Principal: 10.0
Rate: 1.0
Time: 1.0
Interest: 0.1

Question 34
WAP to display diamond pattern of string

PROGRAM
import java.io.*;
class diamondstr
{
public static void main(String args[ ])throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
String s = in.readLine( ); int i,j,k;
81
System.out.println("Pattern is: ");
for(i=-s.length( ); i<s.length( ); i++)
{
k = 0;
for(j=-s.length( ); j<s.length( ); j++)
{
if(Math.abs(i)+Math.abs(j)<s.length( ))
{
System.out.print(s.charAt(k));
k = j<0?++k:--k;
}
else System.out.print(" ");
}
System.out.println( );
}
}
}
Output Of Program
Enter a string: abc
Pattern is:
a
aba
abcba
aba
a

Question 35
WAP to display odd length string in different pattern

PROGRAM
import java.io.*;
class oddlength
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("Enter a string: ");
String s = in.readLine( ); int i,j;
for(i=0; i<s.length( ); i++)
{
82
for(j=0; j<s.length( ); j++)
{
if(i==s.length( )/2)
{
System.out.print(s);
break;
}
else if(i==j || j==s.length( )/2 || i+j==s.length( )-1)
System.out.print(s.charAt(i));
else
System.out.print(" ");
}
System.out.println( );
}
}
}
Output Of Program
Enter a string: rohit
rrr
ooo
rohit
iii
ttt

Question 36
WAP to show pascal reverse triangle

PROGRAM
import java.io.*;
class pascalrev
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[ ] args)throws Exception
{
System.out.print("\n\n\tEnter limit: ");
int n = Integer.parseInt(in.readLine( ));
int arr[ ][ ] = new int[n*2][ ],i,j,k;
System.out.print("\n\tPascal Triangle:\n");
for(i=0; i<n*2; i++)
{
83
k = i<n?i+1:n*2-i-1;
arr[i] = new int[k];
for(j=0; j<k; j++)
{
if(j==0 || j==i)
arr[i][j] = 1;
else if(i<n)
arr[i][j] = arr[i-1][j-1]+arr[i-1][j];
else
arr[i][j] = arr[i-1][j]-arr[i][j-1];
System.out.print("\t"+arr[i][j]);
}
System.out.print("\n");
}
}
}
Output Of Program
Enter limit: 3
Pascal Triangle:
1
11
121
11
1

Question 37
WAP to find second highest no. amongst the list
PROGRAM
import java.io.*;
class secondhigh
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("Enter size: ");
int n = Integer.parseInt(in.readLine( )),h=0,sh=0,i,k;
System.out.println("Start Entering Elements: ");
for(i=0; i<n; i++)
{

84
k = Integer.parseInt(in.readLine( ));
if(k>h)
{
sh = h;
h = k;
}
else if(k<h&&k>sh)
sh = k;
}
System.out.print("Second Highest Is: "+sh);
}
}
Output of Program
Enter size: 3
Start Entering Elements:
1
3
2
Second Highest Is: 2

Question 38
WAP to find intersection of two arrays
PROGRAM
import java.io.*;
class intersection
{
public static void main(String args[ ])throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter size of array 1(R1): ");
int r1 = Integer.parseInt(in.readLine( ));
System.out.print("Enter size of array 2(R2): ");
int r2 = Integer.parseInt(in.readLine( ));
int i,j,p=0,t;
int a1[ ] = new int[r1],a2[ ] = new int[r2],a[ ] = new int[r2];
System.out.println("Enter elements of array 1: ");
for(i=0; i<r1; i++)
{
//a1[i] = Integer.parseInt(in.readLine( ));

85
a1[i] = (int)(Math.random( )*10);
}
System.out.println("Enter elements of array 2: ");
for(i=0; i<r2; i++)
{
//a1[i] = Integer.parseInt(in.readLine( ));
a2[i] = (int)(Math.random( )*10);
}
if(r1<r2)
a = new int[r1];
//processing
for(i=0; i<r1; i++)
{
t = 0;
for(j=0; j<r2; j++)
{
if(a1[i]==a2[j])
t = 1;
}
if(t==1)
a[p++] = a1[i];
}
System.out.println("ARRAY 1: ");
for(i=0; i<r1; i++)
System.out.print(a1[i]+"\t");
System.out.println("\nARRAY 2:");
for(i=0; i<r2; i++)
System.out.print(a2[i]+"\t");
System.out.println("\nINTERSECTION ARRAY: ");
for(i=0; i<p; i++)
System.out.print(a[i]+"\t");
}
}
Output Of Program
Enter size of array 1(R1): 4
Enter size of array 2(R2): 5
Enter elements of array 1:
Enter elements of array 2:
ARRAY 1:

86
7598
ARRAY 2:
98735
INTERSECTION ARRAY:
7598

Question 39
WAP which uses RECURSIVE METHOD to interchange even with odd and vice-versa
PROGRAM
import java.io.*;
class eve_odd
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("Enter size: ");
int i,size = Integer.parseInt(in.readLine( ));
int arr[ ] = new int[size];
System.out.println("Start Entering elements: ");
for(i=0; i<size; i++)
arr[i] = Integer.parseInt(in.readLine( ));
System.out.println("Initial Array: ");
for(i=0; i<size; i++)
System.out.print(arr[i]+"\t");
arrange(arr,size,0,0);
System.out.println("\nSorted Array: ");
for(i=0; i<size; i++)
System.out.print(arr[i]+"\t");
System.out.println( );
}
public static void arrange(int arr[ ],int size,int eve,int odd)
{ while(eve<size && arr[eve]%2!=0)
eve++;
while(odd<size && arr[odd]%2==0)
odd++;
if(eve<size && odd<size)
{ arrange(arr,size,eve+1,odd+1);
swap(arr,eve,odd);
}

87
}
public static void swap(int arr[ ],int i,int j)
{ int t = arr[i];
arr[i] = arr[j]; arr[j] = t;
}
}
Output Of Program
Enter size: 2
Start Entering elements:
1
2
Initial Array:
12
Sorted Array:
21

Question 40
WAP to search given element arranged in array in ascending order
PROGRAM
import java.io.*;
class binarysearch
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[ ])throws Exception
{
System.out.print("\n\n\tEnter size of array: ");
int a[ ] = new int[Integer.parseInt(in.readLine( ))];
int i,st = 0,la = a.length-1,mid = 0,d = 1,key;
System.out.println("\n\n\tStart Entering elements:");
for(i=0; i<a.length; i++)
a[i] = Integer.parseInt(in.readLine( ));
System.out.print("\n\n\tEnter Key:");
key = Integer.parseInt(in.readLine( ));
while(st<=la)
{
mid = (st+la)/2;
if(a[mid]==key)
{
d = 0; break;

88
}
if(a[mid]>key)
la = mid-1;
if(a[mid]<key)
st = mid+1;
}
if(d==0)
System.out.print("\n\n\tKey Occur at: "+(mid+1));
else
System.out.print("\n\n\tKey doesn't occur: ");
}
}
Output Of Program
Enter size of array: 3
Start Entering elements:
1
2
3
Enter Key:1
Key Occur at: 1

89

You might also like