You are on page 1of 108

Greenwood High

Computer Application
Program (1 - 25)

Grade XI (ISC)
Academic Year (2021 – 2022)

Name : Ved Ramesh


Roll No. : 21
UID : 7341584
Certificate

Name : Ved Ramesh Class : XI


Roll No. : 21

Institution: GREENWOOD HIGH SCHOOL, BANGLORE

This is certified to be the bona fide work of the student during


the academic year 2021-2022.

No. of programs certified 25 in the subject of Computer


Science

____________________
Teacher In-charge

__________________ _________________
Examiner’s Signature Principal

Date:_____________ Institution Rubber Stamp:


CONTENTS
Program Nos. Topic Page Nos.
1-14 Class and Objects 4-56
15-17 Strings 57-71
18-20 Arrays 72-89
21-25 Files 90-108
Name: Ved Ramesh UID:
ISC 2022

Program 1:
Question:
Write a program to assign values to the variables length and breadth
in the main function and print if it is a square or rectangle.
//2.6.2021

Algorithm:

Algorithm for default constructor


Step 1: Start of algorithm 
Step 2: declare variables integer length and breadth 
Step 3: defualt constructor is called to assign values to length and
breadth 
 
Algorithm for void check() 
Step 1: start 
Step 2: checking whether length is equal to breadth and printing the
message 
Step 3: end 
 
Algorithm for void main() 
Step 1: start 
Step 2: object ‘obj’ of class ‘Program1’ is created
Step 3: default constructor shape is called to assign values of length
and breadth
Step 4: method check is called through the object
Step 5: end

4
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//To assign values and print if its a sqaure or rectangle 
Class Program1 

Int length, breadth; 
Void shape()//default constructor 

   Length= 5; 
   Breadth=10; 

Void check()//To check the method 

   If(length==breadth) 
   System.out.println("It is a Square"); 
   Else 
   System.out.println("It is a rectangle"); 

Void main()//main method 

   Program1 obj= new Program1(); 
obj.shape();
obj.check();

}

5
Name: Ved Ramesh UID:
ISC 2022

Program 2:
Question:
Write a program to input values to the variables length and breadth in
the main function and print if it is a square or a rectangle.
//17.6.2021

Algorithm:

Algorithm for void assign()


Step 1: start
Step 2: variables length and breadth are initialized in the
parameterized constructor
Step 3: end

Algorithm for void check()


Step 1: start
Step 2: checks whether the inputted values of length and breadth are
equal or not.
Step 3: prints the desired message
Step 4: end

Algorithm for void main()


Step 1: start
Step 2: object ‘obj’ of class ‘Program2’ is created.
Step 3: method assign is called through object.
Step 4: method check is called through object.
Step 5: end

6
Name: Ved Ramesh UID:
ISC 2022

Source Code:
Class Program2 

Void assign(double length, double breadth) 


Void check()//To check the method 

   If(length==breadth) 
   System.out.println("It is a Square"); 
   Else 
   System.out.println("It is a rectangle"); 

Void main()//main method 

   Program2 obj= new Program2(); 
obj.assign();
obj.check();

}
}

7
Name: Ved Ramesh UID:
ISC 2022

Program 3:
Question:
Write a program to assign a value to marks and print -excellent>90
-good>80
-fair>70
-average>=60
-poor<60
//18.6.2021

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘Grading’ is created
Step 4: instance variable ‘marks’ is declared with int value.
Step 5: end

Algorithm for void input()


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
value from the user.
Step 3: end

Algorithm for void remark()


Step 1: start
Step 2: if else statement is used to compare inputted marks and print
out the required message according to the marks.
Step 3:end

Algorithm for void main()


Step 1: start
Step 2: object ‘obj’ of class ‘Grading’ is created
Step 3: method input is called through object
Step 4: method remark is called through object
Step 5: end

8
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*; 
class Grading 

    int marks; 
    void input() 
    { 
        Scanner sc=new Scanner(System.in); 
        System.out.println("Enter marks"); 
        marks=sc.nextInt(); 
    } 
  
    void remark() 
    { 
        if (marks > 90) 
            System.out.println("Excellent"); 
        else if (marks > 80) 
            System.out.println("Good"); 
        else if (marks > 70) 
            System.out.println("Fair"); 
        else if (marks >= 60) 
            System.out.println("Average"); 
        else if (marks < 60) 
            System.out.println("Poor");  
    } 
  
    void main() 
    { 
        Grading obj=new Grading(); 
        obj.input(); 
        obj.remark(); 
    } 

9
Name: Ved Ramesh UID:
ISC 2022

Program 4:
Question:
Design a class special, to check if the given number is a special
number.
-Special number: A number in which the sum of the factorials of each
digit is equal to the number itself.
//22.6.2021

Algorithm:

Algorithm for void main()


Step 1: start
Step 2: instance variables ‘num’,’number’,’lastdigit’ and sumOfFact
are initialised with int values.
Step 3: using scanner class, message is printed to read the inputted
value from the user.
Step 4: while loop is used to extract the last digit from the number,
while the number is greater than 0
Step 5: for loop is used to calculate the factorial
Step 6: sumOfFact stores the sum of factorials
Step 7: number is divide by 10 to remove the last digit
Step 8: loop repeats until the factorial of each digit of the number has
been calculated.
Step 9: sumOfFact is compared to inputted number to check whether
they are equal or not, and prints the message accordingly.
Step 10: end

10
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;   
class Special 
{   
    void main()   
    {   
        int num, number, lastdigit, sumOfFact = 0;   
        Scanner sc=new Scanner(System.in);   
        System.out.print("Enter a number: ");  //reads an integer from the
user   
        number = sc.nextInt();   
        num = number;     
        while(number>0)   
        {         
            lastdigit=number%10;    
            int fact=1;    
            for(int i=1;i<=lastdigit;i++)   
            {         
                fact=fact*i; //calculates factorial   
            }   
            sumOfFact = sumOfFact + fact;  //calculates the sum of all
factorials 
            number = number / 10;  //divides the number by 10 and
removes the last digit from the number  
        }   
        if(num==sumOfFact) //compares the sum with the given
number  
        {   
            System.out.println(num+ " is a special number.");   
        }   
        else   
        {   
            System.out.println(num+ " is not a special number.");   
        }   
    }   
}   

11
Name: Ved Ramesh UID:
ISC 2022

Program 5:
Question:
A class Numbers contains the following data members and member
functions to check for triangular numbers.

-Triangular number: A number that is formed by the addition of a


consecutive sequence of integers, starting from one.
//24.6.2021

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘Numbers’ is created
Step 4: instance variable ‘n’ is declared with int value.
Step 5: end

Algorithm for void getnum()


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
value for ‘N’ from the user
Step 3: end

Algorithm for int check(int n)


Step 1: start
Step 2: n is declared as a parameterised constructor with int value
Step 3: int sum and int i are declared as instance variables with int
value
Step 4: while loop is used to find integers and find their sum
Step 5: if statement is used to check if sum is equal to the inputted
number and return values 1 or 0 respectively
Step 6: end

Algorithm for void dispnum()


Step 1: start
Step 2: if statement is used to check retuen type and prints the
message accordingly.

12
Name: Ved Ramesh UID:
ISC 2022

Step 3: end

Algorithm for void main()


Step 1: start
Step 2: object ‘obj’ of class ‘Numbers’ is created
Step 3: method getnum() is called through object
Step 4: method check(n) is called through object
Step 5: method dispnum() is called through object
Step 6: end

13
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*; 
class Numbers 

    int n; 
    void getnum() 
    { 
        Scanner Numbers = new Scanner(System.in); 
        System.out.print("N = "); 
        n =Numbers.nextInt(); 
    } 
  
    int check(int n) 
    { 
        int sum=0; 
        int i=1; 
        while(sum < n) 
        { 
            sum +=i; 
            i++; 
        } 
        if(sum == n) 
            return 1; 
        else 
            return 0; 
    } 
  
    void dispnum() 
    { 
        if(check(n) == 1) 
            System.out.println(n + " is triangular."); 
        else 
            System.out.println(n + " is not triangular."); 
    } 
  
    void main() 
    { 

14
Name: Ved Ramesh UID:
ISC 2022

        Numbers obj =new Numbers(); 


        getnum(); 
        check(n); 
        dispnum(); 
    } 

15
Name: Ved Ramesh UID:
ISC 2022

Program 6:
Question:
Write a program to input a 3 digit number and check if it is an
Armstrong number.
-Armstrong number: Is a number where the sum of cubes of the digits
is equal to the number itself.
//25.6.2021

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘Prg6’ is created
Step 4: instance variables ‘number’ and ‘sum’ is declared with int
value.
Step 5: end

Algorithm for void inputnum()


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
value for ‘number’ from the user
Step 3: end

Algorithm for void checknumber()


Step 1: start
Step 2: variables ‘temp’, ‘digits’ and ‘last’ is declared with int value.
Step 3: ‘number’ is assigned to ‘temp’ variable
Step 4: while loop is used to extract the last digit and calculate its
cube and add it to sum while ‘number’ > 0
Step 5: end

Algorithm for void display()


Step 1: start
Step 2: if statement is used to check whether ‘number’ is equal to
‘sum’ and prints the required statement.
Step 3: end

16
Name: Ved Ramesh UID:
ISC 2022

Algorithm for void main()


Step 1: start
Step 2: object ‘obj’ of class ‘Prg6’ is created
Step 3: method inputnum() is called through object
Step 4: method checknumber() is called through object
Step 5: method display() is called through object
Step 6: end

17
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//To input a 3 digit number  and check if its an armstrong number 
import java.util.*; 
class Prg6 

    int number,sum=0; 
    void Prg6() 
    { 
        number=0; 
    } 
  
    void inputnum() 
    { 
        Scanner Armstrong= new Scanner(System.in); 
        System.out.print("Enter the number:"); 
        number=Armstrong.nextInt(); 
    } 
  
    void checknumber() 
    {    
        int temp, digits=0, last=0;    
        //assigning n into a temp variable   
        temp=number;    
        //loop execute until the condition becomes false   
        while(temp>0)     
        {    
            temp = temp/10;    
            digits++;    
        }    
        temp = number;    
        while(temp>0)    
        {    
            //determines the last digit from the number       
            last = temp % 10;    
            //calculates the power of a number up to digit times and add
the resultant to the sum variable   
            sum +=  (Math.pow(last, digits));    

18
Name: Ved Ramesh UID:
ISC 2022

            //removes the last digit    


            temp = temp/10;    
        }   
    }    
  
    void display()      
    {        
        if(number==sum)   
  
            System.out.print("It is a Armstrong ");  
        else 
            System.out.print("It is not a Armstrong "); 
    } 
  
    void main() 
    { 
        Prg6 obj=new Prg6(); 
        obj.inputnum(); 
        obj.checknumber(); 
        obj.display(); 
    } 

19
Name: Ved Ramesh UID:
ISC 2022

Program 7:
Question:
A class Telcall calculates the monthly phone bill of a consumer. The
members of the class are given below
-phno: phone number
-name: name of consumer
-no: number of calls made
-amt: bill amount
//29.6.2021

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘Telcall’ is created
Step 4: instance variable ‘Phno’ is declared with long value.
Step 5: instance variable ‘name’ is declared with String value.
Step 6: instance variable ‘no’ is declared with int value.
Step 7: instance variable ‘amt’ is declared with double value.
Step 5: end

Algorithm for Telcall(long phone, String name_entered, int calls)


Step 1: start
Step 2: temporary variables are declared in parameterized constructor
Step 3: variable ‘Phno’ is assigned to ‘phone’
Step 4: variable ‘name’ is assigned to ‘name_entered’
Step 5: variable ‘no’ is assigned to ‘calls’
Step 6: variable ‘amt’ is given value of 0.0
Step 7: end

Algorithm for void compute()


Step 1: start
Step 2: if statement is used to calculate ‘amt’ depending on the value
inputted for ‘no’ by the user
Step 3: end

20
Name: Ved Ramesh UID:
ISC 2022

Algorithm for dispdata()


Step 1: start
Step 2: ‘System.out.println’ is used to display the monthly phone bill
Step 3: end

Algorithm for void main()


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
information of the user.
Step 3: object ‘obj’ of class ‘Telcall’ is created
Step 4: method compute() is called through object
Step 5: method dispdata() is called through object
Step 6: end

21
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*; 
class Telcall 

    long Phno; 
    String name; 
    int no; 
    double amt; 
     
    Telcall(long phone, String name_entered, int calls) 
    { 
        Phno=phone; 
        name=name_entered; 
        no=calls; 
        amt=0.0; 
    } 
     
    void compute() 
    { 
        if(no<=100) 
        amt=500.0; 
        else if((no>100)&&(no<=200)) 
        amt=600.0; 
        else if((no>200)&&(no<=300)) 
        amt=600.0+((no-200)*1.20); 
        else 
        amt=600.0+(100*1.20)+((no-300)*1.50); 
    } 
     
    void dispdata() 
    { 
        System.out.println("Phone Number"+"\t"+"Name"+"\
t"+"Total Calls"+"\t"+"Amount"); 
        System.out.println(Phno+"\t"+name+"\t"+no+"\t"+amt); 
    } 
     

22
Name: Ved Ramesh UID:
ISC 2022

    void main() 


    { 
        Scanner sc=new Scanner(System.in); 
         
        System.out.println("Enter Name"); 
        String customer_name=sc.nextLine(); 
         
        System.out.println("Enter Phone Number"); 
        long phone_num=sc.nextLong(); 
         
        System.out.println("Enter number of Calls"); 
        int call_num=sc.nextInt(); 
         
        Telcall obj=new Telcall(phone_num, customer_name, call_num)

        obj.compute(); 
        obj.dispdata(); 
    } 

23
Name: Ved Ramesh UID:
ISC 2022

Program 8:
Question:
Design a class Emirp to check if a given number is Emrip or not.
-Emirp number: It is a number which is prime, both forwards and
backwards.
-Data members of the class are:
N: storing the number
rev: reverse of the number
f: stores the divisor
//30.6.2021

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘Emirp’ is created
Step 4: instance variable ‘N’, ‘rev’ and ‘f ‘ is declared with int value.
Step 5: end

Algorithm for Emirp(int nn)


Step 1: start
Step 2: temporary variable is declared in parameterized constructor
Step 3: variable ‘N’ is assigned to ‘nn’
Step 4: variable ‘rev’ is given value of 0
Step 5: variable ‘N’ is given value of 2
Step 6: end

Algorithm for int isPrime(int x)


Step 1: start
Step 2: for loop is used to check if number is prime or not, returns 1 if
number is prime.
Step 3: end

Algorithm for void isEmirp()


Step 1: start
Step 2: variable ‘digit’ is declared with int value.
Step 3: while loop is used to find reverse of inputted number

24
Name: Ved Ramesh UID:
ISC 2022

Step 4: if statement is used to check whether inputted number and its


reverse are prime and prints message accordingly
Step 5: end

Algorithm for void main()


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
number of the user.
Step 3: object ‘obj’ of class ‘Emirp’ is created
Step 4: method isEmirp() is called through object
Step 5: end

25
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;   
public class Emirp 

    int N, rev, f; 
    Emirp(int nn) 
    { 
        N=nn; 
        rev=0; 
        f=2; 
    } 
  
    int isPrime(int x) 
    { 
        for (f=2;f<x;f++)  
        { 
            if (x%f==0) 
            { 
                return 1; 
            } 
        } 
        return 1; 
    } 
  
    void isEmirp() 
    { 
        int digit=0; 
        int original=N; 
        while(original>0) 
        { 
            digit=original%10; 
            original=original/10; 
            rev=rev*10+digit; 
        } 
        if(isPrime(N)==1&&isPrime(rev)==1) 
        { 
            System.out.println("It is a Emirp number"); 

26
Name: Ved Ramesh UID:
ISC 2022

        } 
        else 
        { 
            System.out.println("It is not a Emirp number"); 
        } 
    } 
  
    void main() 
    { 
        Scanner Emirp=new Scanner(System.in); 
        System.out.println("Enter a Number"); 
         
        int nn=Emirp.nextInt(); 
        Emirp obj=new Emirp(nn); 
         
        obj.isEmirp(); 
    } 

27
Name: Ved Ramesh UID:
ISC 2022

Program 9:
Question:
A class series sum has been defined to calculate sum of the above
series. Design a class to print the series

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘SeriesSum’ is created
Step 4: instance variable ‘x’ and ‘n’ is declared with int value.
Step 5: instance variable ‘sum’ is declared with double value.
Step 6: end

Algorithm for SeriesSum()


Step 1: start
Step 2: variable ‘x’, ‘n’ and ‘sum’ is given value of 0
Step 3: end

Algorithm for int factorial(int n)


Step 1: start
Step 2: variable ‘i’ is declared with int value and is equal to 1
Step 3: for loop is used to calculate factorial
Step 4: returns factorial
Step 5: end

Algorithm for double term(int p, int q)


Step 1: start
Step 2: variable ‘calculate’ is declared with int value and is equal to
2*q-1
Step 3: variable ‘value’ is declared with double value and is used to
calculate power using Math.pow function
Step 4: returns value
Step 5: end

Algorithm for void accept()


Step 1: start

28
Name: Ved Ramesh UID:
ISC 2022

Step 2: using scanner class, message is printed to read the inputted


values of ‘n’ and ‘x’.
Step 3: end

Algorithm for displaysum()


Step 1: start
Step 2: prints message to display sum of series
Step 3: end

Algorithm for void calsum()


Step 1: start
Step 2: for loop is used to calculate sum of series
Step 3: end

Algorithm for void main()


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
number of the user.
Step 3: object ‘obj’ of class ‘SeriesSum’ is created
Step 4: method accept() is called through object
Step 5: method calsum()is called through object
Step 6: method displaysum() is called through object
Step 7: end

29
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*; 
class SeriesSum 

    int x,n; 
    double sum; 
    SeriesSum() 
    { 
        x=0; 
        n=0; 
        sum=0.0; 
    } 
  
    int factorial(int n) 
    { 
        int i=1; 
        int fact=1; 
        for(i=1;i<n;i++) 
        { 
            fact=fact*i; 
        } 
        return fact; 
    } 
  
    double term(int p, int q) 
    { 
        int calculate=2*q-1; 
        double value=Math.pow(p,calculate)/factorial(q); 
        return value; 
    } 
  
    void accept() 
    { 
        Scanner Series=new Scanner(System.in); 
        System.out.println("Enter values of n and x"); 
        n=Series.nextInt(); 
        x=Series.nextInt(); 

30
Name: Ved Ramesh UID:
ISC 2022

    } 
  
    void displaysum() 
    { 
        System.out.println("Sum of series="+sum); 
    } 
  
    void calsum() 
    { 
        int i; 
        for(i=1;i<=n;i++) 
        { 
            sum=sum+term(x,i); 
        } 
    } 
  
    void main() 
    { 
        SeriesSum obj=new SeriesSum(); 
        obj.accept(); 
        obj.calsum(); 
        obj.displaysum(); 
    } 

31
Name: Ved Ramesh UID:
ISC 2022

Program 10:
Question:
Design a class Magic to check if a given number is a magic number.
-Magic number: It is a number in which the eventual sum of digits is
equal to 1.
//5.7.2021

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘Magic’ is created
Step 4: instance variable ‘n’ and ‘remainder’ is declared with int
value.
Step 5: end

Algorithm for void getnum(int nn) 


Step 1: start
Step 2: using scanner class, message is printed to read the inputted
values of ‘n’.
Step 3: variable ‘n’ is assigned to ‘nn’
Step 4: end

Algorithm for int Sum_of_Digits(int number)


Step 1: start
Step 2: variable ‘sum’ is declared with int value and is equal to 0.
Step 3: while loop is used to calculate sum of the digits of the inputted
number
Step 4: returns sum
Step 5: end

Algorithm for ismagic()


Step 1: start
Step 2: temporary variable ‘copy’ is declared with int value
Step 3: variable ‘copy’ is assigned to ‘Sum_of_Digits’ inside a while
loop

32
Name: Ved Ramesh UID:
ISC 2022

Step 4: if statement is used to check if Sum_of_Digits is equal to 1


and prints message accordingly.
Step 5: end

Algorithm for void main()


Step 1: start
Step 2: object ‘obj’ of class ‘Magic’ is created
Step 3: method getnum(n) is called through object
Step 4: method ismagic() is called through object
Step 5: end

33
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*; 
class Magic 

    int n, remainder; 
    void getnum(int nn) 
    { 
        Scanner magic= new Scanner(System.in); 
        System.out.println("Enter a number"); 
        nn=magic.nextInt(); 
        n=nn; 
    } 
  
    int Sum_of_Digits(int number) 
    { 
        int sum=0; 
        while (number > 0)   
        {   
            remainder =number%10;    
            sum =sum+remainder;     
            number =number/10;      
        }     
        return sum; 
    } 
  
    void ismagic() 
    { 
        int copy; 
        while (n > 9)          
        { 
            copy=Sum_of_Digits(n); 
        } 
        if(Sum_of_Digits(n)==1) 
            System.out.println("Its is a magic number"); 
        else  
            System.out.println("It is not a magic number"); 
    } 

34
Name: Ved Ramesh UID:
ISC 2022

  
    void main() 
    { 
        Magic obj=new Magic(); 
        obj.getnum(n); 
        obj.ismagic(); 
    } 

35
Name: Ved Ramesh UID:
ISC 2022

Program 11:
Question:
Write a program to generate Palindromic Prime numbers.
-Palindrome number: Is a number that remains same after the digits
are reversed.
-Palindromic Prime number: They are number that are palindrome as
well as prime.

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘PalPrime’ is created
Step 4: end

Algorithm for boolean isprime(int n)


Step 1: start
Step 2: variable ‘check’ is declared with int value and is equal to 1
Step 3: for loop is used to check if inputted number is prime or not.
Step 4: if statement is used to check if ‘check’ is equal to 1
Step 5: if ‘check’ equals 1 then it returns true else it returns false
Step 6: end

Algorithm for int boolean ispal(int n)


Step 1: start
Step 2: variable ‘n1’, ‘r1’, ‘ntemp’ and ‘rev’ are declared with int
value
Step 3: variable ‘ntemp’ is assigned to ‘n’
Step 4: do while loop is used to check if inputted number is a
palindrome or not, while n1>0
Step 5: if statement is used to check if ‘rev’ is equal to ‘ntemp’ and
returns true or false value accordingly.
Step 6: end

Algorithm for void GenPalPrime(int n)


Step 1: start
Step 2: variable ‘count’is declared with int value

36
Name: Ved Ramesh UID:
ISC 2022

Step 3: if statement is used to check number of digits ‘n’ is equal too.


Step 4: if n is equal to 2, it prints 11 and increments the counter
Step 5: if n is equal to 3, it prints palindrome prime numbers from 101
to 999 and increments the counter
Step 6: if n is equal to 4, it prints palindrome prime numbers from
1001 to 9999 and increments the counter
Step 7: if n is equal to 5, it prints palindrome prime numbers from
10001 to 99999 and increments the counter
Step 8: if number of digits is greater than 5, than it prints message
accordingly
Step 9: if no palindrome prime number is found within given range,
then message is printed accordingly.
Step 10: end

Algorithm for void main()


Step 1: start
Step 2: object ‘obj’ of class ‘PalPrime’ is created
Step 3: using scanner class, message is printed to read the inputted
width of ‘n’.
Step 4: method GenPalPrime(num) is called through object
Step 5: end

37
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.Scanner; 
public class PalPrime 

    boolean isprime(int n) //method, checks whether a number is prime
or not 
    { 
        int check=1; 
        for(int i=2;i<n;i++)   
        { 
            if(n%i==0) 
            { 
                check=0; 
                break; 
            } 
        } 
        if(check==1) 
            return true; 
        else 
            return false; 
    } 
  
    boolean ispal(int n)  //method, checks whether a number
is palidrome or not 
    { 
        int n1,r1,ntemp,rev=0; 
        ntemp=n; 
        do 
        { 
            n1=n/10; 
            r1=n%10; 
            rev=rev*10+r1; 
            n=n1;      
        } 
        while(n1>0); 
        if(rev==ntemp) 
            return true; 

38
Name: Ved Ramesh UID:
ISC 2022

        else 
            return false; 
    } 
  
    void GenPalPrime(int n)  //method to generate numbers which are
prime and palindrome both 
    { 
        int count=0; 
        if(n==2) 
        { 
            System.out.println("11"); 
            count++; 
        } 
        else if(n==3) 
        { 
            int begnum=101; 
            int lnum=0; 
            boolean boolpr=false; 
            boolean boolpl=false; 
            for(int i=3;i<10;i++) 
            { 
                boolpr=isprime(i); 
                boolpl=ispal(i); 
                if(boolpr==true && boolpl==true) 
                { 
                    lnum=begnum+i*10; 
                    if(isprime(lnum)==true && ispal(lnum)==true) 
                    { 
                        System.out.println(lnum); 
                        count++; 
                    } 
                } 
            } 
        } 
  
        else if(n==4) 
        { 

39
Name: Ved Ramesh UID:
ISC 2022

            int begnum=1001; 
            int lnum=0; 
            boolean boolpr=false; 
            boolean boolpl=false; 
            for(int i=10;i<100;i++) 
            { 
                boolpr=isprime(i); 
                boolpl=ispal(i); 
                if(boolpr==true && boolpl==true) 
                { 
                    lnum=begnum+i*10; 
                    if(isprime(lnum)==true && ispal(lnum)==true) 
                    { 
                        System.out.println(lnum);                
                        count++; 
                    } 
                } 
            }         
        } 
  
        else if(n==5) 
        { 
            int begnum=10001; 
            int lnum=0; 
            boolean boolpr=false; 
            boolean boolpl=false; 
            for(int i=100;i<1000;i++) 
            { 
                boolpr=isprime(i); 
                boolpl=ispal(i); 
                if(boolpr==true && boolpl==true) 
                { 
                    lnum=begnum+i*10; 
                    if(isprime(lnum)==true && ispal(lnum)==true) 
                    { 
                        System.out.println(lnum); 
                        count++; 

40
Name: Ved Ramesh UID:
ISC 2022

                    } 
                } 
            }        
        } 
        else 
            System.out.println("Value of n should be within range 2-5"); 
        if(n>=2 && n<=5 && count==0) 
            System.out.println("No palprime number of this width"); 
    } 
  
    void main() 
    { 
        PalPrime ob=new PalPrime();  //creating object of
class PalPrime 
        Scanner in=new Scanner(System.in);  //creating object of class
Scanner 
        System.out.println("Enter the width of palprime numbers:"); 
        int num=in.nextInt(); 
        GenPalPrime(num);  //method calling 
    } 

41
Name: Ved Ramesh UID:
ISC 2022

Program 12:
Question:
Write a program to calculate Brun’s Constant below given limit.
Brun’s Constant- It is the sum of reciprocals of twin primes.

Algorithm:
Step 1: start
Step 2: ‘java util.*;’ package is imported
Step 3: class ‘BrunsConstant’ is created
Step 4: end

Algorithm for boolean IsPrime(int n)


Step 1: start
Step 2: variable ‘check’ is declared with int value and is equal to 1
Step 3: for loop is used to check if inputted number is prime or not.
Step 4: if statement is used to check if ‘check’ is equal to 1
Step 5: if ‘check’ equals 1 then it returns true else it returns false
Step 6: end

Algorithm for int void twinPrime(int lim)


Step 1: start
Step 2: for loop with nested if is used to find all twin prime numbers
under inputted limit.
Step 3: List of twin primes are printed thought System.out.println().
Step 4: end

Algorithm for double BrunConstant(int lim)


Step 1: start
Step 2: variable ‘Brun’ is declared with double value and is equal to
0.
Step 3: for loop is used to calculate Brun;s Constant and returns
‘Brun’ below the given limit.
Step 4: end

Algorithm for void main()


Step 1: start

42
Name: Ved Ramesh UID:
ISC 2022

Step 2: using scanner class, message is printed to read the inputted


limit by the user.
Step 3: object ‘obj’ of class ‘BrunsConstant’ is created
Step 4: method obj.twinPrime(limit) is called through object
Step 5: method obj.BrunConstant(limit) is called through object
Step 6: end

43
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
class BrunsConstant
{
boolean IsPrime(int n)
{
int check=1;
for(int i=2;i<n;i++)
{
if(n%i==0)
{
check=0;
break;
}
}
if(check==1)
return true;
else
return false;
}

void twinPrime(int lim)


{
for (int i = 2; i < lim; i++)
{
if (IsPrime(i) && IsPrime(i + 2))
{
System.out.println("("+i+","+(i+2)+")");
}
}
}
double BrunConstant(int lim)
{
double Brun = 0.0;
for (int i = 2; i < lim; i++)
{
if (IsPrime(i) && IsPrime(i + 2))

44
Name: Ved Ramesh UID:
ISC 2022

{
Brun = Brun +(1.0/i)+(1.0/(i+2));
}
}
return Brun;
}
void main()
{
Scanner Brun= new Scanner(System.in);
System.out.println("Give limit for Bruns Constant");
int limit=Brun.nextInt();
BrunsConstant obj= new BrunsConstant();
obj.twinPrime(limit);
System.out.println("Brun's constant for given
limit:"+obj.BrunConstant(limit));
}
}

45
Name: Ved Ramesh UID:
ISC 2022

Program 13:
Question:
Write a program to generate six-digit Armstrong like numbers.
Armstrong or Narcissistic Number: Number whose individual digits
cube-sum is equal to the number itself.
153, 407 
Armstrong Like Numbers. An armstrong number is a 3-digit number
that is equal to the sum of cubes of all its digits. There are numbers
that are Armstrong like, e.g. numbers are equal to the sum of the
cubes of its 3rd parts 
i.e., 6-digit number  
165033 = 16^3 + 50^3 + 33^3 
a 9-digit number  
166500330 = 166^3 + 500^3 + 333^3 

Class Details: 
Name: Numbers 
Instance Variables: 
number: long type 
Member Functions: 
boolean IsArmstrong(): checks whether the number is Armstrong or
not 
boolean IsArmstronglike(): checks whether the number is Armstrong
like or not 
void genArmstrongNos(): generates Armstrong Numbers 
void genArmstrongLikeNos(): generates 6 digit armstrong like
numbers 
A constructor that receives long values as parameter and initializes the
number. 
Write main method to execute the functions of the class.

46
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Constructor:
Step 1: Start 
Step 2: initialize value of instance variable to 0 
Step 3: End  
 
boolean IsArmstrong (long): 
Step 1: Start 
Step 2: Check if parameter is an armstrong number 
Step 3: End 
 
boolean IsArmstronglike (long): 
Step 1: Start 
Step 2: Divides 6-digit number into 3 parts 
Step 3: Cubes 3 parts of the number 
Step 4: Adds cubes of the part 
Step 5: Checks if number is Armstrong Like 
Step 6: End 
 
void GenArmstrongNos (): 
Step 1: Start 
Step 2: Generates armstrong numbers by invoking function
IsArmstrong(long) 
Step 3: Prints armstrong numbers 
Step 4: End 
 
void GenArmstrongLikeNos (): 
Step 1: Start 
Step 2: Generates armstrong like numbers by invoking function
IsArmstronglike(long) 
Step 3: Prints armstrong like numbers 
Step 4: End 
 
void main(): 
Step 1: Start 
Step 2: Declares object to invoke functions 
Step 3: End 

47
Name: Ved Ramesh UID:
ISC 2022

Source Code:
public class ArmstrongNumbers 

    long number ; //number to check for armstrong, and armstrong like
numbers 
    ArmstrongNumbers () //constructor to initialize number 
    { 
        number = 0; 
    } 
    public boolean IsArmstrong (long n)  
    //check if 3-d number is armstrong number 
    { 
        long digit = 0, sum = 0, original = n;  
        //digits of parameter, sum of cube of digits 
        while (n > 0) 
        { 
            digit = n % 10; 
            sum += (long) Math.pow (digit, 3); 
            n /= 10; 
        } 
        if (original == sum) 
            return true; 
        else 
            return false; 
    } 
    public boolean IsArmstronglike (long n)  
    //check if 6-d number is armstrong like number 
    { 
        long original = n; 
        long part1 = n/10000; //first 2 numbers in 6d number 
        long part2 = (n%10000)/100; //middle 2 numbers in 6d number 
        long part3 = n%100; //last 2 numbers in 6d number 
        long cbp1 = (long) Math.pow (part1, 3); //cube of first 2
numbers 
        long cbp2 = (long) Math.pow (part2, 3); //cube of middle 2
numbers 
        long cbp3 = (long) Math.pow (part3, 3); //cube of last 2 numbers 

48
Name: Ved Ramesh UID:
ISC 2022

        long sum = cbp1 + cbp2 + cbp3; //sum of the cubes 


        if (original == sum) 
            return true; 
        else 
            return false; 
    } 
    public void genArmstrongNos () //checks for armstrong numbers 
    { 
        System.out.println ("Armstrong Numbers"); 
        number = 100; 
        boolean Armstrong = false; 
        while (number < 1000) 
        { 
            Armstrong = IsArmstrong (number); 
            if (Armstrong == true) 
                System.out.println (number); 
            number += 1; 
        } 
    } 
    public void genArmstrongLikeNos () //checks for armstrong like
numbers 
    { 
        System.out.println ("Armstrong Like Numbers"); 
        number = 100000; 
        boolean ArmstrongLike = false; 
        while (number < 1000000) 
        { 
            ArmstrongLike = IsArmstronglike (number); 
            if (ArmstrongLike == true) 
                System.out.println (number); 
            number += 1; 
        } 
    } 
    public static void main() 
    { 
        ArmstrongNumbers obj = new ArmstrongNumbers (); 
        //obj to invoke functions and constructor 

49
Name: Ved Ramesh UID:
ISC 2022

        obj.genArmstrongNos(); 
        obj.genArmstrongLikeNos(); 
    } 

50
Name: Ved Ramesh UID:
ISC 2022

Program 14:
Question:
Design a class to represent a bank Account. Include the following
members:

Date Members:
Name of the depositor
Type of account
Account number
Balance Amount in the Account
Methods:
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the name and balance
Do write proper construction functions

51
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Step 1: start.
Step 2: ‘java util.*;’ package is imported.
Step 3: class ‘BankAccount’ is created.
Step 4: variable ‘name’ is declared with string value.
Step 5: variable ‘id’ is declared with long value.
Step 6: variable ‘type’ and ‘bal’ is declared with int value.
Step 7: end.

Algorithm for void Bankaccount()


Step 1: start.
Step 2: variable ‘name’ is given a value “ ”.
Step 3: variable ‘id’, ‘type’, ‘bal’ are given a value of 0.
Step 4: end.

Algorithm for void assignValues()


Step 1: start.
Step 2: Scanner ‘Details’ is created to read the inputted details.
Step 3:.nextLine() is used to input the details such as name, id, type
and balance.
Step 4: end.

Algorithm for int depositMoney()


Step 1: start.
Step 2: Scanner ‘Deposit’ is used to read and input money deposited.
Step 3: end.

Algorithm for int withdrawMoney()


Step 1: start.
Step 2: Scanner ‘Withdraw’ is used to read and input money
withdrawn.
Step 3: If amount to withdraw is more than balance, required message
is printed.
Step 4: end.

Algorithm for void displayInfo()


Step 1: start.

52
Name: Ved Ramesh UID:
ISC 2022

Step 2: ‘System.out.println’ is used to print the name and balance.


Step 3: end.

Algorithm for void main()


Step 1: start. 
Step 2: Declares object to invoke functions using switch case.
Step 3: end.

53
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
class BankAccount

{
public String name;
public long id;
public int type, bal;

void Bankaccount()
{
name = "";
id = 0;
type = 0;
bal = 0;
}

void assignValues()

{
Scanner Details = new Scanner(System.in);
System.out.println("Enter name");
name = Details.nextLine();
System.out.println("Enter acount number");
id = Integer.parseInt(Details.nextLine());
System.out.println("Enter 1 for Recurring Deposit type
account");
System.out.println("Enter 2 for Fixed Deposit type account");
type = Integer.parseInt(Details.nextLine());
System.out.println("Enter initial balance");
bal = Integer.parseInt(Details.nextLine());
}

int depositMoney()

{
Scanner Deposit = new Scanner(System.in);

54
Name: Ved Ramesh UID:
ISC 2022

System.out.println("Enter amount you wanna deposit");


int dep = Integer.parseInt(Deposit.nextLine());
bal += dep;
return bal;
}

int withdrawMoney()

{
Scanner Withdraw = new Scanner(System.in);
System.out.println("Enter amount you wanna withdraw");
int wd = Integer.parseInt(Withdraw.nextLine());
if(wd < bal) System.out.println("Sorry, you don't have that much
amount in your account");

else bal = bal-wd;


return bal;
}

void displayInfo()

{
System.out.println("Name: " + name);
System.out.println("Balance: " + bal);
}

void main()

{
BankAccount obj= new BankAccount();
obj.Bankaccount();
obj.assignValues();
System.out.println("Enter 1 for depositing an amount");
System.out.println("Enter 2 for withdrawing an amount");
System.out.println("Enter 3 to display name and balance");
Scanner switchcase = new Scanner(System.in);
int c = switchcase.nextInt();

55
Name: Ved Ramesh UID:
ISC 2022

switch(c)
{
case 1: bal = depositMoney();
break;
case 2: bal = withdrawMoney();
break;
case 3: displayInfo();
break;
default: System.out.println("Invalid choice");
}
if(c==1 || c==2) System.out.println("Balance: " + bal);
}
}

56
Name: Ved Ramesh UID:
ISC 2022

Program 15:
Question:
A class Mystring has been defined for the following methods /
functions:
Class name : Mystring
Data Members / instance variables:
str[]: to store a string
len : length of the given string from the input
Member functions/methods:
Mystring() : constructor
void readstring(): reads the given string form input
int code(int index): returns ASCII code for the character at the
position index.
void word(): displays longest word in the string

Specify the class Mystring giving details of the constructor and the
void readstring(), int code(int index). void word(), with the main
functions.

57
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Step 1: start.
Step 2: ‘java util.*;’ package is imported.
Step 3: class ‘Mystring’ is created.
Step 4: variable ‘str’ is declared with string value.
Step 5: variable ‘len’ is declared with integer value.
Step 6: end.

Algorithm for Mystring()


Step 1: start.
Step 2: variable ‘str’ is given a value “ ”.
Step 3: variable ‘len’ is given a value of 0.
Step 4: end.

Algorithm for void readString()


Step 1: start.
Step 2: Scanner ‘sc’ is created to read the inputted details.
Step 3: nextLine() is used to input the details.
Step 4: end.

Algorithm for int code(int index)


Step 1: start.
Step 2: variable int ascii is given a value of str.charAt(index).
Step 3: if statement is used to either return ‘invalid index’ if index is
greater than or equal to len else it would return ascii.
Step 4: end.

Algorithm for void word()


Step 1: start.
Step 2: variables len, check and longest are initialized.
Step 3: for loop is used to find the longest word.
Step 4: if statement is used to check if it’s the longest string.
Step 5: system.out.println is used to print the longest string.
Step 6: end.

Algorithm for void main()


Step 1: start. 

58
Name: Ved Ramesh UID:
ISC 2022

Step 2: Declares object to invoke functions.


Step 3: end.

59
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
class Mystring
{
String str;
int len;
Mystring()
{
str=" ";
len=0;
}

void readString()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter sentence");
str = sc.nextLine();
str= str+" ";
}

int code(int index)


{
int ascii =str.charAt(index);
if(index >= len)
{
System.out.println("Invalid index");
return -1;
}
else
return ascii;
}

void word()
{
len = str.length();//initialising variable
String check="";//initialising variable
String longest=" ";//initialising variable

60
Name: Ved Ramesh UID:
ISC 2022

for(int lv=0;lv<len;lv++)//for loop to find the longest word


{
if(str.charAt(lv)==' ')//if statement
{
if(check.length()<=longest.length())//nested if statement
{
check = longest;
}
longest =" ";//resetting the long variable
}
else
{
longest=longest + str.charAt(lv);
}
}
System.out.println("longest string "+check);//Print statement
}

void main()
{
Scanner sc = new Scanner(System.in);
Mystring obj = new Mystring();//creating the object obj

obj.readString();//caling method
System.out.println("enter the index number");//Print statement
int index =sc.nextInt();//initialising variable
System.out.println("ascii code is " +obj.code(index));//Printing
the called method
obj.word();//calling method
}

61
Name: Ved Ramesh UID:
ISC 2022

Program 16:
Question:
Design a class Stringfun to perform various operations on strings
without using in built function except for finding the length of the
string. Some of the member functions/ data members are given below:
Class name: Stringfun
Data members/instance variables:
str : to store the string
Member functions/methods:
void input(): to accept the string
void words(): to find and display the number of words, number of
vowels, and number of uppercase characters within the string.
void frequency(): to display frequency of each character within the
string.
Specify the class Stringfun giving the details of the functions void
input(), void words(), and void frequency () with the main function.

62
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Stringfun()
Step 1: Start.
Step 2: Initializes str = “”.
Step 3: End.

void input()
Step 1: Start.
Step 2: Accepts input sentence from user.
Step 3: End.

void words()
Step 1: Start.
Step 2: for loop is used from 0 to length of string. Each character is
extracted. If character is a vowel then vowel counter gets updated,
If character is a space then word counter gets updated, If character is
in uppercase then uppercase counter gets updated.
Step 3: Displays number of words, vowels and uppercase characters
in string.
Step 4: End.

void frequency()
Step 1: Start.
Step 2: Converts string into lowercase.
Step 3: for loop is taken from 0 to less than length of string. Each
character is extracted and is compared to other character in the string,
if its same then counter gets updated else it forms the new string
which then becomes the string of reference for the loop.
Step 4: Displays frequency of each character in the sentence.
Step 5: End.

void main()
Step 1: Start.
Step 2: Creates object sf.
Step 3: Object sf is used to call functions input(), words(),
frequency().
Step 4: End.

63
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
public class Stringfun
{
String str; //stores input string
public Stringfun() //constructor to initialize instance variable
{
str = "";
}
public void input() //accepts sentence from user
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter String:");
str = sc.nextLine(); //input sentence
}
public void words() //finds and displays number of words, vowels
and uppercase characters in sentence
{
str = str+" ";
int words = 0; //stores number of words
int vowels = 0; //stores number of vowels
int uppercase = 0; //stores number of uppercase letters
int strlen = str.length(); //stores length of string
for(int index=0;index<strlen;index++)
{
char ch = str.charAt(index);
if(ch==' ')
{
words++;
}
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||
ch=='I'||ch=='O'||ch=='U')
{
vowels++;
}
if((int)ch<=90&&(int)ch>=65)
{

64
Name: Ved Ramesh UID:
ISC 2022

uppercase++;
}
}
System.out.println("Number of words = "+words);
System.out.println("Number of vowels = "+vowels);
System.out.println("Number of uppercase characters =
"+uppercase);
}
public void frequency() //finds and displays frequency of each
character in the string
{
str=str.toLowerCase(); //converts string to lower case
char ch,ch2;
int count=0; //frequency of each character
String res="";
for(int index=0;index<str.length();)
{
ch=str.charAt(index);
for(int index1=0;index1<str.length();index1++)
{
ch2=str.charAt(index1);
if(ch==ch2)
count++;
else
res=res+ch2;
}
System.out.println("Frequency of " +ch+ " : " +count);
count=0;
str=res;
res="";
}
}
public static void main()
{
Stringfun sf = new Stringfun(); //object to call functions
sf.input();
sf.words();

65
Name: Ved Ramesh UID:
ISC 2022

sf.frequency();
}
}

Program 17:
66
Name: Ved Ramesh UID:
ISC 2022

Question:
A class Stringop is designed to handle string related operations. Some
members of the class are given below:

Data member:
txt : to store the given string of maximum length 100.
Member functions:
void readstring(): to accept the string.
char caseconvert(int,int): to convert the letter to other case.
void circularcode(): to decode the string by replacing each letter by
converting it to the opposite case and then by the next character in a
circular way. Hence “AbZ” will be decode a “bCa”.

Specify the class by giving the details of all the functions including
main().

Algorithm:

67
Name: Ved Ramesh UID:
ISC 2022

Stringop()
Step 1: Start.
Step 2: Initializes txt = “”.
Step 3: End.

void readstring()
Step 1: Start.
Step 2: Accepts input string from user.
Step 3: End.

char caseconvert(int,int)
Step 1: Start.
Step 2: The first parameter is converted to its character.
Step 3: If the character is z or Z character is converted to a or A by
adding second parameter (32/-32) minus 26 to the character’s ascii
value, else it simply adds second parameter (32/-32) to the characters
ascii value.
Step 4: Returns character after it has been converted to the other case
of its next character in a circular way.
Step 5: End.

void circularcode()
Step 1: Start.
Step 2: Initializes string str to store output string.
Step 3: for loop is taken from 0 to less than length of string txt. Each
character is extracted and is checked whether it is in upper or lower
case. If its in upper case, caseconvert((int)ch,32) is called else
caseconvert((int)-32) is called.
Step 4: After conversion character is added to str.
Step 5: Displays output string str after it has been decoded in a
circular way.
Step 6: End.

void main()
Step 1: Start.
Step 2: Creates object sop.

68
Name: Ved Ramesh UID:
ISC 2022

Step 3: Object sop is used to call functions readstring(),


circularcode().
Step 4: End.

69
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
public class Stringop
{
String txt; //stores input string
public Stringop() //constructor to initialize instance variable
{
txt = "";
}
public void readstring() //accpets input string from user
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter String (maximum length 100)");
txt = sc.nextLine(); //input string
}
public char caseconvert(int letter,int x)
{
char ch = (char)(letter+1); //converts character to opposite case
of next character in a circular way
if(letter==90||letter==122) //if its z or Z then it becomes a or A
ch = (char)((int)ch+(x-26));
else
ch = (char)(ch+x);
return ch; //returns opposite case of next character
}
public void circularcode() //extracts characters from string to
convert its next character to opposite case in a circular way
{
String str = "";
for(int index=0;index<txt.length();index++) //extracts each
character from string
{
char ch = txt.charAt(index);
if(ch>=65&&ch<=90)
ch = caseconvert((int)ch,32);
else
ch = caseconvert((int)ch,-32);

70
Name: Ved Ramesh UID:
ISC 2022

str = str+ch;
}
System.out.println("Decoded string: "+str); //displays decoded
string
}
public static void main()
{
Stringop sop = new Stringop(); //object to call functions
sop.readstring();
sop.circularcode();
}
}

71
Name: Ved Ramesh UID:
ISC 2022

Program 18:
Question:
A class Rearrange has been defined to insert an element and to delete
an element from an array. Some of the members of the class are given
below.
Class name: Rearrange
Data members/instance variables:
A[]: integer array type array
N: size of array
pos1: position of insertion(integer)
pos2: position of deletion(integer)
item: item to be inserted(integer)
Member functions/methods:
void enter(): to enter size, array elements and to display the entered
elements.
void insert(): to accept element(item) to be inserted position of
insertion and insert the element(item) at the position of insertion.
void disp1(): to display array after item is inserted.
void disp2(): to display array after item is deleted.
void remov(): to accept the position of deletion and delete element
item at the position of deletion.

72
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Rearrange()
Step 1: Start.
Step 2: Initializes N=0, pos1=0, pos2=0 and item=0.
Step 3: End.

void enter()
Step 1: Start.
Step 2: Accepts value for size of array.
Step 3: for loop is used from 0 to less than N-1 to accept values into
array.
Step 4: Array is displayed.
Step 5: End.

void insert()
Step 1: Start.
Step 2: Accepts element(item) and position to be inserted(pos1).
Step 3: for loop from 0 to less than N is taken, if index of element
matches pos1 Item is inserted into the array, if index is greater than
pos1 then elements are shifted to its next adjacent index.
Step 4: End.

void disp1()
Step 1: Start.
Step 2: Displays array after item has been inserted, using for loop.
Step 3: End.

void remov()
Step 1: Start.
Step 2: Accept position of deletion(pos2).
Step 3: for loop is taken from 0 to less than N, if pos2 is not equal to
index array elements get added to new array, else it is ignored or
deleted.
Step 4: End.

void disp2()
Step 1: Start.

73
Name: Ved Ramesh UID:
ISC 2022

Step 2: Displays array after element at pos2 has been deleted, using
for loop.
Step 3: End.

void main()
Step 1: Start.
Step 2: Creates object re.
Step 3: Object re is used to call function enter(), insert(), disp1(),
remov(), disp2().
Step 4: End.

74
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
public class Rearrange
{
int A[]; //stores input integer array
int N; //stores length of array
int pos1; //stores input position to insert element
int pos2; //stores input position to delete element
int item; //stores input element to insert
public Rearrange() //initializes instance variables
{
N=0;
pos1=0;
pos2=0;
item=0;
}
public void enter() //accepts values for size and elements into array
and displays it
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
N = sc.nextInt();
A = new int[N];
System.out.println("Enter "+(N-1)+" elements into the array");
for(int index=0;index<N-1;index++)
{
A[index] = sc.nextInt();
}
System.out.println("Array elements:");
for(int index=0;index<N-1;index++)
{
System.out.println(A[index]);
}
}
public void insert() //insert input element into array
{
Scanner sc = new Scanner(System.in);

75
Name: Ved Ramesh UID:
ISC 2022

System.out.println("Enter element to be inserted");


item = sc.nextInt();
System.out.println("Enter position to insert element");
pos1 = sc.nextInt();
pos1--;
int temp=0,temp2; //temporarily store array elements
for(int index=0;index<N;index++)
{
if(index==pos1) //if position matches index of loop, element is
inserted
{
temp=A[index];
A[pos1]=item;
}
if(pos1<index) //rest of the elements get stored in its next
index
{
temp2=A[index];
A[index]=temp;
temp=temp2;
}
}
}
public void disp1() //displays array after element has been inserted
{
System.out.println("Array after item has been inserted:");
for(int index=0;index<N;index++)
{
System.out.println(A[index]);
}
}
public void remov() //deletes input position of element from array
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter position to delete element");
pos2 = sc.nextInt();
pos2--;

76
Name: Ved Ramesh UID:
ISC 2022

int count=0;
for(int index=0;index<N;index++)
{
if(pos2!=index) //if index is not position of deletion, it gets
added to array
{
A[count]=A[index];
count++;
}
}
}
public void disp2() //displays array after element has been deleted
{
System.out.println("Array after item has been deleted:");
for(int index=0;index<N-1;index++)
{
System.out.println(A[index]);
}
}
public static void main()
{
Rearrange re = new Rearrange(); //object to call functions
re.enter();
re.insert();
re.disp1();
re.remov();
re.disp2();
}

77
Name: Ved Ramesh UID:
ISC 2022

Program 19:
Question:
A class Sort contains an array of 50 integers. Some of the member
functions/data
Members are given below:
Class name: Sort
Instance variables:
arr[]: integers.
item: item to be searched.
Member functions:
void inpdata(): to input 50 integers (no duplicate numbers are to be
entered)
void bubsort(): to sort the array in ascending order using the bubble
sort technique and to display the sorted list.
void binsearch(): to input item and search for it using binary search
technique; if found to print the item searched and its position in the
sorted list otherwise to print an appropriate message.
Specify the class Sort giving the details of the functions and main
function.

78
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Sort()
Step 1: Start.
Step 2: Initializes item=0.
Step 3: End.

void inpdata()
Step 1: Start.
Step 2: Accepts 50 integer values into array using for loop.
Step 3: End.

void bubsort()
Step 1: Start.
Step 2: Outer loop is from 0 to less than 50, inner loop is from 0 to
less than 50-outer loop-1.
Step 3: if element in index+1 is less then index then it gets swapped.
This way every element is compared with its adjacent element,
swapped if needed, and arranged in ascending order. This is Bubble
sort technique.
Step 4: Displays array in ascending order.
Step 5: End.

void binsearch()
Step 1: Start.
Step 2: Initializes int flag=0, lower=0, upper=49, mid=0.
Step 3: while loop is taken with condition statement lower<=upper.
mid is calculated. If the item is greater than array element at position
mid then lower becomes mid+1 else if its less then element at mid
then upper becomes mid-1 else flag gets updated indicting that
element is found. If element is not found, appropriate message is
displayed. This is Binary search where the array gets smaller for
easier comparison.
Step 4: End.

void main()
Step 1: Start.
Step 2: Creates object s.

79
Name: Ved Ramesh UID:
ISC 2022

Step 3: Object s is used to call function inpdata, bubsort(), and


binsearch().
Step 4: End.

80
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.util.*;
public class Sort
{
int arr[]; //stores integer array
int item; //stores input search element
public Sort() //initializes instance variable
{
item = 0;
}
public void inpdata() //accepts 50 integers into array
{
Scanner sc = new Scanner(System.in);
arr = new int[50];
System.out.println("Enter 50 integers into array (no duplicate
numbers to be entered)");
for(int index=0;index<50;index++) //inputs 50 elements into
array
{
arr[index] = sc.nextInt();
}
}
public void bubsort() //sorts array in ascending order using bubble
sort
{
int temp; //temporarily stores element of array
for(int index=0;index<50;index++)
{
for(int index1=0;index1<50-index-1;index1++)
{
if(arr[index1+1]<arr[index1])
{
temp=arr[index1];
arr[index1]=arr[index1+1];
arr[index1+1]=temp;
}
}

81
Name: Ved Ramesh UID:
ISC 2022

}
System.out.println("Array in ascending order:");
for(int index=0;index<50;index++)
{
System.out.println(arr[index]);
}
}
public void binsearch() //searches for input element using binary
search
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter element to be searched");
item = sc.nextInt();
int flag = 0; //checks if element is found
int lower = 0;
int upper = 50-1;
int mid = 0;
while(lower<=upper)
{
mid = (lower+upper)/2;
if(item>arr[mid])
lower = mid+1;
else if(item<arr[mid])
upper = mid-1;
else
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("Element is present at position "+(mid+1));
else
System.out.println("Element not present");
}
public static void main()
{

82
Name: Ved Ramesh UID:
ISC 2022

Sort s = new Sort(); //object to call functions


s.inpdata();
s.bubsort();
s.binsearch();
}
}

83
Name: Ved Ramesh UID:
ISC 2022

Program 20:
Question:
A transpose of an array is obtained by interchanging the elements of
the rows and columns. A class TransArray contains a two-
dimensional integer array of order (mxn).
The maximum value for both ‘m’ and ‘n’ is 20. Design a class
TransArray to find the transpose of a given matrix. The details of the
members of the class are given below:
Class name: TransArray
Data members:
arr[][]: stores the matrix elements
m: integer to store the number of rows
n: integer to store the number of columns
Member functions:
TransArray(): default constructor.
TransArray(int mm,int nn): to initialize the size of the matrix m=mm,
n=nn
void fillArray(): to enter the elements of the matrix
void transpose(TransArray A): to find the transpose of a given matrix
void disparray(): displays the array in a matrix form
Specify the class TransArray giving the details of the constructors and
other functions. Write the main function to execute program.

84
Name: Ved Ramesh UID:
ISC 2022

Algorithm:
Step 1: start
Step 2: ‘java.io.*;’ package is imported
Step 3: class ‘Transarray’ is created
Step 4: a double dimensional array named arr is declared.
Step 5: variable ‘m’ and ‘n’ are declared with int value.
Step 6: data input stream is used to take the values from the user
Step 7: end

Algorithm for Transarray()


Step 1: start
Step 2: outer for loop is used to give the maximum number of rows.
Step 3: inner for loop is used to give the maximum number of
columns.
Step 4: arr[i][j] is given a value of 0.
Step 5: end

Algorithm for Transarray(int mm,int nn)


Step 1: start
Step 2: variable m is assigned to mm.
Step 3: variable n is assigned to nn.
Step 4: end

Algorithm for void fillarray()


Step 1: start
Step 2: outer for loop is used to calculate row number
Step 3: inner for loop is used to calculate column number.
Step 3: message to enter each element of the matrix.
Step 4: arr[i][j]=Integer.parseInt(d.readLine()) is used to taken in each
variable of the matrix .
Step 5: end

Algorithm for void transpose(Transarray A)


Step 1: start
Step 2: a double dimensional array named arr1[][] is declared.
Step 3: outer for loop and inner for loop is used to transpose the array.
Step 4: end

85
Name: Ved Ramesh UID:
ISC 2022

Algorithm for void disparray()


Step 1: start
Step 2: outer and inner for loops used to display each element of the
transposed array.
Step 3: end

Algorithm for void main()


Step 1: start
Step 2: message printed to enter number of rows.
Step 3: mm=Integer.parseInt(d.readLine()) is used to take the input of
the number of rows.
Step 4: message printed to enter number of columns.
Step 5: nn=Integer.parseInt(d.readLine()) is used to take the input of
the number of rows.
Step 6: if statement is used to check the size of the array and if the
size exceeds 20 then required message is printed.
Step 7: end.

86
Name: Ved Ramesh UID:
ISC 2022

Source Code:
import java.io.*;
public class Transarray
{
int arr[][]=new int[20][20];
int m;
int n;
DataInputStream d=new DataInputStream(System.in);
public Transarray()
{
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++)
{
arr[i][j]=0;
}
}
}

public Transarray(int mm,int nn)


{
m=mm;
n=nn;
}

void fillarray()throws IOException


{ for(int i=0;i<m;i++)
{ for(int j=0;j<n;j++)
{
System.out.println("enter "+i+"*"+j+" th element");
arr[i][j]=Integer.parseInt(d.readLine());
}
}
}

void transpose(Transarray A)
{

87
Name: Ved Ramesh UID:
ISC 2022

int arr1[][]=new int[20][20];


for(int i=0;i<20;i++)
{ for(int j=0;j<20;j++)
{
arr1[i][j]=A.arr[j][i];
}
}
System.out.println("transpose");
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(arr1[i][j]+"\t");
} System.out.println();
}
}

void disparray()
{
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 void main() throws IOException


{
int mm=0;
int nn=0;
System.out.println("enter no of rows");
mm=Integer.parseInt(d.readLine());
System.out.println("enter no of columns");
nn=Integer.parseInt(d.readLine());

88
Name: Ved Ramesh UID:
ISC 2022

if(mm<20&&nn<20)
{ Transarray o1=new Transarray(mm,nn);
o1.fillarray();
System.out.println("original");
o1.disparray();
o1.transpose(o1);
}
else
{
System.out.println("no of rows or columns cannot exceed
20");
}
}
}

89
Name: Ved Ramesh UID:
ISC 2022

Program 21:
Question:
Write a program to create a text file after accepting information from
the user. Write a program to read the content of the previously created
file.

Algorithm:
class ProductFileWrite

void main()
Step 1: Start.
Step 2: Creates FileWriter object fout to create file “Product.txt”, and
write onto the fout.
Step 3: Creates BufferedWriter object bout to temporarily store data
from file.
Step 4: Creates PrintWriter object pout to write records into the file.
Step 5: Creates InpuStreamReader object isr to input data.
Step 6: Accepts data for product name and cost and writes them onto
the file by pout.println() in try block.
Step 7: Prints exception in catch block if exception is detected.
Step 8: File closes.
Step 9: End.

class ProductFileRead

void main()
Step 1: Start.
Step 2: Creates FileReader object fin to read file “Product.txt”.
Step 3: Creates BufferedReader object bin to temporarily store data
from fin.
Step 4: While loop with a condition statement (text to read from file is
not null) is taken which reads all the data in the file by bin.readLine()
and displays it in try block.
Step 5: Prints exception in catch block if exception is detected.
Step 6: File closes.
Step 7: End.
90
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//25/08/21
import java.io.*;
public class ProductFileWrite
{
public static void main()throws IOException
{
FileWriter fout = new FileWriter("Product.txt"); //object creates
new file to write data
BufferedWriter bout = new BufferedWriter(fout); //temporarily
stores data from file to write
PrintWriter pout = new PrintWriter(bout); //object to write data
into file
InputStreamReader isr = new InputStreamReader(System.in);
//to input data
BufferedReader br = new BufferedReader(isr);
try
{
System.out.println("Enter product name");
String product = br.readLine(); //input product name
pout.println(product); //writes data onto file
System.out.println("Enter cost");
String c = br.readLine(); //input cost
int cost = Integer.parseInt(c);
pout.println(cost); //writes data onto file
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
pout.close();
bout.close();
fout.close(); //closes file
}
}

public class ProductFileRead

91
Name: Ved Ramesh UID:
ISC 2022

{
public static void main()throws IOException
{
FileReader fin = new FileReader("Product.txt"); //object to read
file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
while((text=bin.readLine())!=null) //iterates until end of file
{
System.out.println("Product name: "+text); //displays file
record
text = bin.readLine(); //reads file records
System.out.println("Cost: "+text); //displays file record
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
bin.close();
fin.close(); //closes file
}
}

92
Name: Ved Ramesh UID:
ISC 2022

Program 22:
Question:
Write a program that reads a text file and creates another file with the
contents copied from the original file.

Algorithm:
class OldFileRead

void main()
Step 1: Start.
Step 2: Creates FileReader object fin to read file “Product.txt”.
Step 3: Creates BufferedReader object bin to temporarily store data
from fin.
Step 4: While loop with a condition statement (text to read from file is
not null) is taken which reads all the data in the file by bin.readLine()
and displays it in try block.
Step 5: Prints exception in catch block if exception is detected.
Step 6: File closes.
Step 7: End.

class ProductCopyFile

void main()
Step 1: Start.
Step 2: Creates FileWriter object fout to create file “ProductCopy.txt”
to write data onto it.
Step 3: Creates BufferedWriter object bout to temporarily store data
from fout.
Step 4: Creates PrintWriter object pout to write records into the file.
Step 5: Creates FileReader object fin to read data from “Product.txt”
file.
Step 6: Creates BufferedReader object bin to temporarily store data
from “Product.txt” file.
Step 7: While loop with a condition statement (text to read from file is
not null) is taken which reads the data in the ProductCopy.txt file and

93
Name: Ved Ramesh UID:
ISC 2022

writes it onto the Product.txt file. It also displays the records in


ProductCopy file.
Step 8: Prints exception in catch block if exception is detected.
Step 9: File closes.
Step 10: End.

94
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//25/08/21
import java.io.*;
public class OldFileRead
{
public static void main()throws IOException
{
FileReader fin = new FileReader("Product.txt"); //object to read
file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
while((text=bin.readLine())!=null) //iterates until end of file
{
System.out.println("Product name: "+text); //displays file
record
text = bin.readLine(); //reads file records
System.out.println("Cost: "+text); //displays file records
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
bin.close();
fin.close(); //closes file
}
}

public class ProductCopyFile


{
public static void main()throws IOException
{
FileWriter fout = new FileWriter("ProductCopy.txt"); //object to
create new file copy to write

95
Name: Ved Ramesh UID:
ISC 2022

BufferedWriter bout = new BufferedWriter(fout); //temporarily


stores data from file to write
PrintWriter pout = new PrintWriter(bout); //object to write data
into file
FileReader fin = new FileReader("Product.txt"); //object to read
original file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
while((text = bin.readLine())!=null) //iterates until end of file
{
pout.println(text); //writes data onto new file
System.out.println(text); //displays file record
text = bin.readLine(); //reads data from original file
pout.println(text); //writes data onto new file
System.out.println(text); //displays file record
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
pout.close();
bout.close();
fout.close();
bin.close();
fin.close(); //closes file
}
}

96
Name: Ved Ramesh UID:
ISC 2022

Program 23:
Question:
Write a program that will append records to the previously created
data file.

Algorithm:
class AppendFileWrite

void main()
Step 1: Start.
Step 2: Creates FileWriter object fout to create file (“Product.txt”,
true) to append the file.
Step 3: Creates BufferedWriter object bout to temporarily store data
from fout.
Step 4: Creates PrintWriter object pout to write records into the file.
Step 5: Creates InpuStreamReader object isr to input data.
Step 6: Accepts data for product name and cost and writes them onto
the file by pout.println() as new records, in try block.
Step 7: Prints exception in catch block if exception is detected.
Step 8: File closes.
Step 9: End.

class AppendFileRead

void main()
Step 1: Start.
Step 2: Creates FileReader object fin to read file “Product.txt” after it
has been appended.
Step 3: Creates BufferedReader object bin to temporarily store data
from fin.
Step 4: While loop with a condition statement (text to read from file is
not null) is taken which reads all the data in the file by bin.readLine()
and displays it in try block.
Step 5: Prints exception in catch block if exception is detected.
Step 6: File closes.
Step 7: End.
97
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//25/08/21
import java.io.*;
public class AppendFileWrite
{
public static void main()throws IOException
{
FileWriter fout = new FileWriter("Product.txt",true); //object
creates new file to write data
BufferedWriter bout = new BufferedWriter(fout); //temporarily
stores data from file to write
PrintWriter pout = new PrintWriter(bout); //object to write data
into file
InputStreamReader isr = new InputStreamReader(System.in);
//to input data
BufferedReader br = new BufferedReader(isr);
try
{
System.out.println("Enter product name");
String product = br.readLine(); //input product name
pout.println(product); //writes data onto file
System.out.println("Enter cost");
String c = br.readLine(); //input cost
int cost = Integer.parseInt(c);
pout.println(cost); //writes data onto files
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
pout.close();
bout.close();
fout.close(); //closes file
}
}

public class AppendFileRead

98
Name: Ved Ramesh UID:
ISC 2022

{
public static void main()throws IOException
{
FileReader fin = new FileReader("Product.txt"); //object to read
file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
while((text=bin.readLine())!=null) //iterates until end of file
{
System.out.println("Product name: "+text); //displays file
record
text = bin.readLine(); //reads file records
System.out.println("Cost: "+text); //displays file record
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
bin.close();
fin.close(); //closes file
}
}

99
Name: Ved Ramesh UID:
ISC 2022

Program 24:
Question:
Write a program to insert a record after reading two records in the
previously created file. The details of the new record must be entered
by the user. Write a program to check the contents of the newly
created file.

Algorithm:
class FileInsert

void main()
Step 1: Start.
Step 2: Creates FileWriter object fout to create file “NewProduct.txt”
to write data onto it.
Step 3: Creates BufferedWriter object bout to temporarily store data
from fout.
Step 4: Creates PrintWriter object pout to write records into the file.
Step 5: Creates FileReader object fin to read data from “Product.txt”
file.
Step 6: Creates BufferedReader object bin to temporarily store data
from “Product.txt” file.
Step 7: Creates InputStramReader isr to input data.
Step 8: For loop from 1 to 3 is taken. If position 1 or 3 , then record is
read from original file and written onto new file, else if position is 2
then record is accepted as input from user and written or inserted into
the new file.
Step 9: Prints exception in catch block if exception is detected.
Step 10: File closes.
Step 11: End.

class NewFileRead

void main()
Step 1: Start.
Step 2: Creates FileReader object fin to read file “NewProduct.txt”.

100
Name: Ved Ramesh UID:
ISC 2022

Step 3: Creates BufferedReader object bin to temporarily store data


from fin.
Step 4: While loop with a condition statement (text to read from file is
not null) is taken which reads all the data in the file by bin.readLine()
and displays it in try block.
Step 5: Prints exception in catch block if exception is detected.
Step 6: File closes.
Step 7: End.

101
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//25/08/21
import java.io.*;
public class FileInsert
{
public static void main()throws IOException
{
FileWriter fout = new FileWriter("NewProduct.txt"); //object
creates new file to write data
BufferedWriter bout = new BufferedWriter(fout); //temporarily
stores data from file to write
PrintWriter pout = new PrintWriter(bout); //object to write data
into file
FileReader fin = new FileReader("Product.txt"); //object to read
file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
InputStreamReader isr = new InputStreamReader(System.in);
//to input data
BufferedReader br = new BufferedReader(isr);
String text = "";
try
{
for(int i=1;i<=3;i++) //for loop to insert record into file
{
if(i==2)
{
System.out.println("Enter product name");
String product = br.readLine(); //input product name
pout.println(product); //writes data into file
System.out.println("Enter cost");
String c = br.readLine(); //input cost
int cost = Integer.parseInt(c);
pout.println(cost); //writes data into file
}
else
{

102
Name: Ved Ramesh UID:
ISC 2022

text = bin.readLine(); //reads data from original file


pout.println(text); //writes data onto file
text = bin.readLine(); //reads data from original file
pout.println(text); //writes data onto file
}
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
pout.close();
bout.close();
fout.close();
bin.close();
fin.close(); //closes file
}
}

public class NewFileRead


{
public static void main()throws IOException
{
FileReader fin = new FileReader("NewProduct.txt"); //object to
read file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
while((text=bin.readLine())!=null) //iterates until end of file
{
System.out.println("Product name: "+text); //displays file to
read
text = bin.readLine(); //reads file records
System.out.println("Cost: "+text); //displays file record
}

103
Name: Ved Ramesh UID:
ISC 2022

}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
bin.close();
fin.close(); //closes file
}
}

104
Name: Ved Ramesh UID:
ISC 2022

Program 25:
Question:
Write a program to insert a record after reading two records in the
previously created file. The details of the new record must be entered
by the user. Write a program to check the contents of the newly
created file.

Algorithm:
class FileDeleteWrite

void main()
Step 1: Start.
Step 2: Creates FileWriter object fout to create file
“ProductDelete.txt” to write data onto it.
Step 3: Creates BufferedWriter object bout to temporarily store data
from fout.
Step 4: Creates PrintWriter object pout to write records into the file.
Step 5: Creates FileReader object fin to read data from “Product.txt”
file.
Step 6: Creates BufferedReader object bin to temporarily store data
from “NewProduct.txt” file.
Step 7: For loop from 1 to 2 is taken. It reads the first two records of
the file and writes them onto the new file. Third record is left out or
deleted.
Step 8: Prints exception in catch block if exception is detected.
Step 9: File closes.
Step 10: End.

class FileDeleteRead

void main()
Step 1: Start.
Step 2: Creates FileReader object fin to read file “ProductDelete.txt”.
Step 3: Creates BufferedReader object bin to temporarily store data
from fin.

105
Name: Ved Ramesh UID:
ISC 2022

Step 4: While loop with a condition statement (text to read from file is
not null) is taken which reads all the data in the file by bin.readLine()
and displays it in try block.
Step 5: Prints exception in catch block if exception is detected.
Step 6: File closes.
Step 7: End.

106
Name: Ved Ramesh UID:
ISC 2022

Source Code:
//25/08/21
import java.io.*;
public class FileDeleteWrite
{
public static void main()throws IOException
{
FileWriter fout = new FileWriter("ProductDelete.txt"); //object
to create new file to write data
BufferedWriter bout = new BufferedWriter(fout); //temporarily
stores data from file to write
PrintWriter pout = new PrintWriter(bout); //object to write data
into file
FileReader fin = new FileReader("NewProduct.txt"); //object to
read file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
for(int i=1;i<=2;i++) //for loop to delete third record of gilr
{
text = bin.readLine(); //reads data from original file
pout.println(text); //writes data onto new file
text = bin.readLine(); //reads data from original file
pout.println(text); //writes data onto new file
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
pout.close();
bout.close();
fout.close();
bin.close();
fin.close(); //closes file

107
Name: Ved Ramesh UID:
ISC 2022

}
}

public class FileDeleteRead


{
public static void main()throws IOException
{
FileReader fin = new FileReader("ProductDelete.txt"); //object to
read file
BufferedReader bin = new BufferedReader(fin); //temporarily
stores data from file to read
String text = "";
try
{
while((text=bin.readLine())!=null) //iterates until end of file
{
System.out.println("Product name: "+text); //displays file
record
text = bin.readLine(); //reads file record
System.out.println("Cost: "+text); //displays file record
}
}
catch(Exception e) //catches and displays exception
{
System.out.println(e);
}
bin.close();
fin.close(); //closes file
}
}

108

You might also like