NAME : Pankhudi Gupta CLASS : XII-D SUBJECT : COMPUTER SCIENCE YASHASVI SINGH PAGE 0 SESSION : 2022-2023 ACKNOWLEDGEMENT I would like to express my special thanks of gratitude to my teacher (Siddharth Sir) as well as our principal (Sangeeta ma’am) who gave me the golden opportunity to do this wonderful project on the topic,which also helped me in doing a lot of research and I came to know about so many new things I am really thankful to them. Secondly I would also like to thanks my parents and friends who helped me a lot in finalizing this project within the limited time frame. YASHASVI SINGH PAGE 1 INDEX S. No. Topic Page No. 1 Program 1 3-4 2 Program 2 5-7 3 Program 3 8 -10 4 Program 4 11-13 5 Program 5 14-16 6 Program 6 17-19 7 Program 7 20-21 8 Program 8 22-23 9 Program 9 24-26 10 Program 10 27-29 11 Program 11 30-32 12 Program 12 33-34 13 Program 13 35-36 14 Program 14 37-39 15 Program 15 40-42 16 Program 16 43-44 17 Program 17 45-47 18 Program 18 48-49 19 Program 19 50-52 20 Program 20 53-55 21 Program 21 56-57 22 Program 22 58-60 23 Program 23 61-62 YASHASVI SINGH PAGE 2 24 Program 24 63-65 25 Program 25 66-68 YASHASVI SINGH PAGE 3 Question 1. Design a class ArmNum to check if a given number is an Armstrong number or not. A number is said to be Armstrong if sum of its digits raised to the power of length of the number is equal to the number] [10] Example: 371 = 3^3 + 7^3 + 1^3 1634 = 1^4 + 6^4 + 3^4 + 4^4 54748 = 5^5 + 4^5 + 7^5 + 4^5 + 8^5 Thus, 371, 1634 and 54748 are all examples of Armstrong numbers. Some of the members of the class are given below: Class name: ArmNum Data members/instance variables: n: to store the number i: to store the length of the number Methods/Member functions: ArmNum (int nn): parameterized constructor to initialize the data member int sum_pow(int i): returns the sum of each digit raised to the power of the length of the number using recursive technique void isArmstrong(): checks whether the given number is an Armstrong number by invoking the function sum_pow () and displays an appropriate message. Specify the class ArmNum giving details of the constructor( ), int sum_pow(int) and void isArmstrong( ). Define a main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class named ArmNum Step 2: Input the number to be checked Step 3: Initialize the inputted variables in the Class Constructor Step 4: Make a for loop to to get the value of the place of each individual digit Step 5: Get the sum of digits using recursion Step 6: Check whether the following sum we got is an Armstrong number or not. Step 7: Now create the main method in which create object of the class, take the input no. from the user and then call the methods using the object created. Code : import java.io.*; import java.util.*; class ArmNum { YASHASVI SINGH PAGE 4 int n; int l; public ArmNum(int num) { n = num; l = 0; for(int i = n; i != 0; i/= 10) l++; } public int sumPow(int i) { if(i < 10) return (int)Math.pow(i, l); return (int)Math.pow(i % 10, l) + sumPow(i/10); } public void isArmstrong() { if(n == sumPow(n)) System.out.println(n+" is an Armstrong number."); else System.out.println(n+ " is not an Armstrong number."); } public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); System.out.print("Enter value of n ="); int num = sc.nextInt(); ArmNum obj = new ArmNum(num); obj.isArmstrong(); } } VDC : Variable N Datatype Int L Int I Num Int Int YASHASVI SINGH Description It is used to store the number input by the user to a universal variable. It is used to get the position of the digit in the number. It is used to run the for loop. It is used to store the number input by the user. PAGE 5 Output : YASHASVI SINGH PAGE 6 Question 2. Design a class MatRev to reverse each element of a matrix. [10] Some of the members of the class are given below: Class name: MatRev Data members/instance variables: arr[][]: to store integer elements m: to store the number of rows n: to store the number of columns Member functions/methods: MatRev(int mm, int nn) parameterized constructor to initialise the data members m = mm and n = nn void fillarray(): to enter elements in the array int reverse(int x): returns the reverse of the number x void revMat(MatRev P): reverses each element of the array of the parameterized object and stores it in the array of the current object void show(): displays the array elements in matrix form Define the class MatRev giving details of the constructor ( ), void fillarray (), int reverse(int), void revMat(MatRev) and void show(). Define the main () function to create objects and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class named MatRev Step 2: Take array size input Step 3: Initialize the input variables in the Class Constructor Step 4: Create two objects Step 5: Call method fillarray() to take input for the array Step 6: Call function revMath and in turn call recursion int reverse to reverse Step 7: Print the original and new Matrix Code : import java.io.*; import java.util.*; class MatRev{ int arr[][]; int m; int n; public MatRev(int mm, int nn) { m=mm; n = nn; arr=new int[m][n]; } YASHASVI SINGH //constructor to initialize variables PAGE 7 public void fillArray( )throws IOException{ //function to accept input from user Scanner sc = new Scanner(System.in); System.out.println("Enter matrix elements::"); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { arr[i][j] = sc.nextInt(); } } } public int reverse(int x) { //function to reverse the number int rev = 0; for(int i = x; i != 0; i /= 10) rev = rev * 10 + i % 10; return rev; } public void revMat(MatRev p) { for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { this.arr[i] [j] = reverse(p.arr[i] [j]); } } } public void show() { //displays the outpuut for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { System.out. print(arr[i][j] + "\t"); } System.out.println(); } } public static void main(String args[])throws IOException{ //main method Scanner sc = new Scanner(System.in); System.out.print("Enter number of rows::"); int x = sc.nextInt(); System.out.print("Enter number of columns::"); int y = sc.nextInt(); MatRev obj1 = new MatRev(x, y); //object 1 MatRev obj2 = new MatRev(x, y); //object 2 obj1.fillArray(); obj2.revMat(obj1); System.out.println("Original Matrix is::"); obj1.show(); System.out.println("Matrix with reversed elements"); obj2.show(); } YASHASVI SINGH PAGE 8 } VDC : Variable n j i y arr[][] Datatype Int Int Int Int Int Description Size of array It is used to run the for loop. It is used to run the for loop. Size of array Array to store elemnts Output : YASHASVI SINGH PAGE 9 Question 3. A class Rearrange has been defined to modify a word by bringing all the vowels in the word at the beginning followed by the consonants. [10] Example: ORIGINAL becomes OIIARGNL Some of the members of the class are given below: Class name: Rearrange Data Member/instance variable: wrd: to store a word newwrd: to store the rearranged word Member functions/methods: Rearrange(): default constructor void readword(): to accept the word in UPPER case vow freq_vow_con(): finds the frequency of vowels and consonants in the word and displays them with an appropriate message void arrange(): rearranges the word by bringing the vowels at the beginning followed by consonants void display(): displays the original word along with the rearranged word Specify the class Rearrange, giving the details of the constructor(), void readword(), void freq_vow_con(), void arrange() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Rearrange Step 1: Take the word input Step 3:Take the first character of the word Step 4:Make a switch case Step 5:Add the letter in any variable lets say v (if it is a vowel) and c (if it is a consonant) Step 6: Add both the variable, we will get the modified word. Code : import java.io.*; import java.util.*; class Rearrange { String wrd; String newwrd; public Rearrange() { wrd = new String(); //constructor to initialize variables YASHASVI SINGH PAGE 10 newwrd = new String(); } public void readword() throws IOException { //method to take input Scanner sc = new Scanner(System.in); System.out.print("Enter the word:"); wrd = sc.nextLine(); } public void freq_vow_con() { //frequency of vowels and consonant wrd = wrd.toUpperCase(); //converts string to uppercase int v = 0; int c = 0; for(int i = 0; i < wrd.length(); i++) { char ch = wrd.charAt(i); if(Character.isLetter(ch)) { switch(ch) { case 'A': case'E': case 'I': case 'O': case 'U': v++; break; default: c++; } } } System.out.println("Frequency of vowels: "+v); System.out.println("Frequency of consonants: "+c); } public void arrange() { String v = new String(); String c = new String(); wrd = wrd.toUpperCase(); for(int i = 0; i < wrd. length(); i++) { char ch = wrd.charAt(i); if(Character.isLetter(ch)) { switch(ch) { case 'A': case'E': case 'I': case 'O': case 'U': v += ch; break; default: YASHASVI SINGH PAGE 11 c += ch; } } } newwrd = v + c; } public void display() { //displays the result System.out.println("Original word:" + wrd); System.out.println("Rearranged word:" + newwrd); } public static void main(String args[])throws IOException { Rearrange obj = new Rearrange(); //creates object obj obj.readword(); obj.freq_vow_con(); obj.arrange(); obj.display(); } } VDC : Variable v c wrd newwrd Data Type String String String String Description Stores vowels Stores consonants Stores input word Stores new word Output : YASHASVI SINGH PAGE 12 Question 4. An emirp number is a number which is prime backwards and forwards. Example: 13 and 31 are both prime numbers. Thus, 13 is an emirp number. [10] Design a class Emirp to check if a given number is Emirp number or not. Some of the members of the class are given below: Class name: Emirp Data members/instance variables: n: stores the number rev: stores the reverse of the number f: stores the divisor Member functions: Emirp(int nn): to assign n = nn, rev = 0 and f = 2 int isprime(int x): check if the number is prime using the recursive technique and return 1 if prime otherwise return 0 void isEmirp(): reverse the given number Check if both the original number and the reverse number prime, by invoking the function isprime(int) and display the result with an appropriate message Specify the class Emirp giving details of the constructor(int), int isprime (int) and void isEmirp(). Define the main function to create an object and call the methods to check for Emirp number. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class emirp Step 2: Insert three integer type variables. Step 3: Create a class constructor to initialize the following integers. Step 4: Create a parameterized function (int isprime(int x)) to check whether the number is prime or not. Step 5: Create a parameterized function void isEmirp()) to reverse the number and then check whether the reversed number is prime or not using the function on Step 5. Step 6: Now create the main method to create object of the class and then input number by the user, then call the function using class object. Code : import java.util.*; class Emirp { int n,rev,f; Emirp(int nn) { n=nn; rev=0; f=2; //constructor to initialize variables YASHASVI SINGH PAGE 13 } int isprime(int x) { if(n==x) return 1; else if (n%x == 0 ||n == 1) return 0; else return isprime(x+1); } void isEmirp() { int x=n; while(x!=0) { rev=(rev* 10) + x%10; x=x/10; } int ans1=isprime(f); n=rev; f=2; int ans2=isprime(f); System.out.println(n + “Reversed number \n Therefore” ); while(x!=0) { rev=(rev* 10) + x%10; x=x/10; } if(ans1==1 && ans2==1) { System.out.println(n+" is an Emirp number"); else System.out.println(n+" is not an Emirp number"); } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter a number: "); int x=sc.nextInt(); Emirp obj = new Emirp(x); obj.isEmirp(); } // checks for prime //copy of number //reverses the number //checks for prime //checks for prime //reverse the number //main method } YASHASVI SINGH PAGE 14 VDC: Variable Data Type Description n Int rev Int f x ans1,ans2 Int Int Int It is used to store the number input by the user. It is used to calculate and store the reverse of a number. It is used to stores the divisor. It is used to Output : YASHASVI SINGH PAGE 15 Question 5. Design a class Exchange to accept a sentence and interchange the first alphabet with the last alphabet for each word in the sentence, with single-letter word remaining unchanged. The words in the input sentence are separated by a single blank space and terminated by a full stop. [10] Example: Input: It is a warm day. Output: tI si a mraw yad Some of the data members and member functions are given below: Class name: Exchange Data members/instance variables: sent: stores the sentence rev: to store the new sentence size: stores the length of the sentence Member functions: Exchange(): default constructor void readsentence(): to accept the sentence void exfirstlast(): extract each word and interchange the first and last alphabet of the word and form a new sentence rev using the changed words void display(): display the original sentence along with the new changed sentence. Specify the class Exchange giving details of the constructor ( ), void readsentence (), void exfirstlast () and void display (). Define the main () function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Exchange Step 2: Create method/function readsentence to accept and store string input Step 3: Calculate the size of the string Step 3: Call function exfirstlast and trim out each word Step 4: Change the first and last letters of the world Step 5: Create a method/function exfirstlast() to reverse the string as per given condition Step 6: Return the reversed string Step 7: Create method display() and print the reversed string Code : import java.util.Scanner; public class Exchange { YASHASVI SINGH PAGE 16 String sent,rev; int size; Exchange() //constructor to initialize variables { sent=""; rev=""; size=0; } void readsentence() //input from user { Scanner sc=new Scanner(System.in); System.out.print("Enter a sentence"); sent=sc.nextLine(); size=sent.length(); } void exfirstlast() { char ch=' '; String wd=""; for(int i=0;i< size;i++) { ch=sent.charAt(i); if(ch==' '||ch=='.') { if(wd.length()>1) { rev=rev + wd.charAt(wd.length()-1); //last character// rev=rev + wd.substring(1,wd.length()-1); //middle characters// rev=rev + wd.charAt(0); //first character// rev=rev+ch; //space or full stop// } else { rev=rev+wd+ch; } wd=""; } else { wd=wd+ch; } } } void display() { //displays the result YASHASVI SINGH PAGE 17 System.out.println("Input:"+sent); System.out.println("Output: "+rev); } public static void main() { Exchange obj1=new Exchange(); obj1.readsentence(); obj1.exfirstlast(); obj1.display(); } //object to call the methods } VDC : VARIABLE Sent Rev Size Ch Wb DATA TYPE String String Int Char String DESCRIPTION Stores input statement from user Stores the reversed statement Stores the size of string input Stores character at given index Stores reverse sentence Output : YASHASVI SINGH PAGE 18 Question 6. A class Matrix contains a two-dimensional integer array of an order [m * n]. The maximum value possible for both ‘m’ and ‘n’ is 25. Design a class Matrix to find the difference between the two matrices. The details of the members of the class are given below: [10] Class name: Matrix Data members/instance variables: arr[][]: stores the matrix element m: integer to store the number of rows n: integer to store the number of columns Member functions: Matrix (int mm, int nn): to initialize the size of the matrix m=mm and n = nn void fillarray(): to enter the elements of the matrix Matrix SubMat(Matrix A): subtract the current object from the matrix of the parameterized object and return the resulting object void display(): display the matrix elements Specify the class Matrix giving details of the constructor(int, int), void fillarray(), Matrix SubMat (Matrix) and void display (). Define the main ( ) function to create objects and call the methods accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Matrix Step 2: Take input of size of Matrix Step 3: If size of either row or column greater than 25 print terminate program with error Step 1: Define three new matrix let’s say A,B,C Step 2: Call function fillarray() and fill array A and B Step 3: Subtract the matrices using the function subMat using B as the argument Step 4: Save the resulting matrix in C Step 5: Call function display() to display C Code : import java.util. Scanner; public class Matrix { int m,n; int arr[][]; Matrix(int mm, int nn) { m=mm; n=nn; arr=new int[m][n]; //constructor to initialize variables YASHASVI SINGH PAGE 19 } void fillarray() //input by user { Scanner sc=new Scanner(System.in); System.out.println("Enter "+(m*n)+" elements of array"); for(int i=0;i<m;i++) { for(int j=0;j<n; j++) arr[i][j]=sc.nextInt(); } } Matrix SubMat(Matrix A) //difference between two arrays { Matrix B=new Matrix(m,n); for(int i=0;i<m;i++) { for(int j=0;j<n; j++) B.arr[i][j]= arr[i][j] - A.arr[i][j]; } return B; } void display() //displays the result { for(int i=0;i<m;i++) { System.out.println(); { for(int j=0;j<n;j++) System.out.print(arr[i][j] +" \t"); } } } public static void main(String args[]) { Scanner sc1=new Scanner(System.in); System.out.println("Enter no. of Rows:"); //size of rows int x = sc1.nextInt(); System.out.println("Enter no. of Column:"); //size of columns int y = sc1.nextInt(); if(x>25 || y>25) { System.out.println("Rows and Column cannout be greater than 25."); System.exit(0); } Matrix A=new Matrix(x, y); //objct 1 YASHASVI SINGH PAGE 20 Matrix B=new Matrix(x, y); Matrix C=new Matrix(x, y); A.fillarray(); B.fillarray(); C=A.SubMat(B); C.display(); //object 2 //object 3 } } VDC : VARIABLE i j m n DATA TYPE Int Int Int Int DESCRIPTION Runs loop Runs loop Store the number of rows Stores the number of columns Output : YASHASVI SINGH PAGE 21 Question 7. A class Palin has been defined to check whether a positive number is a Palindrome number or not. [10] The number ‘N’ is palindrome if the original number and its reverse are the same. Some of the members of the class are given below: Class name: Palin Data members/instance variables: num: integer to store the number revnum: integer to store the reverse of the number Methods/Member functions: Palin(): constructor to initialize data members with legal initial values void accept(): to accept the number int reverse(int y): reverses the parameterized argument ‘y’ and stores it in revenue using a recursive technique void check(): checks whether the number is a Palindrome by invoking the function reverse() and display an appropriate message Specify the class Palin giving the details of the constructor (), void accept(), int reverse(int) and void check(). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class named Palin Step 2: Create and call method/function “accept” the values Step 3: Create “reverse” method/function Step 4: Find the reverse of the number using recursion Step 5: Return the reversed number Step 6: If the reversed no. is equal to input no. Print Positive result else negative result Code : import java.util.Scanner; public class Palin { int num,revnum; Scanner sc=new Scanner(System.in); Palin() { revnum = num= 0; } void accept() { System.out.println( "Enter a number") ; num=sc.nextInt(); } YASHASVI SINGH //constructor // accepts input PAGE 22 int reverse( int y) //reverses the number { if(y>0) { revnum =revnum * 10 + (y%10); return reverse(y/10); } else { return revnum; } } void check() //checks for palindrome { if( num==reverse(num)) { System.out.println(num+" is palindrome number") ; } else { System.out.println(num +" is not a palindrome number") ; } } public static void main() { Palin ob1=new Palin(); //object to call method functions ob1.accept() ; ob1.check() ; } } VDC : Variable num revnum y Data Type Int Int Int Description Store input by user Store the reversed number Copy of input number Output : YASHASVI SINGH PAGE 23 Question 8. A class Adder has been defined to add any two accepted time. [10] Example: Time A – 6 hours 35 minutes Time B – 7 hours 45 minutes Their sum is – 14 hours 20 minutes (where 60 minutes = 1 hour) The details of the members of the class are given below: Class name: Adder Data member/instance variable: a[ ]: integer array to hold two elements (hours and minutes) Member functions/methods: Adder (): constructor to assign 0 to the array elements void readtime (): to enter the elements of the array void addtime (Adder X, Adder Y): adds the time of the two parameterized objects X and Y and stores the sum in the current calling object void disptime(): displays the array elements with an appropriate message (i.e., hours= and minutes=) Specify the class Adder giving details of the constructor( ), void readtime( ), void addtime(Adder, Adder) and void disptime(). Define the main() function to create objects and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class names Adder Step 2: Initalize two object A and B Step 3: Accept values by using the method readtime() Step 4: Add the given values of time by using the method addtime() Step 5: Display the output time by using the method disptime() Code : import java. util.Scanner; public class Adder { int a[]=new int[2]; Scanner sc=new Scanner( System.in); Adder() { a[0]=0; a[1]=0; } void readtime() { YASHASVI SINGH //input by user PAGE 24 System.out.println("Enter hours and minutes"); a[0]=sc. nextInt(); a[1]=sc. nextInt(); } void disptime() //displays the output { System. out.println("Hours=" + a[0]); System.out.println("Minutes=" + a[ 1]); } void addtime(Adder X,Adder Y) { a[1]=X.a[1] + Y.a[1]; //adds minutes if(a[1]>=60) //if minutes is greater than 60 than add hours(a[1]/60) to a[0] position { a[0]=a[1]/60; a[1]=a[1]%60; } a[0] += X.a[0] + Y.a[0]; } public static void main() { Adder ob1=new Adder(); //object 1 Adder ob2=new Adder(); //object 2 Adder ob3=new Adder(); //object 3 ob1.readtime(); ob2.readtime() ; ob3.addtime(ob1,ob2); //calling method to add time ob3.disptime(); } } VDC : Variable a[] Data Type int Description Stores input value Output : YASHASVI SINGH PAGE 25 Question 9. A class SwapSort has been defined to perform string related operations on a word input. Some of the members of the class are as follows: [10] Class name: SwapSort Data members/instance variables: wrd: to store a word len: integer to store the length of the word swapwrd: to store the swapped word sortwrd: to store the sorted word Member functions/methods: SwapSort(): constructor to initialize data members void readword(): to accept a word in UPPER CASE void swapchar(): to interchange/swap the first and last characters of the word in ‘wrd’ and stores the new word in ‘swapwrd’ void sortword(): sorts the characters of the original word in alphabetical order and stores it in ‘sortwrd’ void display(): displays original word, swapped word and the sorted word Specify the class SwapSort, giving the details of the constructor(), void readword(), void swapchar(), void sortword() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class name SwapSort. Step 2: Declare the instance variablesString type and Int type(wrd,swapwrd,sortwrd,len) Step 3: Initialize the instance variables in class constructor(SwapSort()). Step 4: Create a method named readword() to accept a word in Upper Case by the User. Step 5: Now, create another method named swapchar() to swap the first and last character of the word. Step 6: Now, create another method named sortword() to sort the characters of the word in ascending order. Step 7: Now, create another method named display() to print the original word along with its swapped version and the sorted version. Step 8: Now, create main method to create an object of the class then call all the methods inside of the class using the object. Code : import java .util.Scanner; public class SwapSort { String wrd,swapwrd,sortwrd; int len; Scanner sc=new Scanner(System.in) ; SwapSort() //constructor YASHASVI SINGH PAGE 26 { swapwrd="" ; sortwrd=" "; len=0; wrd=""; } void readword() //function to take input { System.out.println("Enter word in Upper case"); wrd=sc.next() ; len=wrd.length(); wrd=wrd.toUpperCase(); } void swapchar() { swapwrd=swapwrd+wrd.charAt(len-1); //add last character of word to swapwrd swapwrd=swapwrd+ wrd.substring(1,len-1); //add character between first and last char of word swapwrd=swapwrd + wrd.charAt(0); //add first character to swapwrd } void sortword() //sorts the word { char ch1; for(char ch='A' ;ch<='Z';ch++) { for(int i=0 ;i < len;i++) { ch1=wrd.charAt(i); if(ch1==ch) { sortwrd += ch1; } } } } void display() //function to print the output { System.out.println("Original word = " + wrd); System.out.println("Swapped word = " + swapwrd); System.out.println("Sorted word = " + sortwrd); } public static void main() //main method { SwapSort ob1=new SwapSort(); //object creation ob1.readword() ; ob1.swapchar(); ob1.sortword(); ob1.display(); } } YASHASVI SINGH PAGE 27 VDC : Variable wrd len swapwrd Ch1 Data Type String Int String Char Description To store a word To store length of the word To store the swapped word Runs loop Output : YASHASVI SINGH PAGE 28 Question 10. A class Shift contains a two-dimensional integer array of order (m×n) where the maximum values of both m and n are 5. Design the class Shift to shuffle the matrix (i.e. the first row becomes the last, the second row becomes the first and so on). The details of the members of the class are given below: [10] Class name: Shift Data member/instance variable: mat[][]: stores the array element m: integer to store the number of rows n: integer to store the number of columns Member functions/methods: Shift(int mm, int nn): parameterized constructor to initialize the data members m=mm and n=nn void input(): enters the elements of the array void cyclic(Shift p): enables the matrix of the object (P) to shift each row upwards in a cyclic manner and store the resultant matrix in the current object void display(): displays the matrix elements Specify the class Shift giving details of the constructor(), void input(), void cyclic(Shift) and void display(). Define the main() function to create an object and call the methods accordingly to enable the task of shifting the array elements. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class name Shift. Step 2: Declare the instance variables of Int type(mat[][], m, n) Step 3: Initialize the instance variables in parameterized class constructor (Shift (int mm, int nn)). Step 4: Create a void method named input, to fill the elements in the array by the user inputs. Step 5: Create a void class cyclic that enables the matrix of the object (P) to shift each row upwards in a cyclic manner and store the resultant matrix in the current object. Step 6: Create a void method display() to display the matrix elements of either original or shifted matrix. Step 7: Create the main method to create object of the class and execute the folllowing methods. Code : import java.util.Scanner; public class Shift { Scanner sc=new Scanner(System.in); YASHASVI SINGH PAGE 29 int mat[][]; int m,n; Shift(int mm,int nn) //constructor to initialize the variables { m=mm; n=nn; mat=new int[m][n]; } void input() //method to take input from user { System.out.println("Enter elements of array"); for(int i=0;i< m;i++) { for(int j=0;j< n;j++) { mat[i][j]=sc.nextInt(); } } } void display() //method to display the output { for(int i=0;i< m;i++) { for(int j=0;j< n;j++) { System.out.print(mat[i][j]+" "); } System.out.println(); } } void cyclic(Shift P) { for(int i=0;i< m;i++) { for(int j=0;j< n;j++) { if(i==0) { mat[m-1][j]=P.mat[0][j]; } else { mat[i-1][j]=P.mat[i][j]; } } } YASHASVI SINGH PAGE 30 } public static void main(String args[]) { Scanner sc1=new Scanner(System.in); System.out.println("ENTER THE NUMBER OF ROWS"); int r=sc1.nextInt(); System.out.println("ENTER THE NUMBER OF COLUMNS"); int c=sc1.nextInt(); Shift ob1=new Shift(r,c); Shift ob2=new Shift(r,c); ob1.input(); ob2.cyclic(ob1); System.out.println("Original Matrix:"); ob1.display(); System.out.println("Shifted Matrix:"); ob2.display(); } } VDC : Variable Datatype Mat[][] array m int n int mm int nn int Description A double dimensional array to store the elements of the matrix and shift its rows. It is a variable used to store the total number of rows in the matrix It is a variable used to store the total number of columns in the matrix It is a variable used to pass a value in the class constructor. It is a variable used to pass a value in the class constructor. Output : YASHASVI SINGH PAGE 31 Question 11. A class ConsChange has been defined with the following details: [10] Class name: ConsChange Data members/instance variables: word: stores the word len: stores the length of the word Member functions/methods: ConsChange(): default constructor void readword(): accepts the word in lowercase void shiftcons(): shifts all the consonants of the word at the beginning followed by the vowels (e.g. spoon becomes spnoo) void changeword(): changes the case of all occurring consonants of the shifted word to uppercase, for e.g. (spnoo becomes SPNoo) void show(): displays the original word, shifted word and the changed word Specify the class ConsChange giving the details of the constructor ), void readword ( ), void shiftcons (), void changeword() and void show(). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class named ConsChange Step 2: Declare int word and length Step 3: Create an object Step 4: Call function readword() to accept input Step 5: Call functions show() Step 6: Call functions shiftcons() and changeword() and therby display the result Code : import java.util.Scanner; public class ConsChange { String word; int len; Scanner sc=new Scanner(System.in); ConsChange() //constructor to initialize variables { len=0; word=""; } void readword() //method to take input from user { System.out.println("Enter word in Lowercase"); word=sc.next(); YASHASVI SINGH PAGE 32 len=word.length(); } void shiftcons() //method to shift consonant { String consonants="",vowels="",sortedWord=""; char ch=' '; for(int i=0;i< len;i++) { ch=word.charAt(i); if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') //checks if it is a vowel vowels+=ch; else consonants+=ch; } sortedWord=consonants+vowels; System.out.println("Sorted Word="+sortedWord); word=sortedWord; } void changeword() { char ch=' '; String newWd=""; for(int i=0;i< len;i++) { ch=word.charAt(i); if(ch!='a'&&ch!='e'&&ch!='i'&&ch!='o'&&ch!='u') newWd+=Character.toUpperCase(ch); else newWd+=ch; } System.out.println("Changed word="+newWd); } void show() //method to display the results { System.out.println("Originalword="+word); shiftcons(); changeword(); } public static void main() //main method { ConsChange ob1=new ConsChange(); ob1.readword(); ob1.show(); } } YASHASVI SINGH PAGE 33 VDC : Variable word Len Data Type String Int Description To store a word To store length of the word ch newWd Char String Check variable To store changed word Output : YASHASVI SINGH PAGE 34 YASHASVI SINGH PAGE 35 Question 12. A class Admission contains the admission numbers of 100 students. Some of the data members/member functions are given below: [10] Class name: Admission Data member/instance variable: adno[]: integer array to store admission numbers Member functions/methods: Admission(): constructor to initialize the array elements void fillArray(): to accept the elements of the array in ascending order int binSearch(int l, int u, int v): to search for a particular admission number (v) using binary search and recursive technique and returns 1 if found otherwise returns -1 Specify the class Admission giving details of the constructor, void fill Array() and int binSearch(int l, int u, int v). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class name Admission. Step 2: Declare the instance variables of int type(adno[]) Step 3: Initialize the instance variables in class constructor (Admission()). Step 4: Create a void method named fillArray(), to fill the elements in the array by the user inputs in ascending order. Step 5: Create a parameterized int method named binSearch to search for a particular admission number (v) using binary search and recursive technique and returns 1 if found otherwise returns -1. Step 7: Create the main method to create an object and call the functions accordingly to enable the task. Code : import java.util.Scanner; public class Admission { Scanner sc=new Scanner(System.in); int adno[]; Admission() adno=new int[100]; void fillArray() { System.out.println("Enter 100 elements in ascending order"); YASHASVI SINGH //constructor to initialize variables PAGE 36 for(int i=0;i< 100;i++) adno[i]=sc.nextInt(); } int binSearch(int l,int u,int v) { int m=(l+u)/2; if(adno[m]==v) return 1; else if(l> u) return -1; else if(v>adno[m]) return binSearch(m+1,u,v); else return binSearch(l,m-1,v); } public static void main() { Scanner sc1=new Scanner(System.in); Admission ob1=new Admission(); ob1.fillArray(); System.out.println("Enter value to be searched"); int v=sc1.nextInt(); int p=ob1.binSearch(0,ob1.adno.length-1,v); if(p==-1) System.out.println(v+" not found in the array"); else System.out.println(v+" is found in the array"); } //searches for the value //main method //object to call method //calls fillArray to take input in array //takes input of value to be searched } VDC : Variable adno[] l Datatype int int u v int int Description An array to store 100 elements. It stores the position of the element to be found. It stores the length of the array. It stores the number to be found in the array. Output : . . YASHASVI SINGH PAGE 37 Question 13. A class Merger concatenates two positive integers that are greater than 0 and produces a newly merged integer. Example: If the first number is 23 and the second is 764, then the concatenated number will be 23764. Some of the members of the class are given below: Class name: Merger Data members/instance variables: n1: long integer to store the first number n2: long integer to store the second number mergNum: long integer to store the merged number Member functions: Merger(): constructor to initialize the data members void readNum(): to accept the values of the data members n1 and n2 void joinNum(): to concatenate the numbers n1, n2 and store it in mergNum void show(): to display the original numbers and the merged number with appropriate messages Specify the class Merger giving the details of the constructor, void readNum(), void joinNum() and void show(). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Merger Step 2: Declare variables n1 and n2 Step 3: Initialize the variable in a constructor Step 4: Create object and call function readNum() to accept the numbers Step 5: Call function joinNum() to concatenate n1 and n2 Step 6: Call function show() to display the concatenated number. Code : import java.util.Scanner; public class Merger { long nl,n2,mergNum; Merger() //constructor to initialize the variables { nl=n2=mergNum=0; } void readNum() //method to take input { Scanner sc=new Scanner(System.in); System.out.println("Enter two numbers"); nl=sc.nextLong(); YASHASVI SINGH PAGE 38 n2=sc.nextLong(); } void JoinNum() //method to concats the number { String s1=Long.toString(nl); String s2=Long.toString(n2); String s3=s1+s2; mergNum=Long.valueOf(s3); } void show() //function to display the result { System.out.println("First Number="+nl); System.out.println("Second Number="+n2); System.out.println("Merged Number="+mergNum); } public static void main() //main method { Merger ob1=new Merger(); //object to call methods and function ob1.readNum(); ob1.JoinNum(); ob1.show(); } } VDC : Variable n1 n2 s1 s2 s3 Data Type Long Long String String String Description Input from user Input from user Stores n1 in string format Stores n2 in string format Stores concatenated no. Output : YASHASVI SINGH PAGE 39 Question 14. A class Mixer has been defined to merge two sorted integer arrays in ascending order. Some of the members of the class are given below: [10] Class name: Mixer Data members/instance variables: int arr[ ]: to store the elements of an array int n: to store the size of the array Member functions: Mixer(int nn): constructor to assign n=nn void accept(): to accept the elements of the array in ascending order without any duplicates Mixer mix (Mixer A): to merge the current object array elements with the parameterized array elements and return the resultant object void display(): to display the elements of the array Specify the class Mixer, giving details of the constructor(int), void accept(), Mixer mix(Mixer) and void display(). Define the main( ) function to create an object and call the function accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class name Mixer. Step 2: Declare the instance variables of int type(arr[], n) Step 3: Initialize the instance variables in parameterized class constructor (Mixer(int nn)). Step 4: Create a void method named accept(), to accept the elements of the array in ascending order without any duplicates Step 5: Create a parameterized int method named Mixer mix (Mixer A) to merge the current object array elements with the parameterized array elements and return the resultant object. Step 6: Create a void method display() to display the matrix elements. Step 7: Create the main method to create an object and call the functions accordingly to enable the task. Code : import java.util.Scanner; public class Mixer { int arr[]; int n; Scanner sc=new Scanner(System.in); Mixer(int nn) { YASHASVI SINGH //constructor to initialize the variables PAGE 40 n=nn; arr=new int[n]; } void accept() //method to accept input { System.out.println("Enter "+n+" elements in ascending order"); for(int i=0;i< n;i++) { arr[i]=sc.nextInt(); } } Mixer Mixer(Mixer A) { Mixer B=new Mixer(n+A.n); int x=0; for(int i=0;i< n;i++) { B.arr[x++]=arr[i]; } for(int j=0;j< A.n;j++) { B.arr[x++]=A.arr[j]; } return B; } void display() //method to display result { for(int i=0;i< n;i++) { System.out.print(arr[i]+" "); } } public static void main(String args[]) //main method { Scanner sc1=new Scanner(System.in); System.out.println("ENTER SIZE OF FIRST ARRAY"); int sizeOfFirstArray=sc1.nextInt(); //stores size of first array Mixer P=new Mixer(sizeOfFirstArray); P.accept(); System.out.println("ENTER SIZE OF SECOND ARRAY"); int sizeOfSecondArray=sc1.nextInt(); //stores size of second array Mixer Q=new Mixer(sizeOfSecondArray); Q.accept(); Mixer R=P.Mixer(Q); R.display(); } YASHASVI SINGH PAGE 41 } VDC : Variable Datatype Arr[] int n nn int int i int Description It is an array used to store elements. It stores the length of the array. It is a variable used to pass the value to the class constructor. It is a variable used to control the flow of the for loop. Output : YASHASVI SINGH PAGE 42 Question 15. A class SeriesSum is designed to calculate the sum of the following series: 𝑥^2 𝑥^4 𝑥^6 𝑥^𝑛 Sum = 1! + 3! + 5! +………… (𝑛−1)! Some of the members of the class are given below: Class name: SeriesSum Data members/instance variables: x: to store an integer number n: to store the number of terms sum: double variable to store the sum of the series Member functions: SeriesSum(int xx, int nn): constructor to assign x=xx and n=nn double findfact(int m): to return the factorial of m using the recursive technique. double find power(int x, int y): to return x raised to the power of y using the recursive technique. void calculate(): to calculate the sum of the series by invoking the recursive functions respectively void display(): to display the sum of the series (a) Specify the class SeriesSum, giving details of the constructor(int, int), double find fact(int), double find power(int, int), void calculate() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task. [8] (b) State the two differences between iteration and recursion. [2] -------------------------------------------------Answer -----------------------------------------------(A) Algorithm : Step 1: Create a class SeriesSum Step 2: Declare variable x, n and sum Step 3: Take input of the number and no of terms from user and assign it to x and n in constructor Step 4: Call the function calculate Step 5: Call the functions findpower() and findfact() and calculate the sum Step 6: Call the function display() and print the sum Code : import java.util.Scanner; public class SeriesSum { int x,n; double sum; SeriesSum(int xx,int nn) //constructor to initialize the variables YASHASVI SINGH PAGE 43 { x=xx; n=nn; sum=0.0; } double findfact(int a) //returns factorial of the number { if(a==1) { return 1; } else { return a* findfact(a-1); } } double findpower(int a,int b) //returns number to its nth power { if(b==0) { return 1; } else { return a* findpower(a,b-1); } } void calculate() { int k=2; for(int i=1;i<=n;i++) { sum+=findpower(x,k)/findfact(k-1); //calling method findpower and findfact to calculate respective data k=k+2; } } void display() { System.out.println("sum="+sum); //prints the sum of the series } public static void main() { Scanner sc=new Scanner(System.in); System.out.println("ENTER A NUMBER"); int a=sc.nextInt(); System.out.println("ENTER NUMBER OF TERMS"); int b=sc.nextInt(); SeriesSum obj1=new SeriesSum(a,b); obj1.calculate(); obj1.display(); } } YASHASVI SINGH PAGE 44 (b) Iteration: Fast process and less memory. Recursion: Slow process and more memory. VDC : Variable Datatype x n int int sum int Description It is used to store and integer It is a variable used to store an integer value. It is a variable used to store the number to terms of the series. Output : YASHASVI SINGH PAGE 45 Question 16. A sequence of Fibonacci strings is generated as follows: S0 = “a”, SF = “b”, Sn = S(n-1) + S(n-2) where ‘+’ denotes concatenation. Thus the sequence is: a, b, ba, bab, babba, babbabab,……. n terms. [10] Design a class FiboString to generate Fibonacci strings. Some of the members of the class are given below: Class name: FiboString Data members/instance variables: x: to store the first string y: to store the second string z: to store the concatenation of the previous two strings n: to store the number of terms Member functions/methods: FiboString(): constructor to assign x=”a”, y=”b” and z=”ba” void accept(): to accept the number of terms ‘n’ void generate(): to generate and print the Fibonacci strings. The sum of (‘+’ ie concatenation) first two strings is the third string Specify the class FiboString, giving details of the constructor(), void accept() and void generate(). Define the main() function to create an object and call the functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1:Create a class FiboString . Step 2:Create three variable x, y, z . Step 3:Create a constructor to initialize these variables. Step 4:Create function accept() to take input. Step 5:Create generate() to make the Fibonacci series and print it. Code : import java.util.*; class FiboString { String x,y,z; int n; FiboString() { x="a"; y="b"; z="ba"; } void accept() //constructor to intilialize variables //function to take input from user YASHASVI SINGH PAGE 46 { Scanner Sc = new Scanner (System.in); System. out.println ("Enter number of terms"); n = Sc.nextInt(); } void generate() { System. out.print(x+","+y); for(int i=0; i<=n-2; i++) { System.out.print(","+z); x=y; y=z; z=y+x; z= y.concat(x); } } //function to calculate Fibonacci string static void main() { FiboString obj=new FiboString(); obj.accept(); obj.generate(); } //main method } VDC: Datatype Description Variable x y z n String String String int Stores the value of y after each iteration Stores the value of z after each iteration Stores the sum of x and y Takes input of the user for the number of terms Output: YASHASVI SINGH PAGE 47 Question 17. A class Combine contains an array of integers which combines two arrays into a single array including the duplicate elements, if any, and sorts the combined array. Some of the members of the class are given below: [10] Class name: Combine Data Members/instance variables: com[]: integer array size: size of the array Member functions/methods: Combine(nt nn): parameterized constructor to assign size = nn void inputarray(): accepts the array elements. void sort(): sorts the elements of the combined array in ascending order using selection sort technique. void mix(Combine A, Combine B): combines the parameterized object arrays and stores the result in the current object array along with duplicate elements, if any. void display(): displays the array elements Specify the class Combine giving details of the constructor (int), void inputarray(), void sort(), void mix (Combine, Combine) and void display (). Also, define the main() function to create an object and call the methods accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Combine Step 2: Take input of size of array1 and call function inputarray() to accept input in array with object P Step 3: Take input of size of array2 and call function inputarray() to accept input in array with object q Step 4: Create a new object R Step 5: Call function mix() from object R Step 6: Sort the array using function sort() from object R Step 7: Call the display() function from object R Code: import java.util.Scanner; public class Combine { int com[]; int size; Scanner sc=new Scanner(System.in); Combine(int nn) { YASHASVI SINGH //constructor to initialize variables PAGE 48 size=nn; com=new int[size]; } void inputarray() //function to take input in array { System.out.println("Enter "+size+" elements"); for(int i=0;i< size;i++) { com[i]=sc.nextInt(); } } void sort() //function to sort array { int t; for(int i=0;i< size;i++) { for(int j=i;j< size;j++) { if(com[j]< com[i]) { t=com[j]; com[j]=com[i]; com[i]=t; } } } } void mix(Combine A,Combine B) //function to combine both the arrays { int x=0,y=0,z=0; while(x< A.size) { com[z++]=A.com[x++]; } while(y< B.size) { com[z++]=B.com[y++]; } } void display() //function to print the final array { for(int i=0;i< size;i++) { System.out.print(com[i]+" "); } } public static void main() //main method { Scanner sc1=new Scanner(System.in); System.out.println("\n enter size of first array"); YASHASVI SINGH PAGE 49 int a=sc1.nextInt(); //size of 1st array Combine P=new Combine(a); //object 1 P.inputarray(); System.out.println("\n Enter size of Second array"); int b=sc1.nextInt(); //size of 2nd array Combine Q=new Combine(b); //object 2 Q.inputarray(); Combine R=new Combine(a+b); //object 3 R.mix(P,Q); //calling function to merge both arrays R.sort(); //calling function to sort final array System.out.println("Array 1:"); P.display(); System.out.println(); System.out.println("Array 2:"); Q.display(); System.out.println(); System.out.println("Combined Array:"); R.display(); } } VDC: Variable Data Type Description i, x, y, z Int Runs loop a Int Stores size of array1 b Int Stores size of array2 t Int Runs loop Output: YASHASVI SINGH PAGE 50 Question 18. Design a class VowelWord to accept a sentence and calculate the frequency of words that begin with a vowel. The words in the input string are separated by a single blank space and terminated by a full stop. The description of the class is given below: [10] Class name: VowelWord Data Members/instance variables: str: to store a sentence freq: store the frequency of the words beginning with a vowel. Member functions: VowelWord(): constructor to initialize data members void readstr(): to accept a sentence void freq_vowel: counts the frequency of the words that begin with a vowel void display(): display original string and frequency of words that begin with a vowel. Specify the class VowelWord giving details of the constructor (), void readstr (), void freq_vowel () and void display (). Also, define the main () function to create an object and call the methods accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class VowelWord Step 2: Initialize the global variables in the constructor VowelWord() Step 3: Take input from user suing function readstr() Step 4: Call function freq_vowel() and count and store the frequency of word Step 5: Invoke the method display() and display the original string and frequency of words that begin With a vowel Code : import java.util.Scanner; public class VowelWord { String str; int freq; public VowelWord() { str=""; freq=0; } public void readstr() { Scanner sc=new Scanner(System.in); System.out.println("Enter a string"); str=sc.nextLine(); YASHASVI SINGH //constructor to initialize variables //function to accept input PAGE 51 } public void freq_vowel() //function to calculate frequency { char ch,ch1=' '; for(int i=0;i< str.length();i++) { ch=str.charAt(i); if(i==0) { if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') { freq++; } } else if(ch==' ') { ch1=str.charAt(i+1); if(ch1=='a'||ch1=='e'||ch1=='i'||ch1=='o'||ch1=='u'||ch1=='A'||ch1=='E'||ch1=='I'||ch1=='O'||ch1=='U') { freq++; } } } } void display() //function to print the findings { System.out.println("ORIGINAL SENTENCE: "+str); System.out.println("FREQUECY OF WORD BEGINNING WITH A VOWEL "+freq); } public static void main() //main method { VowelWord ob1=new VowelWord(); ob1.readstr(); ob1.freq_vowel(); ob1.display(); } } VDC: Variable str freq Datatype String Int ch ch1 Char Char Description It is used to take input and store the string by the user. It is used to store the frequency of the words beginning with a vowel It is used to check for blankspaces. It is used to check successive character after blankspace whether it is vowel or not. Output: YASHASVI SINGH PAGE 52 Question 19. A happy number is a number in which the eventual sum of the square of the digits of the number is equal to 1. [10] Example: 28 = (2)2 + (8)2 = 4 + 64 = 68 68 = (6)2 + (8)2 = 36 + 64 = 100 100 = (1)2 + (0)2 + (0)2 = 1 + 0 + 0 = 1 Hence, 28 is a happy number. Example: 12 = (1)2 + (2)2 = 1 + 4 = 5 Hence, 12 is not a happy number. Design a class Happy to check if a given number is a happy number. Some of the members of the class are given below: Class name: Happy Data Members/instance variables: n: stores the number Member functions Happy( ): constructor to assign 0 to n. void getnum (int nn): to assign the parameter value to the number n = nn. int sum_sq_digits (int x): returns the sum of the square of the digits of the number x, using the recursive technique void ishappy (): checks if the given number is a happy number by calling the function sum_sq_digits(int) and displays an appropriate message. Specify the class Happy giving details of the constructor (), void getnum (int), int sum_sq_digits (int) and void ishappy (). Also define a main ( s) function to create an object and call the methods to check for happy number. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Happy Step 2: Take input from user a Step 3: Intialize n by passing a to function getnum() Step 4: Call function ishappy() Step 5: Run a loop till the number is not in unitary Step 6: Call function sum_sq_digits() to get the sum of the square of the digits of the no. Step 7: Check the number if it equal to 1 or not and display the result accordingly Code : YASHASVI SINGH PAGE 53 import java.util.Scanner; public class Happy { int n; Happy() //constructor to initialize variables { n=0; } void getnum(int nn) //assigns parameter to n { n=nn; } int sum_sq_digits(int x) //function to calculate sum of square of digits { if(x==0) { return 0; } else { int rem=x%10; return (rem * rem)+sum_sq_digits(x/10); } } void ishappy() //function to check whether the number is happy number { int x=n; while(x!=1 && x!=4) { x=sum_sq_digits(x); } if(x==1) { System.out.println(n+" IS A HAPPY NUMBER"); } else { System.out.println(n+" IS NOT A HAPPY NUMBER"); } } public static void main() { Scanner sc=new Scanner(System.in); System.out.println("Enter a number"); int a=sc.nextInt(); Happy ob1=new Happy( ); ob1.getnum(a); ob1.ishappy(); } } YASHASVI SINGH PAGE 54 VDC: Variable a x rem Data type Int Int Int Description Input from user Stores updated value of the input number after operations Stores unit digit of the number Output: YASHASVI SINGH PAGE 55 Question 20. Input a sentence from the user and count the number of times, the words “an” and “and” are present in the sentence. Design a class Frequency using the description given below: [ 10] Class name: Frequency Data members/variables: text: stores the sentence countand: to store the frequency of the word “and” countan: to store the frequency of the word “an” len: to stores the length of the string Member functions/methods: Frequency(): constructor to initialize the instance variables void accept(String n): to assign n to text, where the value of the parameter n should be in lower case. void checkandfreq(): to count the frequency of “and” void checkanfreq(): to count the frequency of “an” void display(): to display the no. of “and” and “an” with appropriate messages. Specify the class Frequency giving details of the constructor(), void accepts(String), void checkandfreq(), void checkanfreq() and void display(). Also, define the main() function to create an object and call methods accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Frequency Step 2: Declare variables countand, countan, len Step 3: Take input of a sentence from user n Step 4: Call function accept() and assign n to text Step 5: Call function checkandfreq() to calculate the frequency of “and” and store it in countand Step 6: Call function checkanfreq() to calculate the frequency of “an” and store it In countan Step 7: Call function() and display the frequency of “and” and “an” in the input sentence Code : import java.util.Scanner; public class Frequency { String text; int countand,countan,len; public Frequency() //constructor to initialize the variables YASHASVI SINGH PAGE 56 { text=""; countand=0; countan=0; } public void accept(String n) { text=n; if(text.charAt(text.length()-1)!='.') { text=text+'.'; } len=text.length(); } public void checkandfreq() { int pos=0,i=0; char ch=' '; String b=""; for(i=0;i< len;i++) { ch=text.charAt(i); if(ch==' '||ch=='.') { b=text.substring(pos,i); if(b.equals("and")==true) { countand++; } pos=i+1; } } } public void checkanfreq() { int pos=0,i=0; char ch=' '; String b=""; for(i=0;i< len;i++) { ch=text.charAt(i); if(ch==' '||ch=='.') { b=text.substring(pos,i); if(b.equals("an")==true) { countan++; } pos=i+1; } } //function to take input from user //function to check frequency of “and” //function to check frequency of “an” YASHASVI SINGH PAGE 57 } public void display() //function to print the results { System.out.println("Number of and's="+countand); System.out.println("Number of an's="+countan); } public static void main() { Scanner sc=new Scanner(System.in); System.out.println("Enter a sentence in Lowercase"); String n=sc.nextLine(); Frequency ob1=new Frequency(); ob1.accept(n); ob1.checkandfreq(); ob1.checkanfreq(); ob1.display(); } } VDC: Variable text countand Datatype String Int Count an int len int ch i int Description Store the sentence It is used to store the frequency of word ‘and’ in the string. It is used to store the frequency of word ‘or’ in the string. It is used to store the length of the string. It is used to check for blank space and fullstop in the string. It is used to control the flow of the for loop. Output: YASHASVI SINGH PAGE 58 Question 21. A class DeciOct has been defined to convert a decimal number into its equivalent octal number. Some of the members of the class are given below: Class name: DeciOct Data members/instance variables: n: stores the decimal number oct: stores the octal equivalent number Member functions: DeciOct(): constructor to initialize the data members n = 0, oct = 0. void getnum(int nn): assign nn to n void deci_oct(): calculates the octal equivalent of ‘n’ and stores it in oct using the recursive technique void show(): displays the decimal number ‘n’, calls the function deci_oct() and displays its octal equivalent. (a) Specify the class DeciOct, giving details of the constructor( ), void getnum(int), void deci_oct( ) and void show(). Also define a main() function to create an object and call the functions accordingly to enable the task. [8] (b) State any two disadvantages of using recursion. [2] -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create class DeciOCt Step 2: Declare n and oct Step 3: Take input from user in decimal Step 4: Call function getnum() and pass num to assign to n as actual parameter nn Step 5: Call function show() Step 6: Print the decimal number Step 7 : Call function deci_oct() Step 8: Print the octal on for the decimal number Code : import java.util.Scanner; public class DeciOct { int n,oct,i=0; Scanner sc=new Scanner(System.in); public DeciOct() { n=0; oct=0; i=0; } public void getnum(int nn) YASHASVI SINGH //constructor to initialize variables //function to assign the parameter nn to n PAGE 59 { n=nn; } public void deci_oct() //function to convert decimal no to octal no { int c; if(n!=0) { c=n%8; n=n/8; oct=oct+c*(int)Math.pow(10,i); i=i+1; deci_oct(); } } public void show() //functioin to display the results { System.out.println("Decimal Number="+n); deci_oct(); System.out.println("Octal Equivalent="+oct); } public static void main() { Scanner sc=new Scanner(System.in); System.out.println("Enter a decimal num:"); int num=sc.nextInt(); DeciOct ob1=new DeciOct(); ob1.getnum(num); ob1.show(); } } VDC: Variable n Datatype int oct int i int c int Description It is a variable used to store store a decimal number input by the user. It a variable which will store the octal equivalent of the decimal number It is a variable which act as an exponent of 10. It stores moduls of n Output: YASHASVI SINGH PAGE 60 Question 22. You are given a sequence of N integers, which are called as pseudo arithmetic sequences [10] (sequences that are in arithmetic progression). Sequence of N integers : 2, 5, 6, 8, 9, 12 We observe that 2 + 12 = 5 + 9 = 6 + 8 = 14 The sum of.the above sequence can be calculated as 14 × 3 = 42. For sequence containing an odd number of elements the rule is to double the middle element, for example 2, 5, 7, 9, 12 = 2 + 12 = 5 + 9 = 7 + 7 = 14. 14 × 3 = 42 [middle element = 7] A class Pseudoarithmetic determines whether a given sequence is a pseudoarithmetic sequence. The details of the class are given below: Class name: Pseudoarithmetic Data members/instance variables: n: to store the size of the sequence a[]: integer array to store the sequence of numbers ans, flag: store the status sum: store the sum of the sequence of numbers r: store the sum of the two numbers Member functions: Pseudoarithmetic(): default constructor void accept(int nn): to assign nn to n and to create an integer array. Fill in the elements of the array boolean check(): return true if the sequence is a pseudo arithmetic sequence otherwise returns false Specify the class Pseudoarithmetic, giving the details of the constructor(), void accept(int) and boolean check(). Also, define a main() function to create an object and call the member functions accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Pseudoarithematic Step 2: Take input of all the instance variables. YASHASVI SINGH PAGE 61 Step 3: Initialize the instance variables in non-parameterized class constructor Step 4: Create a parameterized void accept() method to take input elements in the array by the user. Step 5: Now, Create a Boolean check() method to check the array elements whether they are in pseudoArithmetic sequence or not. Step 6: Now, create the main() method to create object of the class and then take input of the size of the array from the user and then call all the functions of the class. Code : import java.io.*; class PseudoArithmetic { int n; int a[]; boolean flag; boolean ans; int sum; int r; public PseudoArithmetic() //constructor to initialize variables { n=0; flag=true; ans=false; sum=0; r=0; } public void accept (int num)throws IOException //function to take input { n = num; a=new int[n]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter array elements: "); for(int i = 0; i<n; i++) a[i]=Integer.parseInt(br.readLine()); } public boolean check(){ //function to check for the condition int i=0; int j=n-1; r=a[i]+a[j]; int count=0; do{ int temp = a[i] + a[j]; if(temp != r) { flag = false; break; } if(i==j) sum += a[i] * 2; else sum += a[i] + a[j]; i++; j--; YASHASVI SINGH PAGE 62 count++; } while(i<=j); ans=(sum == r*count); return(flag && ans); } public static void main(String args[])throws IOException{ //main method BufferedReader br = new BufferedReader(new InputStreamReader(System. in)); System.out.println("Enter size of n = "); int num = Integer.parseInt(br.readLine()); //stores size of array PseudoArithmetic obj = new PseudoArithmetic(); //object to call other methods obj.accept (num) ; if(obj.check()) System.out.println("Pseuso arithmetic sequence." ) ; else System.out.println("Not a Pseuso arithmetic sequence." ) ; } } VDC: Variable n Data Type Int a[] Int flag ans sum boolean bolean Int r int Description This is used to take input of the size of the array from the user. This is used to store different numbers for the pseudoAritmetic sequence. This is used to store the status This is used to store the status. This is used to calculate sum of sequence of numbers. It is used to store the sum of two numbers. Output: YASHASVI SINGH PAGE 63 YASHASVI SINGH PAGE 64 Question 23. The coordinates of a point P on a two-dimensional plane can be represented by P(x, y) with x as the x-coordinate and y as the y-coordinate. The coordinates of the midpoint of two points P1(x1, y1) and P2(x2, y2) can be calculated as P(x, y) where: [10] x=(x1+x2)/2, y=(y1+y2)/2 Design a class Point with the following details: Class name: Point Data Members/instance variables: x: stores the x-coordinate y: stores the y-coordinate Member functions: Point (): constructor to initialize x = 0, y = 0 void readpoint (): accepts the coordinates x and y of a point Point midpoint (Point A, Point B): calculates and returns the midpoint of the two points A and B void displaypoint (): displays the coordinates of a point Specify the class Point giving details of the constructor (), member functions void readpoint ( ), Point midpoint (Point, Point) and void displaypoint () along with the main () function to create an object and call the functions accordingly to calculate the midpoint between any two given points. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class Point Step 2: Initialize variables in the constructor Step 3: Take input for the co-ordinate variables from user using object Point A and Point B Step 4: Call the function midpoint(Point A, Point B) using object Point C Step 5: Call the function displaypoint() using object Point C Code : import java.util.Scanner; public class Point { double x,y; Scanner sc = new Scanner(System.in); public Point() { x=0.0; y=0.0; } public void readpoint() { YASHASVI SINGH //constructor to initialize variables //method to take input PAGE 65 System.out.println("Enter value of x"); x=sc.nextDouble(); System.out.println("Enter value of y"); y=sc.nextDouble(); } public void displaypoint() { System.out.println("The value of 'x' "+ x); System.out.println("The value of 'y' "+y); } public Point midpoint(Point A,Point B) { Point C=new Point(); C.x=(A.x+B.x)/2; C.y =(A.y+B.y)/2; return C; } public static void main() { Point p=new Point(); Point q=new Point(); Point r=new Point(); p.readpoint(); q.readpoint(); r=r.midpoint(p,q); p.displaypoint(); q.displaypoint(); r.displaypoint(); } //method to print values of x and y //function to find midpoint of x and y //main method //object1 for input //object 2 for input //object 3 to find midpoint } VDC: Variable x y Data Type Double Double Description Stores x coordinates Stores y coordinate Output: YASHASVI SINGH PAGE 66 Question 24. Input a word in uppercase and check for the position of the first occurring vowel and perform the following operation. [10] (i) Words that begin with a vowel are concatenated with “Y”. For example, EUROPE becomes EUROPEY. (ii) Words that contain a vowel in-between should have the first part from the position of the vowel till the end, followed by the part of the string from beginning till the position of the vowel and is concatenated by “C”. For example, PROJECT becomes OJECTPRC. (iii) Words which do not contain a vowel are concatenated with “N”. For example, SKY becomes SKYN. Design a class Rearrange using the description of the data members and member functions given below: Class name: Rearrange Data Members/instance variables: Txt: to store a word Cxt: to store the rearranged word len: to store the length of the word Member functions: Rearrange (): constructor to initialize the instance variables void readword (): to accept the word input in UPPER CASE void convert (): converts and stores the changed word in string Cxt void display(): displays the original and the changed word Specify the class Rearrange giving the details of the constructor (), void readword ( ), void convert () and void display (). Define a main () function to create an object and call the function accordingly to enable the task. -------------------------------------------------Answer -----------------------------------------------Algorithm : Step 1: Create a class named Rearrange Step 2: Initialize the global variables in the constructor Step 3: Call function readword() to accept input from user Step 4: Call function convert() and store the converted string in cxt Step 5: Display the original word and changed word by calling function display() Code : import java.util.Scanner; public class Rearrange { String Txt,Cxt; int len; Scanner sc = new Scanner(System.in); YASHASVI SINGH PAGE 67 public Rearrange() //constructor to intiaize variables to default value { Txt=""; Cxt=""; len=0; } public void readword() //function to take input from user { System.out.println("Enter word in UPPERCASE"); Txt=sc.nextLine(); len=Txt.length(); } public void convert() //function to convert word as per given instruction { int flag=-1,i=0; char ch=' '; for(i=0;i< len;i++) { ch=Txt.charAt(i); if(ch=='A'|| ch=='E'||ch=='I'||ch=='O'|| ch=='U') { flag=i; break; } } if(flag==-1) { Cxt=Txt.concat("N"); } else if(flag==0) { Cxt=Txt.concat("Y"); } else { String d=Txt.substring(flag,len); String e=Txt.substring(0,flag); Cxt=d+e+"C"; } } public void display() //function to print original and changed string { System.out.println("Original word=" +Txt); System.out.println("Changed word="+Cxt); } YASHASVI SINGH PAGE 68 public static void main() { Rearrange ob1=new Rearrange(); ob1.readword(); ob1.convert(); ob1.display(); } //main method } VDC: Variable txt cxt len flag i Data Type String String Int Int Int Description Stores input from user Stores converted String Stores length of txt Counter variable Runs loop Output: YASHASVI SINGH PAGE 69 Question 25. Design a class Change to perform string related operations. The details of the class are given below: Class name: Change Data Members/instance variables: str: stores the word newstr: stores the changed word len: store the length of the word Member functions: Change(): default constructor void inputword( ): to accept a word char caseconvert (char ch): converts the case of the character and returns it void recchange (int): extracts characters using recursive technique and changes its case and forms a new word void display (): displays both the words (a) Specify the class Change, giving details of the Constructor ( ), member functions void inputword (), char caseconvert (char ch), void recchange (int) and void display (). Define the main () function to create an object and call the functions accordingly to enable the above change in the given word. (b) Differentiate between an infinite and a finite recursion. -------------------------------------------------Answer -----------------------------------------------(A) Algorithm : Step 1: Create a class Change Step 2: Initialize the global variables in the constructor to specified values Step 3: Take input from user by invoking function inputword() Step 4: Call the function recchange to extract and characters in String str Step 5: Pass the extracted character to caseconvert(), store the new character in the string and Return the word Step 6: Display both the words by invoking function display() Code : import java.util.Scanner; public class Change { String str,newstr; int len; Scanner sc = new Scanner(System.in); public Change() { str=""; newstr=""; len=0; YASHASVI SINGH //constructor to initialize variables to default value PAGE 70 } public void inputword() //function to take input from user { System.out.println("ENTER A Word"); str=sc.next(); len=str.length(); } public char caseconvert(char ch) //function to change thee case of character of the string { if(ch>='A' && ch<='Z') { ch=Character.toLowerCase(ch); } else if(ch>='a' &&ch<='z') { ch=Character.toUpperCase(ch); } return ch; } public void recchange(int pos) //function to extract characters from the string { char c=' '; if(pos>-1) { c=str.charAt(pos); recchange(pos-1); newstr+=caseconvert(c); } } public void display() //function to print the new and original string { System.out.println("OriginalWord:"+str); System.out.println("ChangedWord:"+newstr); } public static void main() // main method { Change ob1=new Change(); ob1.inputword(); int length=ob1.len; ob1.recchange(length-1); ob1.display(); } } VDC: Variable str newstr len ch Data Type String String Int Char YASHASVI SINGH Description Stores input from user Stores the converted string Stores the length of str Stores the character to be changed PAGE 71 Output: (B) Finite recursion has the same stopping condition on which the recursive function does not call itself. Infinite recursion has no stopping condition and hence go on infinitely. YASHASVI SINGH PAGE 72