Sei sulla pagina 1di 111

INDEX

S. no. TOPIC 1 PROGRAM 1 2 PROGRAM 2 3 PROGRAM 3 4 PROGRAM 4 5 PROGRAM 5 6 PROGRAM 6 7 PROGRAM 7 8 PROGRAM 8 9 PROGRAM 9 10 PROGRAM 10 11 PROGRAM 11 12 PROGRAM 12 13 PROGRAM 13 14 PROGRAM 14 15 PROGRAM 15 16 PROGRAM 16 17 PROGRAM 17 18 PROGRAM 18 19 PROGRAM 19 20 PROGRAM 20 Page no. 2-8 9-13 14-18 19-22 23-31 32-37 38-42 43-50 51-59 60-67 68-70 71-75 76-78 79-82 83-86 87-92 93-97 98-101 102-104 105-110

Question 1- Define a class TWO_D with following data members: N=size of the array int arr[][]- a square matrix of N X N Member functions: TWO_D(int nn) : to initialize N=nn and to create matrix. void input( ) : to input matrix elements. int has(int y) : returns 1 if y belongs to matrix arr[][] else it returns 0. void check( ) : to remove all duplicate elements only single copy should be there of each element in matrix and insert new element at that position. void print( ) : to print the matrix. Also write main( ). In main both matrix the original one and after deletion.

ALGORITHM
START STEP 1- Input the elements into the square matrix of size 3 as arr[ ][ ]. STEP 2- Print the matrix. STEP 3- Initialize first element of matrix into two variables-max and min which are to store smallest and the biggest element of the matrix. STEP 4- Initialize a variable I and assign 0 to it. STEP 5- Initialize another variable j and assign 0 to it. STEP 6- If [i][j]th element of matrix arr is greater than max, assign the value of that element to max. STEP 7- If [i][j]th element of matrix arr is smaller than min ,assign the value of that element to min. STEP 7- Increment js value by 1 and repeat step 6 and 7 as long as it does not become 2. STEP 8- Increment is value by and repeat from step 6 to 8 as long as it does not become 2. STEP 8- Initialize a variable m as 0. STEP 9- Initialize a variable k as min. STEP 10- Initaliaze a variable c as 0. STEP 11- Initialize a variable i as 0. STEP 12- Initialize a variable j as 0.

3 STEP 13- If k is equals to [i][j]th element of the matrix, c is incremented.

STEP 14- Just when c gets greater than 1, user is asked to input a new number which is again checked if its in already in matrix or no through linear search. If the new number is already present in the matrix, user is again asked to input any number, not already present in the matrix. But if the new number is not in the matrix, the new number is assigned to that [i][j]th position. STEP 15- j is incremented by 1 and i4th step is reapeated as long as it does not become equals to 2. STEP 16- i is incremented by 1 and steps are reapeated from 12 to 15 as long as it does not become equals to 2. STEP 17- k is incremented by 1 and steps are reapeated from 10 to 16 as long as it does not become equals to max. STEP 18- m is incremented by 1 and steps are reapeated from 9 to 17 as long as it is less than 9. STEP 19- Again the matrix is printed in which all duplicate elements are replaced with new numbers. STOP

import java.io.*; class TWO_D { //class starts int arr[][]; int N; //data members initialized TWO_D(int nn) { //parametrizes constructor N=nn; arr=new int[N][N]; } void input()throws IOException { //function to enter the elements into the matrix BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the elements in the matrix"); for (int i=0;i<N;i++)

{ for (int j=0;j<N;j++) arr[i][j]=Integer.parseInt(in.readLine()); //elements of the matrix } } //function ends int has(int y) { //function to see if y is in the matrix or not for (int i=0;i<N;i++) { for (int j=0;j<N;j++) { if(y==arr[i][j]) //checking if y is matrix element or not return 1; } } return 0; } //function ends void check()throws IOException { //function to remove duplicate elements BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int max=arr[0][0]; //for calculating the biggest element of the matrix int min=arr[0][0]; //for calculating the smallest element of the matrix for (int i=0;i<N;i++) { //loop to find the smallest and biggest element of the matrix for (int j=0;j<N;j++) { //nested loop if (arr[i][j]>max) //checking if the [i][j]th element of the matrix is greater than max or not max=arr[i][j]; if (arr[i][j]<min) //checking if the [i][j]th element of the matrix is smaller than min or not min=arr[i][j]; } } //loop finished

for (int m=0;m<(N*N);m++) { //loop to chenge the repeating elements for (int k=min;k<=max;k++) { //loop to calculate frequency of all the elements int c=0; //stores the frequency of each number for (int i=0;i<N;i++) { for (int j=0;j<N;j++) { //loop to check if k is [i][j]th element of the matrix if (k= =arr[i][j]) //if k is [i][j]the element { //if k is [i][j]the element c++; //c is incremented by 1 } if (c>1) { //counter is encountered just when frequency gets more than 1 c=0; //c is reduced back to 0 System.out.println("enter a new no."); //user is asked to enter a new number not present in matrix int s=Integer.parseInt(in.readLine()); //user enters the number if (has(s)==0) //to see is s already present in matrix or not { //if conditions turns false arr[i][j]=s; //s is assigned as the [i][j]the element } else { //if condition is true System.out.println("enter a new no. not present in matrix"); s=Integer.parseInt(in.readLine()); //user again needs to enter a new number } } //iteration for 1 element is done } } } }

} //function over public void print() { //function to print the matrix for (int i=0;i<N;i++) { for (int j=0;j<N;j++) { System.out.print(arr[i][j]+"\t"); } System.out.println(); } } public static void main()throws IOException { //main function TWO_D ob=new TWO_D(3); //object is created ob.input(); ob.print(); ob.check(); ob.print(); //all required functions are called } } //class ends

OUTPUT enter the elements in the matrix 11 22 33 11 22 33 11 22 33 11 22 33 11 22 33 11 22 33 enter a new no. 22 enter a new no. not present in matrix 121 enter a new no. 232 enter a new no. 343 enter a new no. 454 enter a new no. 33 enter a new no. not present in matrix 565 enter a new no. 676 enter a new no.

787 enter a new no. 11 enter a new no. not present in matrix 898 enter a new no. 976 11 22 33 454 232 343 787 976 676

Question 2-Consider following inheritance path where Student is base class

Student Name Address rollno

CommerceStudent
MarksAcc MarksEco

ScienceStudent
Marksphy MarksMaths

Above classes are showing data members Write contructors for passing various attributes for all the three classes and Average( ) for the class CommerceStudent and ScienceStudent which returns average marks. Also write display( ) for all the three classes to display the data members and average too.

10

ALGORITHM
START STEP 1- Pass values to the data members of sciencestudent as "Saumya","Maruti Puram",25,58,52. STEP 2- Pas values to the data members of commercestudent as "Bittu","Janki Puram",11,78,99. STEP 2- In both the above steps, last two values are the marks of two subjects. STEP 3- Average marks are calculated for both the objects by dividing the sum of marks of both the subjects by 2. STEP 4- Details are printed: name, address, roll no., marsk of both subjects and their average. STOP

class mn { //main class void main() { //main function Sciencestudent ob=new Sciencestudent("Saumya","Maruti Puram",25,58,52); //object created for first derived class Commercestudent obc=new Commercestudent("Bittu","Janki Puram" ,11,78,99); //object created for second derived class ob.display(); //funtion calling obc.display(); } } //main class over class Student { //begins the base class

11

String name; String address; int rollno; //data memebers intialized Student(String u,String v,int w) { //parametrized constructor name=u; address=v; rollno=w; } void display() { // function to display the general details of the student System.out.println("name of the student-"+name); System.out.println("address-"+address); System.out.println("roll no.-"+rollno); } } //base class ends class Commercestudent extends Student { //first derived class begins int markseco; int marksacc; Commercestudent(String a,String b,int c,int d,int e) { //parametrized constructor super(a,b,c); //providing values to the base class data members marksacc=d; markseco=e; } double average() { //function to return the average of the 2 asked sunject marks double ave=(markseco+marksacc)/2; return ave; } void display() { //function to display all the details super.display(); //prints the general details

12

double y=average(); //y holds the average marks System.out.println("average marks-"+y); } //function over } //first derived class over class Sciencestudent extends Student { //second derived class begins int marksphy; int marksmaths; Sciencestudent(String f,String g,int h,int i,int j) { //parametrized constructor super(f,g,h); //providing values to the base class data members marksphy=i; marksmaths=j; } double average() { //to calculate the average marks of the 2 asked marks double ave=(marksphy+marksmaths)/2; return ave; } void display() { //to display all the details super.display(); //display base class data members double y=average(); System.out.println("average marks-"+y); } } //second derived class over

13

OUTPUT name of the student-Saumya address-Maruti Puram roll no.-25 average marks-55.0 name of the student-Bittu address-Janki Puram roll no.-11 average marks-88.0

14

Question 3- Define a class TWO_D with following data members : in arr[][]- a square matrix of N X N N- size of the array Member functions: TWO_D(int nn) : to initialize N=nn and to create matrix void input( ) : to input matrix elements void check( ) : to print the smallest in each row along with the matrix. void sort( ) : to sort each row in descending order using any sorting technique. void print( ) : to print the matrix. Also write main( ).

ALGORITHM
START STEP 1- Create a square matrix of size 4. STEP 2- Input elements into the matrix. STEP 3- Initialize a variable k as 0. STEP 4- Initialize [i][0]th element of the matrix as a variable min. STEP 5- Initialize a variable m as 0. STEP 6- If [k][m]th element is lesser than min, [k][m]th element is assigned to the variable min. STEP 7- Increment ms value by 1 and repeat step 6 as long as it is less then 4. STEP 8- Increment ks value by 1 and repeat the steps from 4 to 7 as long as it is less than 4. STEP 9- At the end of each iteration of k loop, the smallest element of [k]th row of the matrix is printed.

15

STEP 10- Initialize a variable k as 0. STEP 9- Initialize a variable i as 0. STEP 10- Initialize a variable j as 0. STEP 11- If [i][j]th elements is greater than [i][j+1]th element of the matrix, they are swapped. STEP 12- Increment js value by 1 and repeat step 11 as long as it is less than 3. STEP 13- Increment Is value by 1 and repeat steps from 10 to 12 as long as it is less than 4. STEP 14- Increment ks value byy 1 and repeat steps from 9 to 13 as long as it is less than 4. STEP 15- Print the matrix. STOP

import java.io.*; class TWO_D1 { //class starts int arr[][]; int N; // data members initialized TWO_D1(int nn) { //parametrized constructor N=nn; arr=new int[N][N]; } void input()throws IOException { //function to input elements in the matrix BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the elemets"); for (int i=0;i<N;i++) { for (int j=0;j<N;j++) arr[i][j]=Integer.parseInt(in.readLine()); }

16

} void check() { //function to print the smallest element in each row print(); //function calling to print the elements in the inputted order for (int k=0;k<N;k++) { int min=arr[k][0]; for (int m=0;m<N;m++) { if (arr[k][m]<min) min=arr[k][m]; } System.out.println("Smallest number in row "+k+" is "+min); //to print the smallest element of each row } } //function over void sort() { //function to sort each row for (int k=0;k<N;k++) { //bubble sorting for (int i=0;i<N;i++) { for (int j=0;j<(N-1);j++) { if (arr[k][j]<arr[k][j+1]) { int t=arr[k][j]; //swapping arr[k][j]=arr[k][j+1]; arr[k][j+1]=t; } } } } //bubble sort over } //function over void print()

17

{ //function to print the matrix for (int i=0;i<N;i++) { for (int j=0;j<N;j++) System.out.print(arr[i][j]+"\t"); System.out.println(); } } //function over void main()throws IOException { //main function BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); TWO_D1 ob=new TWO_D1(4); //object created with 4 as N ob.input(); ob.check(); ob.sort(); ob.print(); //functions called } //main function over } //class over

18

OUTPUT enter the elements 1 3 5 7 2 4 1 7 34 67 34 22 8 6 44 6 1 3 5 7 2 4 1 7 34 67 34 22 8 6 44 6 Smallest number in row 0 is 1 Smallest number in row 1 is 1 Smallest number in row 2 is 22 Smallest number in row 3 is 6 7 5 3 1 7 4 2 1 67 34 34 22

19

44

Question 4- Fractions are numbersand num is the numerator and den is the denominator and denis not equal to 0. Some of the methods in class Division are given below: Class Name : Division Data members : num and den of integer types. Member functionsDivision(int, int) : constructor, first argument is numerator and second argument is denominator. int hcf(int, int) : find the hcf of two numbers. int lcm(int, int) : find the lcm(using hcf) void reduce( ) : reduce current Division objects to its lowest terms e.g. 1000/3000 is 1/3. Division addto(Division f) : to add current Division object to Division f and return the sum as a Division object. E.g. the sum of 2/9 and 5/18 is . Also write main( ).

ALGORITHM
START STEP 1- From the two numbers, c and d, find the smaller one and store it in min. STEP 2- Initialize a variable i as 1 and find the highest number which when divides both the number, c and d, leaves no remainder and store it in h. STEP 3- Increment is value by 1 and repeat step 2 as long as it is less than equals to min. STEP 4- Find the lcm by using the formula: lcm=product of two numbers/their hcf.

20

STEP 5- For reducing the fraction, find the hcf of numerator and denominator and then numerator and denominator are changed to quotient found when numerater and denominator are respectively divided by hcf. STEP 6- Two sets of numerator and denominator are inputted. STEP 7- For both the sets, first repeat steps from 1 to3 and then step 5. STEP 8- Taking denominator of both the sets, perform step 4 and then their lcm is divided by denominator of both sets one bye one. STEP 9- First result derived from step 8 is then then multiplied with numerator and denominator of first and the second result is multiplied with numerator and denominator of the second set. STEP 9- The numerator of both the sets are added and a numerator formed is stored in a new numerator whose denominator is the lcm of the denominator of last two sets of numerator and denominator passed. STEP 10- Print the numerator and denominator. STOP

class Division { //class begins int num; int den; //data members initialized Division(int a,int b) { //parametrized constructor num=a; den=b; } int hcf(int c,int d) { //funtion to return the hcf of two numbers int h=0; int min=0; //to store the smallest of the 2 numbers in this if(c<d) { min=c; } else {

21

min=d; } for(int i=1;i<=min;i++) { //loop begins if ((c%i==0)&&(d%i==0)) { //hcf would divide both the numbers without any remainder h=i; } } //loop ends return h; //returns the hcf when called } //function ends int lcm(int e,int f) { //function to return the lcm of two numbers int hh=hcf(e,f); //findind hcf of the numbers first int l=(e*f)/hh; //using formula:lcm=product of numbers/hcf of numbers return l; //returns the lcm } //function ends void reduce() { //function to reduce the fraction in the most simplified form int s=hcf(num,den); //hcf of num and den num=num/s; //reducing num to smallest possible term den=den/s; //reducing den to its smallest possible term } //function ends Division addto(Division f) { //function to add both the fraction after being reduced int v=lcm(f.den,den); //lcm of the denominators of the fractions f.num=(v/f.den)*f.num; num=(v/den)*num; //changing the numerator to the term possible for being added f.den=v; den=v; //changing the denominators to the term possible for being added f.num=(f.num+num); //adding the numerators return f; //returning the fraction } //function over void main()

22

{ //main function Division ob1=new Division(64,8); Division ob2=new Division(100,200); //two objects created with arguements Division ob3=new Division(0,0); //an object created to store the fraction after addition ob1.reduce(); ob2.reduce(); ob3=ob2.addto(ob1); //function called to find ob3 System.out.println("numerator"+ob3.num); System.out.println("dumerator"+ob3.den); //printing the fraction } //function over } //class over

OUTPUT numerator 17 denominator 2

23

Question 5- A college maintains a list of its students graduating every year. At the end of the year, the college produces a report that lists the following: Year: __________ No. of working graduates: __________ No. of non-working graduates: __________ Details of the top-scorer: _________ Name: _____ Age: _____ Subject: _____ Ave marks: _____ _____% are first divisioners WAP that uses the following inheritance path for the below class es: (BASE CLASS) (DERIVED CLASS)

Person
name age roll no. percentage marks

GraduateStudent
subject employed

Design classes with functions of your own choice and display the list as shown above in main(). Input records for 10 GraduateStudents and display the list.

24

ALGORITHM
START STEP 1- Input general details of the student-name, age, roll no and percentage marks as name, age and per respectively. STEP 2- Input subject. STEP 3- Enter 1 if the person is employed, else input 0. STEP 4- Input the year and % of first divisioners as year and div respectively and then print them. STEP 5- Two integer variables- s and t are initialized. STEP 6- Create two string arrays-nm and sub, two integer arrays-a and r and one double type array-marks. Size of all arrays is 10. STEP 7- 0 is assigned as value of t. STEP 8- Initialize a variable i as 0. STEP 9- Repeat step 1,2 and 3. If employeds value is 1 then t is incremented by 1. STEP 10- Values inputted in step 9 are accordingly assigned as [i]th element of various arrays which were created in step 6. STEP 11- is value is incremented by 1 and 9th and 10th step is repeated as long as it is less than 10. STEP 11- [0]th element of array marks is assigned as value of a double type new variable y. STEP 12- 0 is assigned as value of s. STEP 13- Initialize a variable I as 0. STEP 14- If [i]th element of array marks is greater than y then i is assigned as value of s. STEP 15- Increment is value by 1 and repeat step 14 as long as it is less than 10. STEP 16- t is printed which is no. of working graduates. STEP 17- (10-t) is no. of non-working graduates which is printed. STEP 18- [s]th element of the arrays are printed as they are details of the top scorer.

25

STOP

import java.io.*; class main { //main class begin void diplay()throws IOException { graduatestudent ob= new graduatestudent(); //base class object is created System.out.println(); System.out.println(); ob.input(); ob.print(); } } //main class over class person { //base class begin String name; int age,rollno; double per; //data members initialized void input()throws IOException { //function to input general details BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter general details"); name=in.readLine();

26

age=Integer.parseInt(in.readLine()); rollno=Integer.parseInt(in.readLine()); per=Double.parseDouble(in.readLine()); } } //base class over class graduatestudent extends person { //derived class begin double div; //% of first divisioners String subject; int s,t; //s is to store the index of top scorer int year; int employed; //various arrays are initialized to store details of 10 details String nm[]=new String[10]; int a[]=new int[10]; int r[]=new int[10]; double marks[]=new double[10]; String sub[]=new String[10]; void input()throws IOException { //function to input details t=0; //t holds the no. of working graduates BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter % of first divisioners"); div=Double.parseDouble(in.readLine()); System.out.println("enter the year"); year=Integer.parseInt(in.readLine()); for(int i=0;i<10;i++) { //to input details into the arrays super.input(); nm[i]=name; a[i]=age; r[i]=rollno; marks[i]=per; System.out.println("enter employed(1) or not(0)");

27

employed=Integer.parseInt(in.readLine()); if (employed==1) { t=t+1; } System.out.println("enter subject"); subject=in.readLine(); sub[i]=subject; } double y=marks[0]; for(int i=0;i<10;i++) { //find top-scorer if(marks[i]>y) { y=marks[i]; s=i; } } } void print() { //function to print the list System.out.println("YEAR: "+year); System.out.println("No. of working graduates "+t); System.out.println("No. of non-working graduates "+(10-t)); System.out.println("Details of top-scorer-"); System.out.println("Name: "+nm[s]); System.out.println("Age: "+a[s]); System.out.println("Roll no.: "+r[s]); System.out.println("Subject: "+sub[s]); System.out.println("Average marks: "+marks[s]); System.out.println(div+"% are first divisioners"); } } //derived class over

28

OUTPUT enter % of first divisioners 65 enter the year 2010 enter general details "Saumya" 17 25 88.9 enter employed(1) or not(0) 1 enter subject "Maths" enter general details "Neha" 16 27 90 enter employed(1) or not(0) 1 enter subject "History"

29

enter general details "Payal" 10 12 99 enter employed(1) or not(0) 0 enter subject "Drawing" enter general details "Nitika" 20 44 98 enter employed(1) or not(0) 1 enter subject "Accounts" enter general details "Shruti" 18 40 88.5 enter employed(1) or not(0) 0 enter subject "History" enter general details "Aparna" 10 22 66.7 enter employed(1) or not(0) 0 enter subject

30

"English" enter general details "Kavya" 18 27 100 enter employed(1) or not(0) 1 enter subject "Physics" enter general details "Preeti" 13 34 99 enter employed(1) or not(0) 0 enter subject "GK" enter general details "Shreya" 11 6 94.5 enter employed(1) or not(0) 0 enter subject "Biology" enter general details "Shivani" 17 33 98.5 enter employed(1) or not(0) 0

31

enter subject "Chemistry" YEAR: 2010 No. of working graduates 4 No. of non-working graduates 6 Details of top-scorerName: "Kavya" Age: 18 Roll no.: 27 Subject: "Physics" Average marks: 100.0 65.0% are first divisioners

32

Question 6- Define a class Date with following data members int dd, mm, yy[to store date, month, and year] Member functions: Date( ) void input( ) int leap(int y) int years(int y1, int y2) int days(int a, int b, int c) void total_days(Date d1, Date d2) Also write main( ). :constructor :to input a valid date. : returns 1 if y is a leap year else 0 : to return number of days between rear y1 and year y2. : to return number of days from 1 Jan of the year c where b is month and a day : to print total number of days between Date d1 and Date d2.

ALGORITHM
START STEP 1- Input two variables as y1 and y2 as two years. STEP 2- Difference between the two years is stored in t. STEP 3- Initialize two variables: c and days as 0.

33

STEP 4- Initialize a variable i as y1. STEP 5- In each iteration check if the year is leap year or not. If it is, then c is incremented by 1. STEP 6- Increment I by 1 and repeat step 5 as long as it less than or equals to y2. STEP 7- days is incremented by product of t and 365 and then c is added to it. STEP 8- Input two sets of dates with variables dd, mm and yy each. STEP 8- Calculate the number of days from 1 January to the inputted date of the year given as inputted in ob1 and stored in variable a. If the given year is a leap year, a is incremented by 1. STEP 9- Calculate the number of days from 1 January to the inputted date of the year given as inputted in second set of date and stored in variable b. If the given year is a leap year, a is incremented by 1. STEP 10- Initialize two variables: mydays and m as 0. STEP 11- If yy of first date is equal to the yy of second set and then their difference is stored in mydays. STEP 12- Else if yy of first date is less than yy of second set then it is checked if yy of ob1 is leap year or not. If it is, m is incremented by difference of 366 and a else m is incremented by 365 and a, and then m is added to mydays. And then steps are repeated from 1 to 6 with first dateyy and second dates yy as the two variable and the result is stored in a variable y which is again added to mydays. STEP 13- Else if yy of first date is bigger than yy of second date then it is checked if yy of second date is leap year or not. If it is, m is incremented by difference of 366 and a else m is incremented by 365 and a, and then m is added to mydays. And then steps are repeated from 1 to 7 with second dateyy and first dates yy as the two variable and the result is stored in a variable y which is again added to mydays. STEP 14- my days is then printed. STOP

import java.io.*; class date { //class starts int dd,mm,yy; //data members initialized date() { //contructor dd=0;

34

mm=0; yy=0; } void input()throws IOException { //function to input values to data members BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the date"); dd=Integer.parseInt(in.readLine()); mm=Integer.parseInt(in.readLine()); yy=Integer.parseInt(in.readLine()); } int leap(int y) { //to check if the year is a leap year or not if (y%4==0) return 1; else return 0; } int years(int y1,int y2) { //function to return no. of days between two years y1 and y2 int c=0; //to hold no. of leap years bteween y1 and y2 for (int i=y1+1;i<y2;i++) { int s=leap(i); if (s==1) { //if i is a leap year c=c+1; //c is incremented } } //c is extra no. of days int t=y2-y1; t=t-1; int day=t*365; //no. of days in t yrs day=day+c; //adding extra days due to leap yrs return day; //returns the no. of days between the yrs

35

} int days(int a,int b,int c) { //function to return no. of days from 01/01 to the given date if the year 'c' int g=0; int l=b-2; int ds=l*30; //no. of months to 30 for(int i=1;i<b;i++) { if ((i= =1)||(i= =3)||(i= =5)||(i= =7)||(i= =8)||(i= =10)||(i= =12)) //all months of 31 days g=g+1; //extra days } ds=ds+g; if (leap(c)= =1) { //in leap year no. of days in feb are 29 ds=ds+29; } else { //otherwise 28 days ds=ds+28; } ds=ds+a; return ds; //req. no. of days } void total_days(date d1,date d2) { //to calculate total days int a=days(d1.dd,d1.mm,d1.yy); //calculate days from 1 jan to d1.dd/d1.mm of year d1.yy int b=days(d2.dd,d2.mm,d2.yy); //calculate days from 1 jan to d2.dd/d2.mm of year d1.yy int mydays=0; //stores the required no. of days int m=0; if (d1.yy==d2.yy) { //if both the dates are from same year if (a>b)

36

{ //d2 date lies before d1 date mydays=a-b; } else { //d1 date lies before d2 mydays=b-a; } } if (d1.yy<d2.yy) { if (leap(d1.yy)==1) { m=366-a; } else { m=365-a; } int y=years(d1.yy,d2.yy); mydays=m+y+b; } System.out.println("no. of days between "+d1.dd+"/"+d1.mm+"/"+d1.yy+" and "+d2.dd+"/"+d2.mm+"/"+d2.yy+" is "+mydays); //prints total no. of days between the dates } //function over void main()throws IOException { //main function date ob1=new date(); date ob2=new date(); //two objects created ob1.input(); ob2.input(); //dates are inputted total_days(ob1,ob2); //days between the dates are calculated } //function over } //class over

37

OUTPUT enter the date 23 11 1995 enter the date 23 10 2012 no. of days between 23/11/1995 and 23/10/2012 is 6179

38

Question 7- A principal of a school needs to find the highest and the lowest marks scored by the student and also the merit list on marks from highest to lowest in a class of 10 students. The classes student and meritlist are declared for above activities with following details:Class name Data members/instance variables: Tot[10] Stud[10] Rollno[10] Member function/method:void readdetails( ) void printresult( ) : student : (double) an array to store total marks of 10 students out 500 each. : string array to store name of 10 students of a Class. : string array to store roll no. of 10 students of a class. : to input names and marks of 10 students. Marks are given out of 500 each. And to assign rollnos. From 200101 to 200110. : to print students scoring highest and lowest marks in the class along with names and rollno. of students. : meritlist : NONE : to generate merit list of 10 students on the basis of total marks along with of students.

Class Name Data members/instance variables Member function/methods:void generatemerit( )

39

void printmerit( )

: to print merit list of 10 students in three columns in the following format: NAME XXXXXX XXXXXX XXXXXX ALGORITHM MARKS SCORED XXXXXX XXXXXX XXXXXX

ROLL NO. XXXX XXXX XXXX


STEP 1- Three arrays are created: tot, name and rollno of size 10. STEP 2- Initialize a variable c as 200101. STEP 3- Initialize a variable i as 0. STEP 4- In each iteration, a name and total marks are inpuuted as [i]th element inot arrays tot and name. STEP 5 - is value is incremented and step 4 is repeated With each iteration, c is assigned as [i]th element into array rollno and then c is incremented by 1. This step is performed as long as I is less than 10. STEP 6- Initialize a variable i as 0. STEP 7- Initialize a variable j as 0. STEP 8- It is checked if [j]th element is lesser than [j+1]th element of array tot or not. If it is, then [j+1]th element of arrays tot, name and rollno is assigned as [j]th element of the arrays and former values of [j]th element of these arrays are assigned to [j+1]th elements of these arrays. STEP 9- js value is incremented by and step 8 is repeated as long as it is less than 9. STEP 10- is value is incremented by 1 and steps are repeated from 7 to 9 as long as it is less than 10. STEP 8- All three arrays are printed in proper format. STEP 9- [0]th and [9]th element of these arrays are printed as highest scorer and lowest scorer respectively.

40

import java.io.*; class main { //class starts void mn()throws IOException { //main function name ob=new name(); //object created ob.readlist(); ob.generatemerit(); //required functions are called } } //main class over class student { //base class starts int tot[]=new int[10]; String name[]=new String[10]; int rollno[]=new int[10]; //data members initialized void readlist()throws IOException { //function to input the details begins BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter name,total out of 500"); int c=200101; //first roll no. for(int i=0;i<10;i++) { tot[i]=Integer.parseInt(in.readLine()); //total marks name[i]=in.readLine(); //name of the student rollno[i]=c; c=c+1; } } //function over void printresult() { //function to print details in order for (int i=0;i<10;i++) { //bubble sort for (int j=0;j<9;j++) {

41

if (tot[j]<tot[j+1]) { int t=tot[j]; //swapping of all three arrays int u=rollno[j]; String as=name[j]; tot[j]=tot[j+1]; rollno[j]=rollno[j+1]; name[j]=name[j+1]; tot[j+1]=t; rollno[j+1]=u; name[j+1]=as; } } } //sorting done System.out.println("Highest marks "+tot[0]+" are scored by "+name[0]+" having rollno.-"+rollno[0]); //[0]th student scored the highest marks System.out.println("Lowest marks "+tot[9]+" are scored by "+name[9]+" having rollno.-"+rollno[9]); //[9]th student scored the lowest marks } //function over } //base class over class name extends student { //derived class begins void generatemerit() { //function to print final details printresult(); //prints thr highest and the lowest scorer printmerit(); // prints the merit list } void printmerit() { //function to print the merit list System.out.println("ROLL NO."+"\t"+"NAME "+"\t"+"MARKS OBTAINED"); for (int i=0;i<10;i++)

42

{ System.out.println(rollno[i]+ "\t\t" +name[i]+ "\t\t" +tot[i]); } } //function over } //derived class over

OUTPUT Enter name, total out of 500 111 Saumya 222 Charul 333 Deeksha 444 Gauri 121 Kopal 232 Himani 343 Shruti 12 Neha 345 Aish 454 Aditi Highest marks 454 are scored by Aditi having rollno.-200110 Lowest marks 12 are scored by Neha having rollno.-200108 ROLL NO. NAME MARKS OBTAINED 200110 Aditi 454

43

200104 Gauri 444 200109 Aish 345 200107 Shruti 343 200103 Deeksha 333 200106 Himani 232 200102 Charul 222 200105 Kopal 121 200101 Saumya 111 200108 Neha 12 Question 8- Define a class Binary with following data members: String n1, n2 And following member functions: Binary( ) int check(String n) void input( ) String Dec_to_bin(String h) String Bin_to_dec(String h) void sum( ) :constructor : returns 1 if n is a binary number else it returns 0. : to input 2 binary numbers in n1, n2 with decimals. : to return binary equivalent of h. Eg. If h=5.625 binary eq=101.101 : to retuen decimal equivalent of h. Eg if h=101.101 decimal eq=5.625 : to print sum of n1 and n2 in binary number system and decimal number system.

Eg. n1=111.101 n2=110.01 Sum in binary number system is 1101.111 Sum in decimal number system is 13.875

ALGORITHM
START STEP 1- Input two strings, n1 and n2 which consists of only numbers.

44

STEP 2- Two strings, op1 and op2, are initialized. STEP 3- A number is binary only and only if it has 1s, 0s or a decimal(.). STEP 4- If a string is a binary number, 1 is returned else 0 is returned. STEP 5- Step 4 is performed for n1 and n2 and returned values are stored in x and y respectively. STEP 6- If x is 1, n1 is changed into a decimal number and stored in string form in op1. Else if x is 0, then n1 is simply assigned in op1. STEP 7- If y is 1, n2 is changed into a decimal number and stored in string form in op2. Else if y is 0, then n2 is simply assigned in op2. STEP 8- op1 and op2 are changed into double type and stored in a and b respectively. STEP 9- a nd b are added and stored in a variable of double type c. STEP 10- Initialize a string to_bin. STEP 11- c is changed into string type and stored in to_bin. STEP 12- Initialize a string type variable in_bin. Change the string to_bin into a string which has binary equivalent of c and store it in in_bin. STEP 13- Print c and in_bin. STOP

import java.io.*; class Binary { //class begins String n1; String n2; //data members initialized Binary() { //constructor n1=""; n2=""; } void input()throws IOException { //function to provide 2 strings BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the two strings");

45

n1=in.readLine(); n2=in.readLine(); } int check(String n) { //function to check if the string is binary number or not int c=0; int len=n.length(); for(int i=0;i<len;i++) { if((n.charAt(i)=='1')||(n.charAt(i)=='0')||(n.charAt(i)=='.')) //possible characters in binary no. { c=1; } else if((n.charAt(i)!='1')||(n.charAt(i)!='0')||(n.charAt(i)!='.')) { c=0; break; } } if(c==1) { return 1; } else { return 0; } } String Bin_to_dec(String h) { //function to convert binary no.(in string form) to decimal int s=check(h); double sum=0.0; if(s= =0) {

46

System.out.println("given number is not binary"); } else { int x=0; int len=h.length(); for(int i=0;i<len;i++) { //loop to see if there is decimal in the number or not if(h.charAt(i)=='.') { x=i; } //x has index of decimal } if(x!=0) { //if decimal is there String p1=h.substring(0,x); String p2=h.substring(x); int a=Integer.parseInt(p1); double b=Double.parseDouble(p2); int y=0; while(a!=0) { sum+=a%10*Math.pow(2,y); y++; a=a/10; } String tt=""; tt=tt.valueOf(b); tt=tt.substring(2); int length=tt.length(); y=-1; double temp=0.0; for(int i=0;i<length;i++) { char ch=tt.charAt(i);

47

if(ch==49) { temp=temp+(1*Math.pow(2,y)); } else if(ch==48) { temp=temp+(0*Math.pow(2,y)); } y--; } sum=sum+temp; } else { //if decimal is not there int a=Integer.parseInt(h); int y=0; while(a!=0) { sum+=a%10*Math.pow(2,y); y++; a=a/10; } } } String dec=""; dec=dec.valueOf(sum); return dec; } //function over String Dec_to_bin(String h) { //function to convert decimal no. to binary no. String real=""; int y=check(h);

48

if(y==1) { System.out.println("given string is binary already"); return ""; } else { int x=0; int len=h.length(); for(int i=0;i<len;i++) { //loop to see if decimal is there in the no. or not if(h.charAt(i)=='.') { x=i; } } if(x!=0) { //if decimal is there String p1=h.substring(0,x); String p2=h.substring(x); int a=Integer.parseInt(p1); Double b=Double.parseDouble(p2); while(a!=0) { real=(char)a%2+real; a=a/2; } real=real+'.'; String temp=""; while(b!=1.0) { b=b*2.0; String d=""; d=d.valueOf(b); char ch=d.charAt(0);

49

temp=ch+temp; if(b>1.0) { b=b-1; } } real=real.concat(temp); } else if(x==0) { //if decimal isnt there int a=Integer.parseInt(h); while(a!=0) { real=(char)a%2+real; a=a/2; } } return real; } } //function over void sum()throws IOException { //main function input(); //input 2 strings String op1=""; String op2=""; int x=check(n1); int y=check(n2); if(x= =1) { //if n1 is binary op1=Bin_to_dec(n1); //it is converted to decimal no } else { op1=n1; }

50

if(y= =1) { //if n2 is binary op2=Bin_to_dec(n2); //it is converted to decimal no. } else { op2=n2; } double a=Double.parseDouble(op1); double b=Double.parseDouble(op2); //both the strings are changed to double form double c=a+b; //both operands are added String to_bin=""; to_bin=to_bin.valueOf(c); //sum is converted to string type String in_bin=Dec_to_bin(to_bin); //string is converted to binary no. System.out.println("Sum in binary number system is "+in_bin); System.out.println("Sum in decimal number system is "+c); } //function over } //class over

OUTPUT enter the two strings 111.101 110.01 Sum in binary number system is 1101.111 Sum in decimal number system is 13.875

51

Question 9- Define a class trr with following data members: trr ar[4][4] And following functions: void input( ) void transpose(trr M) void sum( ) 5 7 6 10 7 : to sort only border elements in ascending order in following format of arr[][]. If arr[][] is 2 3 4 1 2 3 3 6 7 8 9 6 7 4 1 2 3 8 1 2 4 : to input a 4 X 4 matrix : to print transpose of matrix M : to print sum of each row and each column and primary diagonal and print in following format:

1 1 1 2 2 2 2 4 1 2 1 2 2 2 3 3 Sum= 6 7 7 11 void sort( ) 1 5 9

52

4 5 6 7 Also write main( ).

7 6 5 5

ALGORITHM
START STEP 1- Create a square matrix with size of 4. STEP 2- Input elements into the matrix STEP 4- Initialize a variable i as 0. STEP 5- Initialize a variable sum as 0. STEP 6- Initialize a variable j as 0. STEP 7- [i][j]th element of the matrix is printed and sum is incremented with [i] [j]th element. STEP 8- j is incremented by 1 and step 7 is repeated as long as it is less than 4. STEP 9- i is incremented by 1 and steps 5 to 8 are repeated as long as it is less than 4. STEP 8- At one repeatition of steps from 5 to 8, sum has the sum of all the elements of [i]th row of the matrix which is then printed.. STEP 9- Initialize a variable i as 0. STEP 10- Initialize a variable c_sum as 0. STEP 11- Initialize a variable j as 0. STEP 13- c_sum is incremented with [i][j]th element. STEP 14- Increment js value by 1 and repeat step 13 as long as it is less than 4. STEP 15- Increment is value by 1 and repeat steps 10 to 14 as long as it is less than 4. STEP 16- At one repeatition of steps from 10 to 12, c_sum has the sum of all the elements of [i]th row of the matrix which is then printed. STEP 17- Initialize a variable p_sum as 0. STEP 18- Initialize a variable as 0. STEP 19- p_sum is then incremented with [i][i]th element of the matrix. STEP 20- is value is incremented by 1 and step 19 is repeated as long as it is less than 4. STEP 21An array of 12 elements is created in which all the border elements of the matrix are stored. STEP 22- Initialize a variable i as 0.

53

STEP 21- Initialize a variable j as 0. STEP 22- If [j]th element is greater than [j+1]thelement of the array, their values are swapped. STEP 23- js value is incremented by 1 and step22 is repeated as long as it is less than 11. STEP 24- is value is incremented by 1 and steps from 21 to 23 are repeated as long as it is less than 12. STEP 24 A new matrix of the same same size is created. STEP 25-Elemnts of the sorted elements are assigned to the border elements og the new matrix and inner elements of the matrix are assigned as the inner elements of the new matrix. STEP 25- Print this new matrix. STEP 26- Create a square matrix of size 4. STEP 27- Input elements into the matrix STEP 28- Transpose the matrix. STEP 29- Print the transposed matrix. STOP

import java.io.*; class trr { //class begin int arr[][]=new int[4][4]; //array initialized void input()throws IOException { //function to input arrays into elements BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter"); for (int i=0;i<4;i++) { for (int j=0;j<4;j++) arr[i][j]=Integer.parseInt(in.readLine()); } } void transpose(trr m) { //function to transpose the elements of the array for(int i=0;i<4;i++)

54

{ for(int j=0;j<4;j++) { //storing the transposed elements in m.arr m.arr[i][j]=arr[j][i]; } } for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { System.out.print(m.arr[i][j]+"\t"); } System.out.println(); } } //function over void sum() { //function to print sum for(int i=0;i<4;i++) { int sum=0; for (int j=0;j<4;j++) { System.out.print(arr[i][j]+"\t"); sum=sum+arr[i][j]; //sum of elements in a row } System.out.print(sum); System.out.println(); } for(int i=0;i<4;i++) { int c_sum=0; for(int j=0;j<4;j++) { c_sum=c_sum+arr[j][i]; //sum of elements each column }

55

System.out.print(c_sum+"\t"); } int p_sum=0; for(int i=0;i<4;i++) { p_sum=p_sum+arr[i][i]; //sum of elements of primary diagonal } System.out.print(p_sum); System.out.println(); } //function over void sort() { //function to sort the array int a[]=new int[12]; //creating an array to store border elements int x=0; //start putting border elements in the array a[] for(int i=0;i<4;i++) { a[x]=arr[0][i]; x++; } for(int i=0;i<4;i++) { a[x]=arr[3][i]; x++; } for(int i=1;i<3;i++) { a[x]=arr[i][0]; x++; } for(int i=1;i<3;i++) { a[x]=arr[i][3]; x++; }

56

//array a[] complete for(int i=0;i<12;i++) { //begin bubble sort for (int j=0;j<11;j++) { if(a[j]>a[j+1]) { int t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } //bubble sort complete int narr[][]=new int[4][4]; //new array with sorted border elements int y=0; //putting border elements into narr[] for(int i=0;i<4;i++) { narr[0][i]=a[y]; y++; } for(int i=1;i<3;i++) { narr[i][3]=a[y]; y++; } for(int i=3;i>=0;i--) { narr[3][i]=a[y]; y++; } for(int i=2;i>0;i--) { narr[i][0]=a[y]; y++;

57

} //border elements done for(int i=1;i<3;i++) { //inner elements for(int j=1;j<3;j++) { narr[i][j]=arr[i][j]; } } for(int i=0;i<4;i++) { //printing the required array for(int j=0;j<4;j++) { System.out.print(narr[i][j]+" "); } System.out.println(); } } //function over void main()throws IOException { //main function trr ob=new trr(); trr ob1=new trr(); ob.input(); ob1.input(); System.out.println(); System.out.println(); ob.sum(); System.out.println(); System.out.println(); ob.sort(); System.out.println(); System.out.println(); for(int i=0;i<4;i++) { for(int j=0;j<4;j++)

58

{ System.out.print(ob1.arr[i][j]+"\t"); } System.out.println(); } System.out.println(); ob1.transpose(ob); } //main function over } //class over

OUTPUT enter 1 2 3 4 5 6 7 8 7 6 5 4 3 enter

59

11 22 33 44 55 66 77 88 99 99 88 77 66 55 44 33 1 5 9 6 21 1 9 8 7 2 6 9 6 3 7 8 5 3 4 4 5 22 77 88 55 33 88 77 44 44 33 2 6 9 5 22 3 7 8 4 22 4 8 7 3 22 10 26 33 18 18

11 55 66 99 99 66

60

11 22 33 44

55 66 77 88

99 99 88 77

66 55 44 33

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

ALGORITHM
START STEP 1- Input the value of three data members as N, day_no. and year.If the inputted value of N is less than 1 or greater than 100 or if inputted value of day_no is greater than 366 or if the inputted value of year is not a 4 digits number then display the message to ask user to input proper values. STEP 2- Initialize an integers variable dd to store the day of the date and other as mn to store the month number. STEP 3- Initialize an integer variable x as 0 to store the calculated no. of extra days. STEP 4- Store day_no in a new integer variable s.

61

STEP 5- Initialize an integer variable m as 2 which would be used later for calculation of the month of the date STEP 6- If s would less than or equals to 31 then mns value would be 1 and dds value would be s itself. STEP 7- If s is greater than 31 and less than or equals to 59 and the year is not a leap year or if s is greater than 31 and less than or equals to 60 and the year is a leap year then dd would be 31 less day_no and mns value is 2 STEP 8- If s is greater than 59 and its not a leap year then s would be 59 less s and then a loop is created which is iterated as long as s is greater than or equal to 31. In each iteration, ss vaule is decremented by 31 (as maximum number of days in a month is 31) and ms value is incremented by 1. STEP 9- If s is greater than 60 and its a leap year then s would be 60 less s and then a loop is created which is iterated as long as s is greater than or equal to 31. In each iteration, ss vaule is decremented by 31 (as maximum number of days in a month is 31) and ms value is incremented by 1. STEP 10- If m is greater than 3 and less than oe equals to 5 then xs value is 1 STEP 11- If m is greater than 5 and less than or equals to 8 then xs value is 2. STEP 12- If m is greater than 8 and less than equals to 10 then xs value is 3. STEP 13- If m is greater than 10 the n xs value is 4. STEP 14- Final value of dd would be sum of ss value and xs value and mns value is one more than ms value. STEP 15- Create a String array arr whose size is 13. STEP 16- Keep the first value of arr empty and then sequentially assign all twelve months names between elements os index no. 1 and 12. STEP 17- Initialize a String variable suf which would store the suffix to be written after after the day. STEP 18- If dd lies between 11 and 19 then sufs value is th, else if dds last digit is 1 then suf value is st, else if dds last digit is 2 then sufs value is nd, else if dds last digit is 3 then sufs value is rd and in all other conditions sufs value is th. STEP 19- Print dd followed by suf, then a space followed by the mnth element of the array arr and again a space followed by year. STEP 20- A new integer variable nday_no is initialized which is the sum of day_no and N. STEP 21- If year is a leap year and nday_no is greater than 366 then nday_no is 366 less than nday_no but if is not a leap year and nday_no is greater than 365 then nday_no is 365 less than nday_no. In both the cases, year is incremented by 1. STEP 22- Now all the steps from step no.2 till 19 are repeated.

62

STOP

import java.io.*; class calc {//class started int N; int day_no; int year; //data members initialized calc() { //default constructor N=0; day_no=0; year=0; } //constructor over void input()throws IOException { //function to input values to data members BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

63

System.out.println("enter limit such that 1<=limit<=100"); N=Integer.parseInt(in.readLine()); if ((N<1)||(N>100)) { //if user inputs the value of N incorrectly System.out.println("wrong input,please input N between 1 and 100"); N=Integer.parseInt(in.readLine()); } System.out.println("enter day no. and year"); day_no=Integer.parseInt(in.readLine()); if ((day_no>366)||(day_no<1)) { //if day_no. is incorrect System.out.println("wrong input,please input day_no between 1 and 366"); day_no=Integer.parseInt(in.readLine()); } year=Integer.parseInt(in.readLine()); int c=0;//for the no. of digits in year int y=year; while(y>0) { //to calculate the number of digits in year y=y/10; c++; } if (c!=4) { //if the year given by the user is wrong System.out.println("wrong input,please input year of 4 digits"); year=Integer.parseInt(in.readLine()); } } //function over void results(int days,int yr) { //function for calculating date int x=0; //variable for extra days int dd=0; //day of the final date int mn=0; //month of the final date int m=2; //variable to increment month no. while calculating the date

64

int s=days; //initialising day no. as 's' if (yr%4==0) { //when its a leap year: if(s<=31) { //when day no. is less than or equal to 31 then: dd=s; //day is day no. itself mn=1; //month is January } else if((s>31)&&(s<=60)) { //when day no. is greater than 31 but less than or equal to 60 then: dd=s-31; mn=2; //month would be February } else if(s>60) { //when day no. is greater than 60: s=s-60; //subtracting first 60 days of the year while(s>=31) { //31 as maximum no. of days in a month can be 31 only s=s-31; m++; } //calculating extra days as per the months if((m>3)&&(m<=5)) { x=1; } else if((m>5)&&(m<=8)) { x=2; } else if((m>8)&&(m<=10)) { x=3; } else if(m>10)

65

{ x=4; } dd=s+x; //day of the date would also include extra days mn=m+1; //month of the date would be one more than the calculated as 'm' } } //all probable conditions for the date in the leap year checked else if(yr%4!=0) { //same conditions would be checked to calculate the date in an year which is not a leap year if(s<=31) { dd=s; mn=1; } else if((s>31)&&(s<=59)) { dd=s-31; mn=2; } else if(s>59) { //59 as in a normal year total no. of days in first two months is 59 s=s-59; while(s>=31) { s=s-31; m++; } if((m>3)&&(m<=5)) { x=1; } else if((m>5)&&(m<=8)) {

66

x=2; } else if((m>8)&&(m<=10)) { x=3; } else if(m>10) { x=4; } dd=s+x; mn=m+1; } } String arr[]={"", "January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December"}; //array of all the months such a way that the index number is the month number of the year String suf=""; // 'suf' is the variable for the suffix after the day if((dd>=11)&&(dd<=19)) { //all days between 11 and 19 has 'th' as suffix no matter its last digit is 1,2 or 3 suf="th"; } else if(dd%10==1) { //days whose last digit is 1 and aren't between 11 and 19 has 'st' as suffix suf="st"; } else if(dd%10==2) { //days whose last digit is 2 and aren't between 11 and 19 has 'nd' as suffix suf="nd"; } else if(dd%10==3) { //days whose last digit is 3 and aren't between 11 and 19 has 'rd' as

67

suffix suf="rd"; } else { //rest of the days has 'th' as suffix suf="th"; } System.out.println(dd+suf+" "+arr[mn]+" "+yr); //printing the date } void mn() { // main function results(day_no,year); //calculates the date of the given day number with the given year System.out.println("Date after "+N+" days: "); int nday_no=day_no+N; //day no. after 'N' days if((year%4==0)&&(nday_no>366)) //when the given year is a leap year { //if the new day no.gets greater than 366 nday_no=nday_no-366; //the date we need would be in the next year year=year+1; } else if((year%4!=0)&&(nday_no>365)) //when the given year is not a leap year { //if the new day no.gets greater than 365 nday_no=nday_no-365; //the date we need would be in the next year year=year+1; } results(nday_no,year); //fianlly claculates the date after 'N' days of the given day no. } //end of main function } //end of class

68

OUTPUT enter limit such that 1<=limit<=100 123 wrong input,please input N between 1 and 100 59 enter day no. and year 876 wrong input,please input day_no between 1 and 366 346 12345 wrong input,please input year of 4 digits 2008 11th December 2008 Date after 59 days: 8th February 2009 Qusetion 11- Define a class Number with following data members: Int limit, s; And following functions: Number(int l) :constructor to assign limit=l and other data members. int prime(int n, int c) :returns 1 if n is a prime number else returns 0. int reverse(int m) :to store reverse of m in s and return it using recursion. void print( ) :to print all prime palindrome numbers from 1 to limit. Write main( ).

ALGORITHM

69

START STEP 1- Input a value to data member limit. STEP 2- If n is equal to c, then return 1. Else if n is equals to 1 or on being divided by c leaves no remainder then return 0. If above two values are not satisfied then this step is again repeated with variables n remaining the same and (c+1) acting as new c. STEP 3- If m is equals to 0 then s is returned else remainder of m on being divided by 10 is stored in a new variable r, s is multiplied by 10 and then to it is added r and this value is again stored in s, and then this step is repeated with (m/10) acting as new m. STEP 4- Initialize a variable i as 0. STEP 5- Assign 0 as value to data member s. STEP 6- Step 1 is repeated with variables i and 2 and returned value is stored in a new variable x. STEP 7- Step 2 is repeated with i acting as m and returned value is stored in a new variable y. STEP 8- If y is equals to i and x is 1, then print i. STEP 9- Increment is value by 1 and repeat steps from 5 to 8 as long as it is less than or equals to limit. STOP

import java.io.*; class Number { //class began int limit,s; Number(int l) { //constructor limit=l; s=0; } int prime(int n,int c) { //recursive function to see if the no. is prime or not if(n= =c) { return 1;

70

} else if((n%c= =0)||(n= =1)) { return 0; } else { return prime(n,c+1); //repeating the same function } } int reverse(int m) { //function to return the reverse of the no. if(m= =0) { return s; } else { int r=m%10; s=s*10+r; return reverse(m/10); } } void print() { //to print prime palindrome no. bet 1 and limit System.out.println("prime palindrome numbers between 1 to "+limit); for(int i=0;i<=limit;i++) { s=0; int x=prime(i,2); int y=reverse(i); if((y= =i)&&(x= =1)) { System.out.println(i); }

71

} } void main() { //function to call the print function print(); } } //class over

OUTPUT prime palindrome numbers between 1 to 100 2 3 5 7 11 Question 12- NIC institutes resource manager has decided to network the computer resources like printer, storage media etc, so that minimum resources and maximum sharing could be availed. Accordingly printers are linked to a centralized system and the printing jobs are done on a first cum first served basis only. This is like the first persons job will get done first and the next persons job will be done as the next job in the list and so on. In order to avoid collision, the restriction is that no more than 20 printing jobs can be added.
Define the class PrintJob with the following detail:

Class name job[] newjob capacity front

Data members/instance variable:

: PrintJob

: array of integers to hold the printing jobs. : to add a new printing job into the array. : the maximum capacity of the integer array. : to point to the index of the frony.

72

rear
Member functions:

: to point to the index of the last.

PrintJob( )

: constructor to initialize the data member capacity=20, front=rear= -1 and call the function creatjob( ). void createjob( ) : to create an array to hold the printing jobs. void addjob( ) : adds the new printing job to the end of the last printing job, if possible, otherwise displays the message Printjob is full, cannot add any more. void removejob( ) : removes the printing job from the front if the printing job is not empty, otherwise displays the message Printjob is empty. Also write main( ) for above class.

ALGORITHM
START STEP 1- Create an array of size 20. STEP 3- If rears value is 19 a message is printed Printjob is full,cannot add more" else rear is incremented by 1 and newjob is assigned as the value of [rear]th element of the array and if fronts value is -1 then its incremented. STEP 4- If fronts value is -1, a message is printed Printjob is empty. else fronts value is incremented. STEP 5- Now user is asked to input either 1 or 2 or 3. STEP 6- If its 1 then step 3 is performed, else if its 2 step 4 is performed. Else if its 3, array is printed. If user gives any other input than these 3, a message is displayed- wrong input. STEP 7- Step 5 and 6 are continued as long as user does not input 3.

73

STOP

import java.io.*; class printjob { //class begin int job[]; int newjob; int capacity; int front; int rear; //data members initialized printjob()throws IOException { //constructor capacity=20; front=-1; rear=-1; job=new int[capacity]; createjob(); } void createjob()throws IOException { //function to input values into the array job=new int[20]; } //function ends void addjob()throws IOException { if(rear= =19) { System.out.println("Printjob is full,cannot add more"); } else { BufferedReader in= new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the printjob"); int x=Integer.parseInt(in.readLine());

74

++rear; job[rear]=x; //assigning the new printing job in the last index of the } if(front= =-1) { front++; } } void removejob() { //function to remove a job if(((front==-1)&&(rear==-1))||(front>rear)) { front=-1; rear=-1; System.out.println("Printjob is empty"); } else { front++; } } //function ends void main(String args[])throws IOException { //main function int n=0; //object creation printjob ob=new printjob(); BufferedReader in= new BufferedReader(new InputStreamReader(System.in)); do { System.out.println("enter choice"); System.out.println("enter 1 to input"); System.out.println("enter 2 to delete");

75

System.out.println("enter 3 to display and exit"); n=Integer.parseInt(in.readLine()); switch(n) { //various cases case 1: ob.addjob(); break; case 2: ob.removejob(); break; default: System.out.println("wrong input"); break; } } while(n!=3); for(int i=ob.front;i<=ob.rear;i++) { System.out.println(ob.job[i]); } } //function ends } //class ends OUTPUT enter choice enter 1 to input enter 2 to delete enter 3 to display and exit 1 enter the printjob 45 enter choice enter 1 to input enter 2 to delete enter 3 to display and exit

76

2 enter choice enter 1 to input enter 2 to delete enter 3 to display and exit 3 wrong input

Question 13- Define a class Recursion with following data members String str Int v, w And following functions: Recursion( ) : constructor. void accept( ) : to input any string. void count(int ) : to count number of words starting with a vowel in str and store in data member v and number of words in w using recursion. void display( ) : to print number of words starting with vowels and words in str. Also write main( ).

77

ALGORITHM
START STEP 1- Initialize three data members- string type str and two integer types v and w. STEP 2- Calculate the length of str and store it in a variable l. STEP 3- Begin this step with i as 0. As long as i is less than l, we extract out the [i]th character of str and store it in ch. If ch is any vowel then v is incremented by 1 else if ch is a space then w is incremented by 1 and again this step is repeated with (i+1) acting as new i. STEP 4- (w+1) is the no. of words in str which are printed and v is number of words starting with vowel which is again printed. STOP

import java.io.*; class recursion { //class begin String str; int v,w; //data members initialized recursion() { //constructor str=""; v=0; w=0; } void accept()throws IOException

78

{ //function to input the string BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the string"); str=in.readLine(); } void count(int i) { //function to count no. of words and no. of words starting with vowel int l=str.length(); //length of string if(i<l) { char ch=str.charAt(i); if((str.charAt(i-1)= =' ')&&((ch= ='a') ||(ch= ='A') || (ch= ='e') ||(ch= ='E') ||(ch= ='i') ||(ch= ='I')||(ch= ='o')||(ch= ='O')||(ch= ='u')||(ch= ='U'))) { v=v+1; } else if(ch= =' ') { w=w+1; } count(i+1); } } void display() { //function to display the details System.out.println("no. of words "+(w+1)); System.out.println("no. of words starting with vowels "+v); } void main()throws IOException { //main function accept(); count(1); display(); }

79

} //class over

OUTPUT enter the string "Saumya is a good boy" no. of words 5 no. of words starting with vowels 2

Question 14- Define a class unique with following data members: int arr[10] And following methods: void input( ) : to input 10 integers in arr. int check(int n) : returns 1 if n is a unique no. else it returns 0. A unique no. is a no. whose all the digits are different (eg. 1273 is unique but 121 is not unique.) void print( ) : to print the original array and then print all the unique numbers in the array with proper messages. Also write main( ).

80

ALGORITHM
START STEP 1- Create an array of size 10. STEP 2- Input all 10 elements into the array. STEP 3- Print the array. STEP 4- Initialize a variable c. STEP 5- Initialize a variable i as 0. STEP 6- c is assigned as 0. STEP 7- The number which has to be checked,n, if its unique or not is assigned to a new variable m. STEP 8- Last digit of m is extracted and checked if its equals to i or not. If it is equal to i, c is incremented. STEP 9- m is divided by 10 STEP 10- Repeat steps 8 and 9 as long as m is unequal to 0. STEP 11- Once m becomes 0, it is checked if c is greater than 1 or not. STEP 12- If c is 0 or 1 then is value is incremented by 1 and steps from 6 to 11 are repeated as long as it is less than or equals to 9 but if c is greater than 2, move to the next step. STEP 12- cs value is checked. If c is greater than 1, 0 is returned else 1 is returned. STEP 13- Initialize a variable i as 0. STEP 14- Repeat the steps from 4 to 12 with [i]th element of the array acting as m. And if 1 is returned, [i]th value of the array is printed. STEP 15- Increment is value by 1 and repeat step 14 as long as it is less than 10. STOP

import java.io.*; class unique { //class is started int a[]=new int[10]; //an integer of size 10 is created void input()throws IOException

81

{ //function to input all ten elements in an array BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter all the 10 elements of the array"); for(int i=0;i<10;i++) { a[i]=Integer.parseInt(in.readLine()); } } //function ended int check(int n) { //function to check if n is unique or not int c=0; for(int i=0;i<=9;i++) { //loop to calculate frequency of all digits from 0 to 9 int m=n; //value of n is assigned to a new variable m in each iteration c=0; // variable to calculate the frequency of digit i do { //nested loop to check whether i is a digit if m or not int r=m%10; if(i= =r) { c++; //increments the value of c if i is a digit of m } m=m/10; // m's value is changed in each iteration of nested loop } //frequency if digit i is calculated while(m!=0); if(c>=2) { //if frequency of any number is greater than 1 then its not a unique number and loop can be stopped break; } } if(c>=2) { return 0;

82

} else { //if at each iteration c's value remained 0 or 1 then n is a unique number return 1; } } //function ends void print() { //function to print the details for(int i=0;i<10;i++) { //prints the array System.out.print(a[i]+" "); } System.out.println(); //counter moves to the next line line System.out.println("unique numbers are:"); for(int i=0;i<10;i++) { //loop to check which elements of the array are unique int y=check(a[i]); //check function returns either 1 or 0 here if(y= =1) { System.out.println(a[i]); } } } //function ends void main()throws IOException { //main function unique ob=new unique(); //object is created ob.input(); ob.print(); } //function ends }//class end

83

OUTPUT enter all the 10 elements of the array 121 234 232 345 343 456 454 567 565 678 121 234 232 345 343 456 454 567 565 678 unique numbers are: 234 345 456 567 678

Question 15- Define a class array with following members: int a[ ] int size And following functions: array(int n) : to initialize size=n and create array. void input( ) : to input elements in array. array merge(array a1, array a2) : to return merge array a1 and a2. void print( ) : to print the array. Write main( ) also.

84

ALGORITHM
START STEP 1- Create three objects ob1 with argument 5, ob2 with argument 10 and ob3 with argument 0. STEP 2- Input elements into the array of object ob1 and then print it. STEP 3- Input elements into the array of object ob2 and then print it. STEP 4-Initialize 0 as value of a new variable x. STEP 5- Create a loop from 0 to 4. STEP 6- Assign [i]th element of the array of object ob1 as value of [x]th element of the array of object ob3. STEP 7- x is incremented by 1. STEP 8- Create a loop from 0 to 9. STEP 9- Assign [i]th element of the array of object ob2 as value of [x]th element of the array of object ob3. STEP 10- x is incremented by 1. STEP 11- Print the array of object ob3. STOP

import java.io.*; class array { //class begin int a[]; int size; //data members initialized array(int n) { //parametrized constructor size=n; a=new int[size]; } void input()throws IOException

85

{ //function to input values into the array BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println("enter the elements"); for(int i=0;i<size;i++) { a[i]=Integer.parseInt(in.readLine()); } System.out.println(); } //function over array merge(array a1,array a2) { //function to merge two arrays array ob=new array(a1.size+a2.size); //an object is created int x=0; for(int i=0;i<a1.size;i++) { //values of a1.arr are assigned into the array of object ob ob.a[x]=a1.a[i]; x++; } for(int i=0;i<a2.size;i++) { //values of a2.arr are assigned into the array of object ob ob.a[x]=a2.a[i]; x++; } ob.size=x; //x is asigned as ob's size return ob; //ob is returned } //function over void print() { //function to print the array System.out.println(); for(int i=0;i<size;i++) { System.out.print(a[i]+" "); }

86

} //function over void main()throws IOException { //main function array ob1=new array(5); //first object array ob2=new array(10); //second object array ob3=new array(0); //third object ob1.input(); //values are inputted into the array of first object System.out.println("first array"); ob1.print(); //array of ob1 is printed ob2.input(); //values are inputted into the array of second object System.out.println("second array"); ob2.print(); //array of ob2 is printed ob3=ob3.merge(ob1,ob2); //arrays of ob1 and ob2 are merged and stored in third object System.out.println(); System.out.println(); System.out.print("merged array"); ob3.print(); //merged array is printed } //function over } //class over

OUTPUT enter the elements 1 2 3 4 5 first array

87

12345 enter the elements 11 22 33 44 55 66 77 88 99 00 second array 11 22 33 44 55 66 77 88 99 0 merged array 1 2 3 4 5 11 22 33 44 55 66 77 88 99 0

Question 16- Define a class arrayop with following data members: int a[ ] int size And following methods: arrayop(int n) : to initialize size=n and to create array. arrayop arraydel(arrayop a1) : to delete all duplicate elements of a1 only single copy should be there of each element. void input( ) : to input elements in the array. arrayop common(arrayop obj) : to return the merged array of obj and current array object only of even

88

void print( ) Write main( ) also.

elements. : to print the array.

ALGORITHM
START STEP 1- Create two arrays of size 5 and 6 simultaneously. STEP 2- Elements are inputted into both the arrays. STEP 3- Third array is created. Its arrays size is sum of sizes of first two arrays. STEP 4- Initialize a variable x and assign 0 as its value. STEP 5- Initialize a variable i as 0. STEP 6- If [i]th element of the first array is even, it is assigned as the value of [x]th element of the third array. x is incremented by 1. STEP 7- Increment is value by 1 and repeat step 6 as long as it is less than 5. STEP 8- Initialize a variable i as 0. STEP 9- If [i]th element of the second array is even, it is assigned as the value of [x]th element of the third array. x is incremented by 1. STEP 10- Increment is value by 1 and repeat step 9 as long as it is less than 6. STEP 11- Print third array. STEP 10- Create fourth array of size 5. STEP 11- Calculate the biggest and the smallest element of the array and store them in max and min respectively. STEP 12- Initialize a variable i as min. STEP 13- Calculate the frequency of number i. Just when frequency gets more than 1, all elements are shifted 1 index behind and arrays size is reduced by 1 and again frequency becomes 0. STEP 14- Increment is value by 1 and repeat step 13 as long as it less than 5. STEP 15- Fourth array is printed. STOP

89

import java.io.*; class arrayop { //class begin int a[]; int size; //data members initialized arrayop(int n) { //constructor size=n; a=new int[n]; //array initialized } void input()throws IOException { //function to input the size of the array BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the elements"); for(int i=0;i<size;i++) { a[i]=Integer.parseInt(in.readLine()); } } arrayop arraydel(arrayop a1) { //function to delete the duplicate elements int max=a1.a[0]; //to store the biggest value in the array int min=a1.a[0]; //to store the smallest value in the array for(int i=0;i<a1.size;i++) { //biggest and smallest elements are searched out if(a1.a[i]>max) { max=a1.a[i]; } else if(a1.a[i]<min) { min=a1.a[i]; } }

90

for(int m=0;m<a1.size;m++) { //loop from min to max for(int i=min;i<=max;i++) { int f=0; //to calculate the frequency of number i for(int j=0;j<a1.size;j++) { if(i==a1.a[j]) { f++; } if(f>1) { //just when frequency gets more than 1 f=0; for(int k=j;k<a1.size-1;k++) { a1.a[k]=a1.a[k+1]; //all values are shifted to 1 index behind } a1.size=a1.size-1; //size of the aray is reduced by 1 } } } } return a1; } //function over arrayop common(arrayop obj) { //function to combine the even elements of obj and current object arrayop obj1=new arrayop(size+obj.size); int x=0; for(int i=0;i<size;i++) { if(a[i]%2==0) { obj1.a[x]=a[i]; x++;

91

} } for(int i=0;i<obj.size;i++) { if(obj.a[i]%2==0) { obj1.a[x]=obj.a[i]; x++; } } obj1.size=x; return obj1; } void print() { //function to print the array for(int i=0;i<size;i++) { System.out.print(a[i]+" "); } } void main()throws IOException { //main function arrayop ob1=new arrayop(5); arrayop ob2=new arrayop(5); arrayop ob3=new arrayop(6); arrayop ob4=new arrayop(0); ob1.input(); ob3.input(); //array of objects, ob1 and ob3, are inputted ob4=ob1.common(ob3); //two arrays, ob1 and ob3, are combined and stored in object ob4 ob4.print(); //object ob4 is printed System.out.println(); ob2.input(); //array of object ob2 is inputted ob2=arraydel(ob2); //duplicate elements are deleted ob2.print(); //object ob2 is printed

92

} //function ends } //class over

OUTPUT enter the elements 1 2 3 4 5 enter the elements

93

6 7 8 9 10 11 2 4 6 8 10 enter the elements 1 2 2 2 3 123

Question 17- Define a class pattern with following data members and functions: int size, int arr[ ][ ] void input( ) : to input size(>=3) and to create array. void print( ) : to generate following matrix. If n is odd If n=5 o/p 4 2 1 3 5 If n is even if n=4 o/p 1234

94

9 14 19 24

7 12 17 22

6 11 16 21

8 13 18 23

10 15 20 25

4123 3412 2341

ALGORITHM
START STEP 1- Input a number as size STEP 2- Create a matrix of that size. STEP 3- If value of size is an odd then then initialize 1 as value of a new variable y. STEP 4- Find the middle of the size as x. STEP 5- Start assigning values from middle of each row. STEP 6- But if size is even values are assigned from the [i][i]th position where I varies from 0 to the size. STOP

import java.io.*; class pattern { //class started int size; //data member for the size of the array int arr[][]; //data member for the array pattern() { //constructor size=0;

95

} void input()throws IOException { //function to input the value of size BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any number greater than 3"); size=Integer.parseInt(in.readLine()); arr=new int[size][size]; //creates the array of size 'size' } //function ends void print() { //function to assign values in the matrix if(size%2!=0) { //if the size of the array is an odd number int y=1; //first element in the matrix int x=size/2; //middle point array for(int i=0;i<size;i++) { //loop to assign elements in matrix arr[i][x]=y; y++; //each element of the array increments by 1 for(int a=1;a<=x;a++) { //nested loop to move on either side of of middle of row(i) arr[i][x-a]=y; //on the left side of the middle y++; arr[i][x+a]=y; //on the right side of the middle y++; } } //values assigned for(int i=0;i<size;i++) { //loop for each row for(int j=0;j<size;j++) { //nested loop for each column System.out.print(arr[i][j]+"\t"); //printing elements of a column in a row } System.out.println(); // shift the counter to next row

96

} } else if(size%2= =0) { //if the size of the array is an even number for(int i=0;i<size;i++) { //loop for each row int a=1; //first element to be assigned in a row for(int j=i;j<size;j++) { //nested loop to move the control to next column arr[i][j]=a; a++; if((i!=0)&&(j==(size-1))) { //if the value isn't assign in column 0 of any row for(int k=0;k<i;k++) { //controls starts assigning values from column 0 once it has already assigned value to column as per in the nested loop arr[i][k]=a; a++; } } } } for(int i=0;i<size;i++) { //printing the matrix for(int j=0;j<size;j++) { System.out.print(arr[i][j]); } System.out.println(); //shifting the control to next row System.out.println(); } } } //function ends void main()throws IOException { //main function starts

97

input(); print(); } // function ends } // class ends

OUTPUT enter any number greater than 3 7 6 4 2 1 3 13 11 9 8 10 20 18 16 15 17 27 25 23 22 24

5 12 19 26

7 14 21 28

98

34 32 30 29 31 33 41 39 37 36 38 40 48 46 44 43 45 47 enter any number greater than 3 4 1234 4123 3412 2341

35 42 49

Question 18- A class arithmetic is defined to perform arithmetic operation on the expression given. The expression given contains only one operator(+, -, * or /). The expression should be input as a string and the output should be a number. Assume that only integer constants and an operator is given as the expression. E.g. INPUT 10*7 OUTPUT 70 The description of the class is given below: Class name : arithmetic Data members : String expr, double result

99

Member functions: void accept( ) void calculate( ) void print( )

: function for accepting the expression in form of a string. : function for calculating the expression. : function for printing the result.

Specify the class arithmetic giving details of all the member functions. Write the main function.

ALGORITHM
START STEP 1- Input a string which contains only numbers and a mathematical operator and initialize a double type variable result. STEP 2- Initialize a variable ch of char type. STEP 3- Initialize 0 as value of a new variable x. STEP 4- Find length of the string and store it in a new variable len. STEP 5- Initialize a variable i as 0. STEP 6- [i]th character of the string is stored in ch. STEP 7- If chs Unicode value is 42, 43, 45 or 47, store i in x and and move to step 9. STEP 8- Increment is value by 1 and repeat steps 6 and 7 as long as it less than len. STEP 9- Initialize a string op1 and store in it one half of the original string from 0 to (x-1). STEP 10- Initialize a string op2 and store in it second half of the original string from (x+1) to (len -1). STEP 11- Convert string op1 and op2 in double type and store them in variables a and b respectively. STEP 12- If chs Unicode value is 43, then sum of a and b is stored in result. STEP 13- IF chs Unicode value is 45, then b is subtracted from and the difference is stored in result.

100

STEP 14- If chs Unicode value is 42, then product of a and b is stored in result. STEP 15- If chs Unicode value is 47, then a is divided by b and its quotient is stored in result. STEP 16- Result is then printed. STOP

import java.io.*; class arithmetic { //class starts String expr; double result; //data members void accept()throws IOException { //function to input values to data members BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a string containing digits and any of the arithmetic operators only"); expr=in.readLine(); } void calculate( ) { //function to calculate the result from mathematical expression char ch=' '; //to store the arithmetic operator int x=0; //to store the index of the arithmetic operator in the string expression int len=expr.length(); //to store the length of string expression for(int i=0;i<len;i++) { //loop to find the index value of the arithmetic operator if((expr.charAt(i)= ='+')||(expr.charAt(i)= ='-')||(expr.charAt(i)= ='*')||(expr.charAt(i)= ='/')) { ch=expr.charAt(i); //arithmetic operator is stored in ch as a character x=i; //assign the index value of ch in x

101

break; //stops the iteration once operator is found } } String op1=expr.substring(0,x); //stores first half of the expression as op1 String op2=expr.substring(x+1); //stores the second half of the expression as op2 double a=Double.parseDouble(op1); //op1 is converted into double type as a double b=Double.parseDouble(op2); //op2 is converted into double type as b int c=0; c=(int) ch; //stores the unicode value of the operator if (c==43) { //unicode value of + is 43 result=a+b; } else if(c==45) { //unicode value of - is 45 result=a-b; } else if(c==42) { //unicode value of * is 42 result=a*b; } else if(c==47) { //unicode value of / is 47 result=a/b; } } //function ends with the final value of result void print() { //function to display the string expression and the result calculate(); //function is called System.out.println("the expression given by the user "+expr); //string expression is displayed System.out.println(result); //result is displayed } //function ends

102

void main()throws IOException { //main function accept(); //input function is called print(); //print function is called } //main function ends } //class ends

OUTPUT enter a string containing digits and any of the arithmetic operators only 122/4 the expression given by the user 122/4 30.5

Question 19- Define a class Number with following specifications: Data members: int limit, (you can assume other data members also) Member functions: Number( ) Number(int L) int length(int n) : constructor to initialize limit=0. : constructor to initialize limit=L. : returns length of number n. Using recursion.

103

int power(int h) void automorphic( ) Writr main( ) for above class.

: returns 10 to power h(h>0). Using recursion. : to print all automorphic numbers by making use of appropriate functions from 1 to limit.

ALGORITHM
START STEP 1- Initialize a data member limit. STEP 3- 100 is assigned as value to limit. 1STEP 4- If n on being divided by 10 leaves 0 as quotient then 1 is returned else this step is again repeated with (n/10) acting as new n and returning value is incremented by 1 before returning. STEP 5- If h is equal to 0, 10 is returned else this step is repeated with (h-1) acting as new h and former returning value is multiplied by 10 and then returned. STEP 6- Initialize a variable i as 1. STEP 7- Step 4 is performed on i and returning value is stored in x. STEP 8- Step 5 is performed on x and returning value is stored in y. STEP 9- If (i*i) on being divided by y leaves i as remainder then i is an automorphic number and it is printed. STEP 10- Increment is value by 1 and repeat steps from 7 to 9 as long as it is less than or equal to limit. STOP

class Number { //class starts int limit; //data member for the limit Number() { //unparametrized constructor limit=0; } Number(int L)

104

{ //parametrized constructor limit=L; } int length(int n) { //function to return the number of digits to n if(n/10==0) { return 1; } else { //returns(1+calls again to the function) return(1+length(n/10)); } } //function ends int power(int h) { //function to return 10 to power h if(h==1) { //when 10 to power is 1,the number is 10 itself return 10; } else { //else the number is 10*(calls the function again(h-1)) return(10*power(h-1)); } } //function ends void automorphic() { //function to check if the number is automorphic or not for(int i=1;i<=limit;i++) { //loop from 1 to limit;iteration checks if i is automorphic or not int x=length(i); //calculates no. of digits of i as x int y=power(x); //calculates 10 to power x as y if((i*i)%y==i) //i is automorphic if remainder of i*i on being divided by y is i itself { //prints all the automorphic number from 1 to limit System.out.println(i);

105

} } } //function ends void main() { //main function Number ob=new Number(100); //object is created with an arguement ob.automorphic(); //automorphic function is called } //function ends } //class ends

OUTPUT 1 5 6 25 76

Question 20- Define a class Matrix with following specifications: Data members: int arr[ ][ ] a matrix of 3 X 3. Member functions: void input( ) Matrix multiplication(Matrix M1) : to input a 3X3 matrix. : to return multiplication of matrix M1 and current matrix object.

106

Matrix sort(Matrix M1) void print( ) Write main( ) for above class.

: to sort each row of matrix M1 in ascending order using selection sort and returns it. : to print the matrix.

ALGORITHM
START STEP 1- Create three matrices. STEP 2- For first two matrices, the size is 3. STEP 3- Values are inputted into the matrices and then printed. STEP 4- Initialize a variable k as 0. STEP 4- Initialize a variable i as 0. STEP 5- 0 is initialized as a value of new integer variable sum. STEP 6- Initialize a variable j as 0. STEP 7- sum is incremented with product of [k][j]th element of first matrix and [j][i]th element of second matix. STEP 8- Increment js value by 1 and repeat step 7 as long as it is less than 3. STEP 9- sums value is assigned to the [k][i]th element of third matrix. STEP 10- Increment is value by 1 and repeat steps from 5 to 9 as long as it is less than 3. STEP 11- Increment ks value by 1 and repeat steps from 4 to 10 as long as it is less than 3. STEP 12- Third matrix is printed. STEP 13- Initialize a variable i as 0. STEP 14- Selection sort of [i]th row of first matrix is performed STEP 15- Increment is value by 1 and repeat step 14 as long as it is less than 3. STEP 16- Print this sorted matrix. STOP

107

import java.io.*; class matrix { //class begins int arr[][]=new int[3][3]; //matrix is created void input()throws IOException { //values are inputted into the matrix BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter elements into the matrix"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { arr[i][j]=Integer.parseInt(in.readLine()); } } } void print() { //function to print the matrix System.out.println(); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { System.out.print(arr[i][j]+"\t"); } System.out.println(); } } //function over matrix sort(matrix m1) { //function to sort the rows of the matrix for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { //selection sort for each row

108

int sm=m1.arr[i][j]; int pos=j; for(int k=j+1;k<3;k++) { if(sm>m1.arr[i][k]) { sm=m1.arr[i][k]; pos=k; } } int t=m1.arr[i][j]; m1.arr[i][j]=m1.arr[i][pos]; m1.arr[i][pos]=t; //swapping done } //selection sort done } return m1; //object is returned } //function over matrix multiplication(matrix m1) { //function to multiply curent matrix matrix and M1 and then return it matrix obj=new matrix(); for(int k=0;k<3;k++) { for(int i=0;i<3;i++) { int sum=0; for(int j=0;j<3;j++) { sum=sum+arr[k][j]*m1.arr[j][i]; } obj.arr[k][i]=sum; } } return obj; //multiplied matrix is returned } //function over void main()throws IOException

109

{ //main function matrix ob1=new matrix(); //first object matrix ob2=new matrix(); //second object matrix ob3=new matrix(); //third object matrix ob4=new matrix(); //fourth object ob1.input(); ob1.print(); ob2.input(); ob2.print(); ob3=ob1.multiplication(ob2); System.out.println("multiplication of two matrices:"); ob3.print(); ob4=sort(ob1); System.out.println("sorted matrix"); ob4.print(); } //function over } //class ends

OUTPUT enter elements into the matrix 1 5 0 11 33

110

55 67 99 3 1 5 0 11 33 55 67 99 3 enter elements into the matrix 11 55 88 44 77 1 5 8 6 11 55 88 44 77 1 5 8 6 multiplication of two matrices: 231 1848 5108 sorted matrix 0 11 3 1 33 67 440 3586 11332 5 55 99 93 1331 6013

111

Potrebbero piacerti anche