0% found this document useful (0 votes)
9 views148 pages

Assignment 1

The document outlines three Java programming assignments: the first requires writing a program to print the first N numbers of the Pell series; the second involves calculating the average marks of students and identifying the student with the lowest average; and the third checks if a number is a Hamming number based on its prime factors. Each assignment includes a detailed algorithm, source code, and variable listings. The programs emphasize user input validation and appropriate output formatting.

Uploaded by

sohond331
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views148 pages

Assignment 1

The document outlines three Java programming assignments: the first requires writing a program to print the first N numbers of the Pell series; the second involves calculating the average marks of students and identifying the student with the lowest average; and the third checks if a number is a Hamming number based on its prime factors. Each assignment includes a detailed algorithm, source code, and variable listings. The programs emphasize user input validation and appropriate output formatting.

Uploaded by

sohond331
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 148

ASSIGNMENT 1

Program Description
Q1. Write a Java program to print the first N
numbers of the Pell series.
In mathematics, the Pell numbers are an infinite
sequence of integers.
The sequence of Pell numbers starts with 0 and
1, and then each Pell number is the sum of twice
the previous Pell number and the Pell number
before that.:
thus, 70 is the companion to 29, and 70 = 2 × 29
+ 12 = 58 + 12.
The first few terms of the sequence are : 0, 1, 2,
5, 12, 29, 70, 169, 408, 985, 2378, 5741, 13860,…

Algorithm for the Pell Series Program


Start

Step 1: Main Method (main)


1. Create an instance of the Pell class named ob.
2. Call the accept() method on the instance ob to gather input from the user.
3. Call the display() method on the instance ob to display the Pell series.

End Main Method

Step 2: Accept Method (accept)


1. Create a Scanner object named sc to read user input.
2. Repeat the following steps until a valid non-negative integer is entered:
 Prompt the user to enter N (the number of terms to print in the Pell
series).
 Read the integer input and store it in N.
3. If N is less than 0, display an error message indicating that the number of
terms cannot be negative and repeat the prompt.
1
End Accept Method

Step 3: Display Method (display)


1. Print a message indicating the first N terms of the Pell series.
2. Initialize three integer variables: a (set to 0), b (set to 1), and c (to store the
next term).
3. For each integer i from 1 to N:
 If i is 1, print the value of a.
 If i is 2, print the value of b.
 For i greater than 2:
 Calculate the next term c using the formula c = 2 * b + a.
 Print the value of c.
 Update a to the value of b.
 Update b to the value of c.

End Display Method

End

2
OUTPUTS

1.

2.

3
SOURCE CODE
//Program to display N terms of Pell series
import java.util.Scanner;
class Pell
{
private int N; //instance variable to store no. of terms
private void accept()//to accept no. of terms
{
Scanner sc=new Scanner(System.in);
do{
System.out.print("Enter N to print first N numbers
of the PELL series: ");
N=sc.nextInt();
}while(N<0);//no. of terms cannot be negative
}
private void display()//to print Pell Series
{
System.out.println("The first "+N+" terms of the Pell
series: ");
int a=0,b=1,c; //to store three consecutive terms
for(int i=1;i<=N;i++)
{
if(i==1)
System.out.print(a+", ");
else if(i==2)
System.out.print(b+", ");
else
{
c=2*b+a; //computing the next term
System.out.print(c+", ");
a=b; //updating to next term
b=c; //updating to next term
}
}
}
public static void main(String a[])
{
Pell ob = new Pell(); //creating object of Pell class
ob.accept(); //calling method for input from user
ob.display(); //calling method for displaying terms
}
}

4
LISTINGS
Class Listing
Class
Name Purpose

Represents the Pell series and contains methods to accept user input for
Pell the number of terms and to display the first N terms of the Pell series.

Method Listing
Method
Name Prototype Purpose

private void Accepts the number of terms (N) from the user with
accept accept() input validation.

private void Calculates and displays the first N terms of the Pell
display display() series.

public static
void The entry point of the program that creates an
main(String instance of the Pell class and calls
main a[]) the accept() and display() methods.

VARIABLE LISTING
Variable Data
Name Type Scope Purpose

Stores the number of terms to be displayed


N int Instance in the Pell series.

Scanne Local
sc r (in accept()) Used to read user input from the console.

5
Variable Data
Name Type Scope Purpose

Local
(in display() Stores the first term of the Pell series
a int ) (initially set to 0).

Local
(in display() Stores the second term of the Pell series
b int ) (initially set to 1).

Local
(in display() Used to store the next term in the Pell series
c int ) during calculations.

Local
(in display() Loop counter used to iterate through the
i int ) terms of the Pell series.

Local An instance of the Pell class used to call


ob Pell (in main()) the accept() and display() methods.

6
ASSIGNMENT 2
Program Description
Q2. Write a program in java which takes as
input the name of a student and marks of 5
subjects of the student. The average marks
is calculated for the student. This is
repeated for N students. The program will
display the name and the average marks of
the student with the lowest average marks.
(No sorting or searching technique to be
applied).

Algorithm for the Average Marks Program


Start

Step 1: Main Method (main)


1. Create an instance of the Average class named ob.
2. Call the input() method on the instance ob to gather input from the user.
3. Call the display() method on the instance ob to display the name and lowest
average marks.

End Main Method

Step 2: Input Method (input)


1. Create a Scanner object named sc to read user input.
2. Repeat the following steps until a valid non-negative integer is entered:
 Prompt the user to enter the number of students N.
 Read the integer input and store it in N.

7
3. If N is less than 0, display an error message indicating that the number of
students cannot be negative and repeat the prompt.
4. For each student i from 1 to N:
 Prompt the user to enter the name of the student and store it in a
temporary variable nm.
 Initialize a variable sum to 0.0 to store the total marks for the student.
 For each subject s from 1 to 5:
 Prompt the user to enter the marks for the current subject.
 Read the marks and store it in a variable t.
 If the entered marks t are less than 0.0:
 Display an error message indicating that marks cannot be
negative.
 Decrement i by 1 to re-enter the data for the same
student.
 Otherwise, add the entered marks t to sum.
 If i is 1 (the first student):
 Set name to nm (the name of the first student).
 Calculate the average marks as marks = sum / 5.
 If the average marks of the current student ( sum / 5) are less than the
current lowest average marks (marks):
 Update marks to the new average marks.
 Update name to nm (the name of the current student).

End Input Method

Step 3: Display Method (display)

1. Print the name of the student with the lowest average marks using name.
2. Print the lowest average marks using marks.

End Display Method

8
End

9
OUTPUTS
1.

2.

10
SOURCE CODE
//Program to display the name and lowest average marks
import java.util.Scanner;
class Average
{
private int N;//to store number of students
private String name;//to store names of student with lowest average
marks
private double marks; //to store lowest average marks
private void input()//to take name and marks of students from user
{
Scanner sc=new Scanner(System.in);
do{
System.out.print("Enter number of students: ");
N=sc.nextInt();
}while(N<0);//no. of students cannot be negative
for(int i=1;i<=N;i++)
{
System.out.print("Enter name of Student: ");
String nm=new Scanner(System.in).nextLine();
double sum=0.0;//to store total marks in 5 subjects
for(int s=1;s<=5;s++)
{
System.out.print("Enter marks of "+nm+" in Subject "+s+": ");
double t=sc.nextDouble();
if(t<0.0)
{
System.out.println("Marks cannot be negative. Re-enter.");
i--;
}
else
sum+=t;
}
if(i==1)//one student cannot be compared
{
name=nm;
marks=sum/5;
}
if(sum/5<marks)//comparing and storing the lowest avg. marks
{
marks=sum/5;
name=nm;
}
}
}
private void display()//to display name and lowest average marks
{
System.out.println("Name of Student with lowest average marks:
"+name);
System.out.println("Lowest average marks: "+marks);
}
public static void main(String a[])
{
Average ob = new Average();
ob.input();
ob.display();
}
}

11
LISTINGS
Class Listing
Class
Name Purpose

Represents the functionality to input student names and their


Averag marks, and to determine and display the student with the
e lowest average marks.

Method Listing
Metho
d
Name Prototype Purpose

Gathers input from the user for the number of


students, their names, and their marks. It
private calculates the average marks and determines
input void input() the student with the lowest average marks.

private Displays the name of the student with the lowest


displa void average marks and the corresponding average
y display() marks.

public
static void The entry point of the program that creates an
main(String instance of the Average class and calls
main a[]) the input() and display() methods.

VARIABLE LISTING
Variable Data
Name Type Scope Purpose

N int Instance Stores the number of students.

name String Instance Stores the name of the student with


12
Variable Data
Name Type Scope Purpose

the lowest average marks.

marks double Instance Stores the lowest average marks.

Scann Local Used to read user input from the


sc er (in input()) console.

Local Temporarily stores the name of the


nm String (in input()) current student being processed.

Local Stores the total marks for the current


sum double (in input()) student across 5 subjects.

Local Stores the marks entered for the


t double (in input()) current subject.

Local Loop counter used to iterate through


s int (in input()) the subjects (1 to 5).

Local Loop counter used to iterate through


i int (in input()) the students (1 to N).

13
ASSIGNMENT 3
Program Description
Q3. Hamming numbers are positive integer
numbers whose prime factors include 2,3 and 5
only
Example:
n=6 is an hamming number as 6=2x3 .So its
prime factors are limited to 2 ,3
n=8 is an hamming number as 8=2x2x2 and it
has only 2 as its prime factors
n=90 is an hamming number as 90=2x3x3x5
which has only 2,3,5 as prime factors
n=14 is not a hamming number as 14=2x7 .It has
7 as one of its prime factor
n=44 is not a hamming number as 44=2x2x11. It
has 11 as one of its prime factors
Design a program to accept any positive integer
number and check if it is a Hamming number or
not. Display the result with an appropriate
message in the format specified below. The
program
should also generate error message if a negative
number is entered.

Algorithm for Checking if a Number is Hamming


Start

Step 1: Main Method (main)

1. Create an instance of the Hamming class named ob.


2. Call the input() method on the instance ob to gather input from the user.
3. Call the display() method on the instance ob to check if the number is a
Hamming number and display the result.

End Main Method

14
Step 2: Input Method (input)

1. Create a Scanner object named sc to read user input.


2. Repeat the following steps until a valid positive integer is entered:
 Prompt the user to enter a number and store it in num.
 If num is less than or equal to 0, display an error message indicating
that negative numbers are not allowed and prompt the user to re-enter
the number.

End Input Method

Step 3: Display Method (display)

1. Print the output header with the number num.


2. Initialize a variable f to 2 (the smallest prime factor) and a variable n to num.
3. While n is not equal to 1:
 If n is divisible by f (i.e., n % f == 0):
 Print the factor f.
 Divide n by f.
 If n is not divisible by f:
 Increment f by 1 to check the next potential factor.
 Continue to the next iteration of the loop.
 If n is not equal to 1 after the loop and f is less than or equal to 5, print
that num is a Hamming number.
 Otherwise, print that num is not a Hamming number.

End Display Method

End

15
OUTPUTS

1.

2.

16
SOURCE CODE
//Program to check if a number is Hamming or not
import java.util.Scanner;
class Hamming
{
private int num;
private void input()//to take number from user
{
Scanner sc=new Scanner(System.in);
do{
System.out.print("INPUT: Enter any number: ");
num=sc.nextInt();
if(num<=0) //to print error message
System.out.println("NEGATIVE not allowed. Re-enter.");
}while(num<=0); //no. must be positive
}
private void display()//to print prime factors of number and
hence determine hamming or not
{
System.out.print("OUTPUT: "+num+"= ");
int f=2,n=num;
while(n!=1)
{
if(n%f==0)
{
System.out.print(f);
n/=f;
}
else
{
f++;
continue;
}
if(n!=1)
System.out.print(" x ");
}
if(num!=1 && f<=5)
System.out.print("\n"+num+" IS A HAMMING NUMBER");
else
System.out.print("\n"+num+" IS A NOT A HAMMING
NUMBER");
}
public static void main(String a[])
{
Hamming ob = new Hamming();
ob.input();
ob.display();
}
}

17
LISTINGS
Class Listing

Class
Name Purpose
Represents the functionality to check if a
Hammi number is a Hamming number by
ng determining its prime factors.

Method Listing

Meth
od
Name Prototype Purpose
private Gathers input from the user for a
void positive integer and validates the
input input() input.
Calculates and displays the prime
private factors of the number and
displa void determines if it is a Hamming
y display() number.
The entry point of the program that
public creates an instance of
static void the Hamming class and calls
main(Stri the input() and display() method
main ng a[]) s.

18
Variable Listing

Varia
ble Data
Name Type Scope Purpose
Stores the number input by
num int Instance the user.
Local
Scanne (in input( Used to read user input
sc r )) from the console.
Local Stores the current factor
(in displa being checked (starting
f int y()) from 2).
Local
(in displa Stores a copy of num for
n int y()) factorization purposes.
An instance of
the Hamming class used to
Local call
Hammi (in main( the input() and display()
ob ng )) methods.

19
ASSIGNMENT 4
Program Description
Q4. Lucky numbers are a sequence of natural
numbers that remain after removing second,
third, fourth, fifth and so on numbers
respectively from a sequence of consecutive
natural numbers.
Consider the sequence of first 20 natural
numbers :
Removing every second number produces the
sequence 1, 3, 5, 7, 9, 11, 13, 15, 17, 19
Next removing every third number produces the
sequence 1, 3, 7, 9, 13, 15, 19
Next removing every fourth number produces the
sequence : 1, 3, 7, 13, 15, 19
Further deleting every fifth number we get the
sequence : 1, 3, 7, 13, 19
Deletion of every sixth number is not possible
and the five numbers that are lucky to escape
deletion
remain indefinitely.
Write a program to enter any positive natural
number ‘N’ where (1<=N<=50) and generate
lucky numbers less than the given natural
number.

Algorithm for Generating Lucky


Numbers
Start
Step 1: Main Method (main)
1. Create an instance of the Lucky class named ob.
2. Call the input() method on the instance ob to gather
input from the user.
3. Call the gen() method on the instance ob to generate
lucky numbers.
4. Call the display() method on the instance ob to display
the lucky numbers.
End Main Method
20
Step 2: Input Method (input)
1. Create a Scanner object named sc to read user input.
2. Repeat the following steps until a valid integer N is
entered (where N is between 1 and 50):
 Prompt the user to enter a value for N.
 Read the integer input and store it in N.
3. Set size to N - 1 (to account for lucky numbers less
than N).
4. Initialize an array set of size size to store natural numbers
from 1 to N-1.
5. Fill the set array with natural numbers:
 For each index i from 0 to size - 1, set set[i] to i +
1.
End Input Method

Step 3: Generate Method (gen)


1. Initialize a variable c to 2 (the position of the integer to be
removed).
2. While c is less than or equal to size:
 For each index i from 0 to size - 1:
 If (i + 1) % c == 0, set set[i] to 0 (marking the
integer for removal).
 For each index i from 0 to size - 1:
 If set[i] is 0:
 For each index j from i to size - 2:
 Shift the elements to the left to
remove the marked integer.
 Decrement size by 1 to reflect the removal
of an integer.
 Increment c by 1 to check the next position.
End Generate Method

Step 4: Display Method (display)


1. Print the output header indicating the lucky numbers less
than N.
2. For each index i from 0 to size - 1, print the lucky
number set[i] followed by a comma.
End Display Method

End

21
OUTPUTS

1.

22
2.

SOURCE CODE
//Program to generate lucky numbers less than the given natural number
import java.util.Scanner;
class Lucky
{
private int N;
private int set[];
private int size; //store no. of integers in the set
private void input()
{
Scanner sc = new Scanner(System.in);
do{
System.out.print("INPUT: N=");
N=sc.nextInt();
}while(N<1||N>50);

23
size=N-1; //lucky nos. less than N are required
set=new int[size];
for(int i=0;i<size;i++)//to fill set with natural numbers
set[i]=i+1;
}
private void gen()//to generate lucky numbers
{
int c=2; //stores position of integer to be removed
while(c<=size)
{
for(int i=0;i<size;i++)
{
if((i+1)%c==0)//for removing integer
set[i]=0;
}
for(int i=0;i<size;i++)
{
if(set[i]==0)
{
for(int j=i;j<size-1;j++)//removing the integers
set[j]=set[j+1];
size--;
}
}
c++;
}
}
private void display()//to print luck numbers within range
{
System.out.print("OUTPUT: LUCKY NUMBERS LESS THAN "+N+" ARE:
");
for(int i=0;i<size;i++)
System.out.print(set[i]+",");
}
public static void main(String a[])
{
Lucky ob = new Lucky();
ob.input();
ob.gen();
ob.display();
}
}

LISTINGS
Class Listing
Class
Name Purpose
Represents the functionality to generate and
display lucky numbers less than a given
Lucky natural number.

24
Method Listing
Metho
d
Name Prototype Purpose
Gathers input from the user for a
natural number N and initializes
private the set of natural numbers less
input void input() than N.
Generates lucky numbers by
removing certain integers from
private the set based on the lucky
gen void gen() number algorithm.
private Displays the lucky numbers that
displa void were generated and are less
y display() than N.
The entry point of the program
public that creates an instance of
static void the Lucky class and calls
main(Strin the input(), gen(),
main g a[]) and display() methods.

Variable Listing

25
Variab
le Data
Name Type Scope Purpose
Stores the upper limit
for generating lucky
N int Instance numbers.
Array to store natural
numbers from 1 to N-
set int[] Instance 1.
Stores the number of
size int Instance integers in the set.
Used to read user
Scann Local input from the
sc er (in input()) console.
Stores the position of
the integer to be
removed in the lucky
number generation
c int Local (in gen()) process.
Local Loop counter used to
(in input() and iterate through
i int gen()) the set.
Loop counter used to
shift elements in
the set when
j int Local (in gen()) removing integers.
ob Lucky Local (in main())An instance of
the Lucky class used
to call
26
Variab
le Data
Name Type Scope Purpose
the input(), gen(),
and display() method
s.

ASSIGNMENT 5
Program Description
Q5. Write a program which takes n integers as
input (max 50 integers) and stores them in an
array data from index 0 to n-1.
Now we want to rearrange the integers in the
following way:-
Find the maximum value and put it in position
(n/2) [for odd number of elements] and position
(n/2 -1)[ for even number of elements]);
find the second largest value and put it to its
right;
then the next largest and place it and place it to
its left and so on altering left and right until all
the integers are done.
Initial array:-
7, 3, 1, 6, 4, 2, 5
then after rearranging it becomes
1, 3, 5, 7, 6, 4, 2

Algorithm for Sorting Integers Altering Left


and Right
Start
Step 1: Main Method (main)
1. Create an instance of the Pendulum class named ob.
27
2. Call the input() method on the instance ob to gather
input from the user.
3. Print the message "INITIAL" to indicate the initial state of
the array.
4. Call the display() method on the instance ob to display
the initial array.
5. Call the sort() method on the instance ob to sort the
integers in descending order.
6. Call the rearrange() method on the instance ob to
rearrange the integers alternating left and right.
7. Print the message "After Rearranging" to indicate the state
of the array after rearrangement.
8. Call the display() method on the instance ob to display
the rearranged array.
End Main Method

Step 2: Input Method (input)


1. Create a Scanner object named sc to read user input.
2. Repeat the following steps until a valid integer n is
entered (where n is between 0 and 50):
 Prompt the user to enter the number of integers n.
 Read the integer input and store it in n.
3. Initialize an array a of size n to store the integers.
4. For each index i from 0 to n-1:
 Prompt the user to enter an integer and store it
in a[i].
End Input Method

Step 3: Sort Method (sort)


1. For each index i from 0 to n-2:
 Initialize a variable max to i.
 For each index j from i+1 to n-1:
 If a[j] is greater than a[max], update max to j.
 Swap the values of a[i] and a[max] to place the
maximum value at the correct position.
End Sort Method

Step 4: Rearrange Method (rearrange)


1. Initialize a new array x of size n to store the rearranged
integers.
2. Calculate the initial position pos based on whether n is
even or odd:
 If n is even, set pos to n/2 - 1.
 If n is odd, set pos to n/2.
3. For each index i from 0 to n-1:
28
 Update pos based on whether i is even or odd:
 If i is even, decrement pos by i.
 If i is odd, increment pos by i.
 Assign the value of a[i] to x[pos].
4. Assign the rearranged array x back to a.
End Rearrange Method

Step 5: Display Method (display)


1. Print the message "ARRAY:" to indicate the array contents.
2. For each index i from 0 to n-1, print the value
of a[i] followed by a comma.
3. Print a newline for better formatting.
End Display Method

End

29
OUTPUTS

1.

2.

30
SOURCE CODE
//Program to sort integers altering left and right
import java.util.Scanner;
class Pendulum
{
private int a[],n;
private void input()//to take tegers from user
{
Scanner sc = new Scanner(System.in);
do{
System.out.print("Enter n (no. of integers) :");
n=sc.nextInt();
}while(n<0||n>50);
a=new int[n]; //initialsing array
for(int i=0;i<n;i++)
{
System.out.print("Enter integer: ");
a[i]=sc.nextInt();
}
}
private void sort()//to sort integers in descending order
{
for(int i=0;i<n-1;i++)
{
int max=i;
for(int j=i+1;j<n;j++)
{
if(a[j]>a[max])
max=j;
}
int t=a[i];
a[i]=a[max];
a[max]=t;
}
}
private void rearrange()//to arrange integers altering left and right
{
int x[]=new int[n];
int pos=(n%2==0)?n/2-1:n/2; //choosing position for the maximum integer
for(int i=0;i<n;i++)
{
pos+=(i%2==0)?-i:i; //alternating position
x[pos]=a[i];
}
a=x;
}
private void display() //to display all integers
{
System.out.println("ARRAY: ");
for(int i=0;i<n;i++)
System.out.print(a[i]+",");
System.out.println();
}
public static void main(String a[])
{
Pendulum ob = new Pendulum();
ob.input();
System.out.print("INITIAL ");
ob.display();
ob.sort();
ob.rearrange();
System.out.print("After Rearranging ");
ob.display();
}
}

LISTINGS
31
Class Listing
Class
Name Purpose

Represents the functionality to sort integers and


Pendulu rearrange them in an alternating left and right
m pattern.

Method Listing
Method
Name Prototype Purpose

private Gathers input from the user for the


void number of integers and initializes the
input input() array with those integers.

private Sorts the integers in the array in


sort void sort() descending order.

private
void
rearran rearrange( Rearranges the sorted integers in an
ge ) alternating left and right pattern.

private
void
display display() Displays the contents of the array.

The entry point of the program that


public creates an instance of
static void the Pendulum class and calls
main(Strin the input(), sort(), rearrange(),
main g a[]) and display() methods.

32
Variable Listing
Variab
le Data
Name Type Scope Purpose

Array to store the integers


a int[] Instance input by the user.

Stores the number of


integers to be sorted and
n int Instance rearranged.

Scanne Local Used to read user input from


sc r (in input()) the console.

Stores the index of the


Local maximum integer found
max int (in sort()) during sorting.

Local
(in rearrange( Temporary array to store the
x int[] )) rearranged integers.

Local Stores the current position


(in rearrange( for placing integers in the
pos int )) rearranged array.

Local
(in input(), so
rt(),
and rearrange Loop counter used to iterate
i int ()) through the arrays.

Loop counter used to find the


Local maximum integer during
j int (in sort()) sorting.

ob Pendul Local An instance of


um (in main()) the Pendulum class used to

33
Variab
le Data
Name Type Scope Purpose

call
the input(), sort(), rearran
ge(),
and display() methods.

34
ASSIGNMENT 6
Program Description
Q6. Write a program to declare a matrix A [ ] [ ]
of order (M × N) where ‘M’ is the number of rows
and ‘N’ is the number of columns such that both
M and N must be greater than 2 and less than
10.Allow the user to input integers into this
matrix. Display appropriate error message for an
invalid input. Perform the following tasks on the
matrix.
(a) Display the input matrix
(b) Rotate the matrix by 270 degrees anti clock
wise and display the resultant matrix
(c) Calculate the sum of the odd elements of the
matrix and display

Algorithm for Rotating a Matrix 270° Anti-


Clockwise and Computing Sum of Odd Elements
Start
Step 1: Main Method (main)
1. Create an instance of the Rotation class named ob.
2. Call the input() method on the instance ob to gather
input from the user.
3. Print the message "OUTPUT:" to indicate the start of
the output section.
4. Print the message "ORIGINAL MATRIX:" to indicate
the original matrix.
5. Call the display() method on the instance ob to
display the original matrix.
6. Call the rotate() method on the instance ob to rotate
the matrix 270° anti-clockwise.
7. Print the message "ROTATED MATRIX (270 ANTI
CLOCK WISE)" to indicate the rotated matrix.
8. Call the display() method on the instance ob to
display the rotated matrix.
9. Call the calcSum() method on the instance ob to
calculate the sum of odd elements in the rotated
matrix.
10. Print the sum of the odd elements
using ob.oddsum.
End Main Method

35
Step 2: Input Method (input)
1. Create a Scanner object named sc to read user input.
2. Declare two integer variables M and N to store the
dimensions of the matrix.
3. Print the message "INPUT:" to indicate the start of
input.
4. Repeat the following steps until valid dimensions are
entered (where M and N are both greater than 2 and
less than 10):
 Prompt the user to enter the number of rows M.
 Prompt the user to enter the number of
columns N.
 If M is less than or equal to 2, or greater than or
equal to 10, or if N is less than or equal to 2, or
greater than or equal to 10, display an error
message and prompt the user to re-enter the
dimensions.
5. Initialize a 2D array A of size M x N to store the
matrix elements.
6. Print the message "ENTER ELEMENTS:" to prompt the
user to enter the matrix elements.
7. For each index i from 0 to M-1:
 For each index j from 0 to N-1:
 Read the integer input and store it in A[i][j].
End Input Method

Step 3: Display Method (display)


1. For each index i from 0 to the length of A:
 For each index j from 0 to the length of A[i]:
 Print the value of A[i][j] followed by a tab
character.
 Print a newline after each row to format the
matrix.
End Display Method

Step 4: Rotate Method (rotate)


1. Initialize a new 2D array Ar of size [A[0].length]
[A.length] to store the rotated matrix.
2. For each index i from 0 to the length of Ar:
 For each index j from 0 to the length of Ar[i]:
 Assign the value of A[(A.length - 1) - j]
[i] to Ar[i][j] to perform the 270° anti-
clockwise rotation.
3. Assign the rotated array Ar back to A.
End Rotate Method

Step 5: Calculate Sum Method (calcSum)


36
1. Initialize oddsum to 0 to store the sum of odd
elements.
2. For each index i from 0 to the length of A:
 For each index j from 0 to the length of A[i]:
 If A[i][j] is odd (i.e., A[i][j] % 2 == 1):
 Add A[i][j] to oddsum.
End Calculate Sum Method

End

37
OUTPUTS

1.

2.

SOURCE CODE

38
//Program to rotate a matrix 270° anti-clockwise and compute sum of odd elements
import java.util.Scanner;
class Rotation
{
private int A[][],oddsum;
private void input()//to take size and elements of matrix
{
Scanner sc = new Scanner(System.in);
int M,N;
System.out.println("INPUT: ");
do{
System.out.print("M= ");
M=sc.nextInt();
System.out.print("N= ");
N=sc.nextInt();
if(M<=2||N<=2||M>=10||N>=10)
System.out.println("INVALID INPUT. Re-enter.");
}while(M<=2||N<=2||M>=10||N>=10); //row and column size must be >2 & <10
A=new int [M][N];
System.out.println("ENTER ELEMENTS: ");
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
A[i][j]=sc.nextInt();
}
}
}
private void display() //to display the matrix
{
for(int i=0;i<A.length;i++)
{
for(int j=0;j<A[i].length;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
}
private void rotate()//to rotate the matrix
{
int Ar[][]=new int[A[0].length][A.length];
for(int i=0;i<Ar.length;i++)
{
for(int j=0;j<Ar[i].length;j++)
{
Ar[i][j]=A[(A.length-1)-j][i];
}
}
A=Ar;
}
private void calcSum()//to calculate sum of odd elements
{
for(int i=0;i<A.length;i++)
{
for(int j=0;j<A[i].length;j++)
{
if(A[i][j]%2==1)
oddsum+=A[i][j];

}
}
}
public static void main(String a[])
{
Rotation ob = new Rotation();
ob.input();
System.out.println("OUTPUT: ");
System.out.println("ORIGINAL MATRIX: ");
ob.display();
ob.rotate();
System.out.println("ROTATED MATRIX (270 ANTI CLOCK WISE)");
ob.display();
ob.calcSum();
System.out.println("SUM OF THE ODD ELEMENTS = "+ob.oddsum);
}
}

39
LISTINGS
Class Listing
Class
Name Purpose

Represents the functionality to rotate a matrix 270°


Rotatio anti-clockwise and compute the sum of odd
n elements in the matrix.

Method Listing
Metho
d
Name Prototype Purpose

private
void Gathers input from the user for the size
input input() and elements of the matrix.

private
void
display display() Displays the contents of the matrix.

private
void
rotate rotate() Rotates the matrix 270° anti-clockwise.

private
calcSu void Calculates the sum of odd elements in
m calcSum() the matrix.

The entry point of the program that


public creates an instance of
static void the Rotation class and calls
main(Strin the input(), display(), rotate(),
main g a[]) and calcSum() methods.

Variable Listing

40
Variab
le Data
Name Type Scope Purpose

2D array to store the


A int[][] Instance elements of the matrix.

oddsu Stores the sum of odd


m int Instance elements in the matrix.

Stores the number of rows


M int Local (in input()) in the matrix.

Stores the number of


N int Local (in input()) columns in the matrix.

Scann Used to read user input


sc er Local (in input()) from the console.

Local
(in display(), rot Loop counter used to
ate(), iterate through the rows of
i int and calcSum()) the matrix.

Local
(in display(), rot Loop counter used to
ate(), iterate through the columns
j int and calcSum()) of the matrix.

Temporary 2D array to
Ar int[][] Local (in rotate()) store the rotated matrix.

Used to determine the


position of elements during
pos int Local (in rotate()) rotation.

ob Rotati Local (in main()) An instance of


on the Rotation class used to
call
the input(), display(), rot
ate(),

41
Variab
le Data
Name Type Scope Purpose

and calcSum() methods.

42
ASSIGNMENT 7
Program Description
Q7. A class Encode has been defined to replace only the
vowels in a word by the next corresponding vowel and
form a new word.
i.e. A → E, E → I, I → O, O → U, U → A and a →e, e → i, i
→ o, o → u, and u → a

Example: Input: Institution


Output: Onstotatoun

Some of the members of the class are given below:


Class name : Encode
Data members/instance variables:
word : to store a word
length : integer to store the length of the word
new_word : to store the encoded word
Methods / Member functions:
Encode( ) : default constructor to initialize data
members with legal initial values
void acceptWord( ) : to accept a word
void nextVowel( ) : to replace only the vowels from the
word stored in ‘word’ by the next corresponding vowel
and to assign it to ‘newword’, with the remaining
alphabets unchanged
void display( ) : to display the original word along with
the encrypted word

Specify the class Encode giving details of the


constructor( ), void acceptWord( ), void nextVowel( )
and void display( ). Define a main ( ) function to create
an object and call the functions accordingly to enable
the task.

Algorithm for Replacing Vowels in a Word


with the Next Corresponding Vowel
Start
Step 1: Main Method (main)
1. Create an instance of the Encode class named ob.
2. Call the acceptWord() method on the instance ob to
gather input from the user.

43
3. Call the nextVowel() method on the instance ob to
generate the encrypted word by replacing vowels.
4. Call the display() method on the instance ob to
display the original and encrypted words.
End Main Method

Step 2: Constructor (Encode)


1. Initialize the instance variables:
 Set word to an empty string.
 Set new_word to an empty string.
 Set length to 0.
End Constructor

Step 3: Accept Word Method (acceptWord)


1. Create a Scanner object named sc to read user
input.
2. Print the message "Enter a word:" to prompt the
user.
3. Read the input word from the user and store it in
the variable word.
End Accept Word Method

Step 4: Next Vowel Method (nextVowel)


1. For each index i from 0 to the length of word minus
1:
 Get the character ch at index i from word.
 If ch is a vowel (check if ch is in the string
"AEIOUaeiou"):
 Find the index of ch in the string
"AEIOUAaeioua".
 Append the next vowel (the character at
the index + 1) to new_word.
 If ch is not a vowel:
 Append ch to new_word.
End Next Vowel Method

Step 5: Display Method (display)


1. Print the message "ORIGINAL WORD: " followed by
the value of word.
2. Print the message "ENCRYPTED WORD: " followed
by the value of new_word.
End Display Method

End

44
45
OUTPUTS

1.

2.
46
SOURCE CODE
//Program to replace only the vowels in a word by the next
corresponding vowel
import java.util.Scanner;
class Encode
{
private String word,new_word;
private int length;
private Encode()// default constructor to initialize data
members with legal initial values
{
word=new_word="";
length=0;
}
private void acceptWord()//to take word from user
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
word=sc.next();
}
private void nextVowel()//to generate encrypted word by
replaceing each vowel with next vowel
47
{
for(int i=0;i<word.length();i++)
{
char ch=word.charAt(i);
if("AEIOUaeiou".indexOf(ch)>=0)//checking letter is
vowel or not

new_word+="AEIOUAaeioua".charAt("AEIOUAaeioua".indexO
f(ch)+1);// adding next vowel
else
new_word+=ch;
}
}
private void display()//to display original wod and
encrypted word
{
System.out.println("ORIGINAL WORD: "+word);
System.out.println("ENCRYPTED WORD: "+new_word);
}
public static void main(String a[])
{
Encode ob = new Encode();
ob.acceptWord();
ob.nextVowel();
ob.display();
}
}

LISTINGS
Class Listing
Class
Name Purpose
Represents the functionality to replace
vowels in a word with the next
Encod corresponding vowel and display the
e original and encrypted words.

Method Listing

48
Method
Name Prototype Purpose
Default constructor to
private initialize data members
Encode Encode() with legal initial values.
private
void Gathers input from the user
acceptW acceptWor for the word to be
ord d() processed.
private
void Generates the encrypted
nextVow nextVowel( word by replacing each
el ) vowel with the next vowel.
private
void Displays the original word
display display() and the encrypted word.
The entry point of the
program that creates an
public instance of
static void the Encode class and calls
main(Strin the acceptWord(), nextVow
main g a[]) el(), and display() methods.

Variable Listing
Variabl Data
e Name Type Scope Purpose

Stores the original word


word String Instance input by the user.

49
Variabl Data
e Name Type Scope Purpose

Stores the encrypted


new_wo word with vowels
rd String Instance replaced.

Stores the length of the


original word (not actively
length int Instance used).

Local
Scann (in acceptWo Used to read user input
sc er rd()) from the console.

Local Stores the current


(in nextVowe character being processed
ch char l()) from the word.

Local Loop counter used to


(in nextVowe iterate through the
i int l()) characters of the word.

An instance of
the Encode class used to
call
the acceptWord(), nextVo
Encod Local wel(),
ob e (in main()) and display() methods.

50
ASSIGNMENT 8
Program Description
Q8. Write a program which will accept two octal
numbers from user. Add them and display final
result. (Do validation check) [Don’t convert the
numbers to decimal number system]

Algorithm for Adding Two Octal


Numbers
Start
Step 1: Main Method (main)
1.Create a Scanner object named sc to read
user input.
2.Declare
two String variables octal1 and octal2 to
store the octal numbers.
3.Call the acceptOctalNumbers() method to
gather input from the user.
4.Call the addOctalNumbers(octal1,
octal2) method to add the two octal numbers
and store the result.
5.Call the displayResult(result) method to
display the final result.
End Main Method

Step 2: Accept Octal Numbers Method


(acceptOctalNumbers)
1.Repeat the following steps until valid octal
numbers are entered:
 Prompt the user to enter the first octal
number and store it in octal1.
 Validate octal1 to ensure it contains only
digits from 0 to 7:
 If invalid, display an error message
and prompt the user to re-enter.
 Prompt the user to enter the second
octal number and store it in octal2.
51
Validate octal2 to ensure it contains only
digits from 0 to 7:
 If invalid, display an error message
and prompt the user to re-enter.
End Accept Octal Numbers Method

Step 3: Add Octal Numbers Method


(addOctalNumbers)
1.Initialize an empty String variable result to
store the sum.
2.Initialize two integer
variables carry and sum to 0.
3.Determine the maximum length of the two
octal numbers (maxLength).
4.Pad both octal1 and octal2 with leading zeros
to make their lengths equal to maxLength.
5.For each index i from maxLength - 1 down
to 0:
 Convert the characters at
index i of octal1 and octal2 to integers.
 Calculate the sum of the two digits and
the carry.
 If the sum is greater than or equal to 8:
 Set carry to 1 (since octal is base 8).
 Set sum to sum % 8 (to get the last
digit).
 Otherwise, set carry to 0.
 Prepend sum to the result.
6.If there is a carry left after the loop,
prepend 1 to the result.
7.Return the result.
End Add Octal Numbers Method

Step 4: Display Result Method (displayResult)


1.Print the message "The sum of the octal
numbers is: " followed by the result.
End Display Result Method

End

52
53
OUTPUTS

1.

2.

SOURCE CODE
//Program to add two octal numbers
import java.util.Scanner;

54
class AddOctal
{
private int num1,num2,sum;
private void input()//to take input from user
{
Scanner sc = new Scanner(System.in);
do{
System.out.print("Enter octal number: ");
num1=sc.nextInt();
System.out.print("Enter octal number: ");
num2=sc.nextInt();
if(!(check(num1) && check(num2)) )
System.out.println("NOT OCTAL numbers. Re-enter.");
}while(!(check(num1) && check(num2)) );//checking methods are octal or not
}
private boolean check(int x)//to check the parameter is octal
{
while(x>0)
{
if(x%10>=8)
return false;
x/=10;
}
return true;
}
private void add()//to calculate the sum of the two octal numbers
{
int d=Math.max((int)Math.log10(num1)+1,(int)Math.log10(num2)+1);//counting max no. of digits
int n1[]=new int[d];
int n2[]=new int[d];
for(int i=d-1,o1=num1,o2=num2;i>=0;i--)//storing the digits in the 2 arrays
{
n1[i]=o1%10;
o1/=10;
n2[i]=o2%10;
o2/=10;
}
int sum1[]=new int[d];
boolean carry=false;
for(int i=d-1;i>=0;i--)
{
int s=n1[i]+n2[i];
if(carry)//if carry is there adding 1
{
s++;
carry=false;
}
if(s<8) //highest digtit is 7
sum1[i]=s;
else
{
sum1[i]=s-8;
carry=true;
}
}
sum=(carry)?1:0;
for(int i=0;i<d;i++)//to store the resultant sum in data member
{
sum=sum*10+sum1[i];
}
}
private void display()//to display the octal numbers and their sum
{
System.out.println("Octal number: "+num1);
System.out.println("Octal number: "+num2);
System.out.println("Octal sum: "+sum);
}
public static void main(String a[])
{
AddOctal ob = new AddOctal();
ob.input();
ob.add();
ob.display();
}
}

LISTINGS
Class Listing
55
Class
Name Purpose

Represents the functionality to accept two


AddOct octal numbers, add them, and display the
al result.

Method Listing
Method
Name Prototype Purpose

public static The entry point of the program


void that orchestrates the input,
main main(String a[]) addition, and output.

Gathers input from the user for


private void two octal numbers and
input input() validates them.

private boolean Checks if the given integer is a


check check(int x) valid octal number.

private void Calculates the sum of the two


add add() octal numbers.

private void Displays the two octal numbers


display display() and their sum.
Variable Listing
Variabl
e Data
Name Type Scope Purpose

Stores the first octal number


num1 int Instance input by the user.

Stores the second octal


num2 int Instance number input by the user.

sum int Instance Stores the sum of the two

56
Variabl
e Data
Name Type Scope Purpose

octal numbers.

Scann Local Used to read user input from


sc er (in input()) the console.

Parameter
(in check(in The octal number being
x int t x)) checked for validity.

Stores the maximum number


Local of digits
d int (in add()) between num1 and num2.

Local Array to store the digits of


n1 int[] (in add()) the first octal number.

Local Array to store the digits of


n2 int[] (in add()) the second octal number.

Local Array to store the resultant


sum1 int[] (in add()) sum of the octal addition.

Indicates whether there is a


boolea Local carry during the addition
carry n (in add()) process.

Loop counter used for


Local iterating through the digits
i int (in add()) of the octal numbers.

Temporary variable to hold


Local the value of num1 during
o1 int (in add()) digit extraction.

Temporary variable to hold


Local the value of num2 during
o2 int (in add()) digit extraction.

ob AddOc Local An instance of


57
Variabl
e Data
Name Type Scope Purpose

the AddOctal class used to


call the input(), add(),
tal (in main()) and display() methods.

ASSIGNMENT 9
Program Description
Q9. Write a program in JAVA to accept day number
(between 1 and 366) and year (yyyy) from the user and
display the corresponding date. Also accept ‘N’ from the
user where (1<=N<=100) to compute and display the
future date ‘N’ days after the given date. Display error
message if the value of the day number or ‘N’ are not
within the limit.
Day number is calculated taking 1st January of the
given year as 1.

Algorithm for Displaying


Corresponding Date and Future
Date
Start
Step 1: Main Method (main)
1. Create an instance of the Date class named ob.
2. Call the input() method on the instance ob to
gather input from the user.
3. Print "OUTPUT: ENTERED DATE: ".
4. Call the displayCDate(int days, int yr) method on
the instance ob with
parameters ob.dno and ob.yyyy to display the
corresponding date.
5. Print ob.N + " DAYS LATER: ".
6. Call the displayCDate(int days, int yr) method on
the instance ob with parameters ob.dno +
ob.N and ob.yyyy to display the future date.
End Main Method
58
Step 2: Input Method (input)
1. Create a Scanner object named sc to read user
input.
2. Declare an integer variable d to store the maximum
number of days in the year.
3. Repeat the following steps until a valid day number
(dno) is entered:
 Prompt the user to enter the day number and
store it in dno.
 Prompt the user to enter the year and store it
in yyyy.
 Determine if the year is a leap year:
 If the year is divisible by 4, set d to 366
(leap year).
 Otherwise, set d to 365 (non-leap year).
 If dno exceeds d, display an error message
"DAY NUMBER EXCEEDING YEAR."
4. Repeat the following steps until a valid value
for N is entered:
 Prompt the user to enter N and store it in N.
 If N is less than 1 or greater than 100, display
an error message "NOT WITHIN LIMIT. Re-
enter."
End Input Method

Step 3: Display Corresponding Date Method


(displayCDate(int days, int yr))
1. Initialize an integer variable mm with the value 1
(to represent the month).
2. While days is greater than the number of days in
month mm of year yr:
 Subtract the number of days in
month mm from days.
 Increment mm by 1.
 If mm equals 13 (indicating the next year):
 Set mm to 1 and increment yr by 1.
3. Print the corresponding date in the format "MONTH
DAY, YEAR".
End Display Corresponding Date Method

Step 4: Days of Month Method (daysOf(int mm, int


yyyy))
1. If mm is 2 (February):

59
 Return 29 if yyyy is a leap year; otherwise,
return 28.
2. If mm is less than or equal to 7:
 Return 31 for odd months and 30 for even
months.
3. If mm is greater than 7:
 Return 31 for even months and 30 for odd
months.
End Days of Month Method

End

60
OUTPUTS

1.

2.

3.

SOURCE CODE
//Program to display corresponding date and future date
import java.util.Scanner;
61
class Date
{
private int dno,yyyy,N;
private String
months[]={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","S
EPTEMBEER","OCTOBER","NOVEMBER","DECEMBER"};
private void input()//to take day no. and year from user and N
{
Scanner sc = new Scanner(System.in);
int d;//to store maximum no. of days in the year
do{
System.out.print("INPUT: DAY NUMBER: ");
dno=sc.nextInt();
System.out.print("YEAR: ");
yyyy=sc.nextInt();
d=(yyyy%4==0)?366:365;
if(dno>d)
System.out.println("DAY NUMBER EXCEEDING YEAR.");
}while(dno>d);
do{
System.out.print("N: ");
N=sc.nextInt();
if(N<1 || N>100)
System.out.println("NOT WITHIN LIMIT. Re-enter.");
}while(N<1 || N>100);
}
private void displayCDate(int days,int yr)//to display corresponding date of that yr
{
int mm=1;//mm stores month number
while(days>daysOf(mm,yr))
{
days=days-daysOf(mm,yr);
mm++;
if(mm==13)//when month is of next year
{
mm=1;
yr++;
}
}
System.out.println(months[mm-1]+" "+days+", "+yr);
}
private int daysOf(int mm,int yyyy)//return no. of days in mm month and yyyy year
{
if(mm==2)
return(yyyy%4==0)?29:28;
else if(mm<=7) //till July odd moths have 31 days
return(mm%2==0)?30:31;
else //after August even months have 31 days
return(mm%2==0)?31:30;
}
public static void main(String a[])
{
Date ob = new Date();
ob.input();
System.out.print("OUTPUT: ENTERED DATE: ");
ob.displayCDate(ob.dno,ob.yyyy);
System.out.print(ob.N+" DAYS LATER: ");
ob.displayCDate(ob.dno+ob.N,ob.yyyy);
}
}

62
LISTINGS
Class Listing
Class
Name Purpose

Represents the functionality to accept a day number


and year, and to calculate and display the
Date corresponding date and a future date.

Method Listing
Method
Name Prototype Purpose

The entry point of the program


public static void that orchestrates the input,
main main(String a[]) date calculation, and output.

Gathers input from the user for


the day number, year, and the
input private void input() number of days to add (N).

private void Displays the corresponding


displayCD displayCDate(int date based on the day number
ate days, int yr) and year.

private int
daysOf(int mm, int Returns the number of days in
daysOf yyyy) a given month and year.

Variable Listing
Variabl
e Data
Name Type Scope Purpose

Stores the day number input


dno int Instance by the user.

Stores the year input by the


yyyy int Instance user.

63
Variabl
e Data
Name Type Scope Purpose

Stores the number of days to


N int Instance add to the entered date.

month String Array that holds the names


s [] Instance of the months.

Scann Used to read user input from


sc er Local (in input()) the console.

Stores the maximum number


d int Local (in input()) of days in the year.

Local Stores the current month


(in displayCDate(i number during date
mm int nt days, int yr)) calculation.

Parameter The number of days


(in displayCDate(i remaining to calculate the
days int nt days, int yr)) corresponding date.

Parameter The year for which the


(in displayCDate(i corresponding date is being
yr int nt days, int yr)) calculated.

Local Loop counter used for


(in daysOf(int mm, iterating through the
i int int yyyy)) months.

An instance of the Date class


used to call
the input(), displayCDate(),
ob Date Local (in main()) and other methods.

64
ASSIGNMENT 10
Program Description
Q10. A snowball string is a sentence where each word is
arranged in ascending order of their length and is also
consecutive.

For example:
“I am the Lord” is a snowball string as
 Length of word ‘I’ is 1
 Length of word ‘am’ is 2
 Length of word ‘the’ is 3
 Length of word ‘Lord’ is 4
The length of each word is one more than the previous
word.
Hence, they are consecutive and in ascending order.

Write a program to enter any sentence and check if it is


a snowball string or not. The words in the sentence may
be separated by a one or more spaces and terminated
by ‘.’ or ‘?’ only. The program will generate appropriate
error message for any other terminating character.

Algorithm for Checking a Sentence as a


Snowball String
Start
Step 1: Main Method (main)
1.Create an instance of the SnowBall class
named ob.
2.Call the input() method on the instance ob to
gather input from the user.
3.Call the display() method on the
instance ob to show the result.
End Main Method

Step 2: Input Method (input)


1.Declare a character variable l.
2.Start a do-while loop:
 Step 2.1: Print "INPUT: " to prompt the
user for input.

65
 Step 2.2: Read the input sentence
using Scanner and store it in the
variable sent.
 Step 2.3: Get the last character of the
sentence and assign it to l:
 l = sent.charAt(sent.length() - 1);
 Step 2.4: Check if l is not equal
to . and l is not equal to ?:
 Step 2.4.1: If true, print "Sentence
not terminated by '?' or '.' Re-enter."
3.Step 3: Repeat the loop until l is either . or ?.
End Input Method

Step 3: Check Snowball String Method


(isSnowball)
1.Create a string array words by splitting the
sentence sent (excluding the last character)
using whitespace as a delimiter:
 String words[] = sent.substring(0,
sent.length() - 1).split("\\s+");
2.Start a for loop to iterate through
the words array from index 0 to words.length
- 2:
 Step 2.1: For each index i, check if the
length of the current word (words[i]) is
not equal to the length of the next word
(words[i + 1]) minus one:
 Step 2.1.1: If the condition is true,
return false (indicating it is not a
snowball string).
3.Step 3: If the loop completes without
returning false, return true (indicating it is a
snowball string).
End Check Snowball String Method

Step 4: Display Method (display)


1.Print the sentence stored in sent by
displaying "Sentence: " followed by the value
of sent.

66
2.Call the isSnowball() method:
 Step 2.1: If it returns true, print "IT IS A
SNOWBALL STRING."
 Step 2.2: If it returns false, print "IT IS
NOT A SNOWBALL STRING."
End Display Method

End

67
OUTPUTS

1.

2.

3.

68
SOURCE CODE
//Program to check a sentence is snowball string
import java.util.Scanner;
class SnowBall
{
private String sent="";
private void input()//to take sentence from user
{
char l;
do{
System.out.print("INPUT: ");
sent=new Scanner(System.in).nextLine();
l=sent.charAt(sent.length()-1);
if(!(l=='.' || l=='?'))
System.out.println("Sentence not terminated by '?'
or '.' Re-enter.");
}while(!(l=='.' || l=='?'));//check that sentence is
properly terminated
}
private boolean isSnowball()//to compute string is
snowball or not
{
String words[]=sent.substring(0,sent.length()-
1).split("\\s+");//taking words in array
for(int i=0;i<words.length-1;i++)
{
if(words[i].length()!=words[i+1].length()-1)//length
of each word 1 less than next
return false;
}
return true;
}
private void display()//to display snowball or not
{
System.out.println("Sentence: \n"+sent);
if(isSnowball())
System.out.println("IT IS A SNOWBALL STRING.");
else
System.out.println("IT IS NOT A SNOWBALL
STRING.");
}
public static void main(String a[])
{
SnowBall ob = new SnowBall();
ob.input();
ob.display();
69
}
}

LISTINGS
Class Listing
Class
Name Purpose

This class is designed to check if a given


sentence is a "snowball string," where each
subsequent word in the sentence is exactly
one character longer than the previous word.
It includes methods for inputting the
SnowB sentence, validating the snowball string
all condition, and displaying the results.

Method Listing
Method
Prototype Purpose

To take a sentence input from the user


and ensure it is properly terminated with
void input() either a . or ?.

To check if the input sentence is a


snowball string, where each subsequent
boolean word is one character longer than the
isSnowball() previous word.

void To display the original sentence and


display() whether it is a snowball string or not.

The main method to execute the


static void program, create an instance of
main(String the SnowBall class, and call the input
a[]) and display methods.

70
Variable Listing
Variabl
e Data
Name Type Scope Purpose

To store the input


Strin sentence from the
sent g Instance user.

To store the last


character of the
Local input sentence for
l char to input() method validation.

To store the array


Local of words obtained
Strin to isSnowball() meth by splitting the
words g[] od input sentence.

Local Loop index used to


to isSnowball() meth iterate through
i int od (within for loop) the words array.

71
ASSIGNMENT 11
Program Description
Q11. Write a program to accept a sentence which may
be terminated by either ‘.’ , ‘?’ or ‘!’ only.
The words may be separated by at least one blank
spaces and are in UPPER CASE.
Perform the following tasks:
(a) Count number of vowels and consonants present in
each word
(b) Generate the output of the frequency in form of a
bar graph, where V denotes vowels and C consonants.

Algorithm for Counting Vowels and


Consonants of Each Word
Start
Step 1: Main Method (main)
1. Create an instance of the CountVowCons class
named ob.
2. Call the input() method on the instance ob to
gather input from the user.
3. Call the count_and_display() method on the
instance ob to count and display the vowels and
consonants for each word.
End Main Method

Step 2: Input Method (input)


1. Declare a character variable l.
2. Start a do-while loop:
 Step 2.1: Print "INPUT: " to prompt the user for
input.
 Step 2.2: Read the input sentence
using Scanner, trim any leading or trailing
whitespace, and store it in the variable sent.
 Step 2.3: Get the last character of the sentence
and assign it to l:
 l = sent.charAt(sent.length() - 1);
 Step 2.4: Check if l is not equal to ., ?, or !:
 Step 2.4.1: If true, print "Sentence not
terminated. Re-enter."
3. Step 3: Repeat the loop until l is either ., ?, or !.
4. Step 4: Convert the entire sentence to uppercase
using sent = sent.toUpperCase();.
72
End Input Method

Step 3: Count and Display Method (count_and_display)


1. Create a StringTokenizer object st to tokenize the
sentence sent using delimiters: space, ?, ., and !.
2. Print "OUTPUT: " and "WORD\tCOUNT" to display the
header.
3. Start a while loop to iterate through the tokens
in st:
 Step 3.1: For each token (word), initialize two
integer variables v and c to 0 (to count vowels
and consonants, respectively).
 Step 3.2: Start a for loop to iterate through
each character in the word:
 Step 3.2.1: Check if the character is a
letter using Character.isLetter().
 Step 3.2.2: If the character is a vowel
(check if it exists in "AEIOU"):
 Increment v by 1.
 Step 3.2.3: If the character is a consonant:
 Increment c by 1.
 Step 3.3: Print the word followed by a tab
character.
 Step 3.4: Start a for loop to print v number of
"V" characters (indicating the count of vowels).
 Step 3.5: Print a newline character.
 Step 3.6: Start a for loop to print c number of
"C" characters (indicating the count of
consonants).
 Step 3.7: Print a newline character.
End Count and Display Method

End

73
OUTPUTS

1.

2.

74
SOURCE CODE
//Program to count Vowels and Consonants of each word
import java.util.Scanner;
import java.util.StringTokenizer;
class CountVowCons
{
private String sent="";
private void input()//to take sentence from user
{
char l;
do{
System.out.print("INPUT: ");
sent=new Scanner(System.in).nextLine().trim();
l=sent.charAt(sent.length()-1);
if(!(l=='.' || l=='?' || l=='!'))
System.out.println("Sentence not terminated. Re-enter.");
}while(!(l=='.' || l=='?' || l=='!'));//check that sentence is properly
terminated
sent=sent.toUpperCase();
}
private void count_and_display()
{
StringTokenizer st=new StringTokenizer(sent," ?.!");
System.out.println("OUTPUT: ");
System.out.println("WORD\tCOUNT");
while(st.hasMoreTokens())
{
String word=st.nextToken();
int v=0,c=0;
for(int i=0;i<word.length();i++)
{
if(Character.isLetter(word.charAt(i)))//checking if the
character of word is letter
{
if("AEIOU".indexOf(word.charAt(i))>=0)//if vowel
v++;
else //consonant
c++;
}
}
System.out.print(word+"\t");
for(int t=1;t<=v;t++)//displaying vowel frequency
System.out.print("V");
System.out.print("\n \t");
for(int t=1;t<=c;t++)//displaying consonant frequency
System.out.print("C");
System.out.println();
}
}
public static void main(String a[])
{
CountVowCons ob =new CountVowCons();
ob.input();
ob.count_and_display();
}
}

75
LISTINGS
Class Listing
Class Name Purpose

This class is designed to count the number


of vowels and consonants in each word of
a user-provided sentence. It includes
methods for inputting the sentence,
CountVowC counting vowels and consonants, and
ons displaying the results.

Method Listing
Method
Prototype Purpose

To take a sentence input from the


user and ensure it is properly
void input() terminated with either a ., ?, or !.

void To count the vowels and consonants


count_and_displ in each word of the sentence and
ay() display the results.

The main method to execute the


program, create an instance of
static void the CountVowCons class, and call the
main(String a[]) input and count/display methods.

Variable Listing
Variab
le
Name Data Type Scope Purpose

sent String Instance To store the input


sentence from

76
Variab
le
Name Data Type Scope Purpose

the user.

To store the last


character of the
input sentence
l char Local to input() for validation.

To tokenize the
input sentence
into individual
Local words using
StringToke to count_and_disp specified
st nizer lay() delimiters.

To store the
current word
being processed
Local from the
to count_and_disp tokenized
word String lay() sentence.

To count the
Local number of vowels
to count_and_disp in the current
v int lay() word.

To count the
Local number of
to count_and_disp consonants in the
c int lay() current word.

Loop index used


to iterate
Local through the
to count_and_disp characters of the
i int lay() current word.

77
Variab
le
Name Data Type Scope Purpose

Loop index used


to display the
Local frequency of
to count_and_disp vowels and
t int lay() consonants.

78
ASSIGNMENT 12
Program Description
Q12. An integer number whose digits are arranged in
ascending order from left to right is called an Increasing
Number. At any position, the current digit is always
greater than or equal to the previous digit. For example,
1233, 13689, 112334566, etc.

An integer number whose digits are arranged in


descending order from left to right is called a
Decreasing Number. Here the current digit is always less
than or equal to the previous digit. For example, 321,
88531, 8755321, etc.

A positive integer where the digits are neither in


increasing nor decreasing order is called a Bouncy
number. In other words, if the digits of the number are
unsorted then it is bouncy. For example, 123742, 101,
43682, etc.

Design a program to accept a number (containing only


digits 0 to 9) from the user. For an invalid input, display
an appropriate message. Check whether the number is
an increasing, decreasing or a bouncy number and
display with an appropriate message

Algorithm for Checking Number Type (Increasing,


Decreasing, or Bouncy)
Start
Step 1: Main Method (main)
1. Create an instance of the Number class named ob.
2. Call the input() method on the instance ob to
gather input from the user.
3. Call the display() method on the instance ob to
determine and display the type of the number.
End Main Method

Step 2: Input Method (input)


1. Create a Scanner object named sc to read user
input.
2. Start a do-while loop:

79
 Step 2.1: Print "INPUT: Enter a number: " to
prompt the user for input.
 Step 2.2: Read the input number
using sc.nextInt() and store it in the
variable num.
3. Step 3: Repeat the loop until num is greater than or
equal to 0 (i.e., the user enters a non-negative
number).
End Input Method

Step 3: Check Increasing Method (isIncreasing)


1. Initialize an integer variable n with the value
of num.
2. Start a while loop that continues as long as n is
greater than 9:
 Step 2.1: Get the last digit of n using d = n %
10.
 Step 2.2: Remove the last digit
from n using n /= 10.
 Step 2.3: Check if the last digit d is less than
the new last digit of n:
 Step 2.3.1: If true, return false (indicating
the number is not increasing).
3. Step 4: If the loop completes without
returning false, return true (indicating the number
is increasing).
End Check Increasing Method

Step 4: Check Decreasing Method (isDecreasing)


1. Initialize an integer variable n with the value
of num.
2. Start a while loop that continues as long as n is
greater than 9:
 Step 2.1: Get the last digit of n using d = n %
10.
 Step 2.2: Remove the last digit
from n using n /= 10.
 Step 2.3: Check if the last digit d is greater
than the new last digit of n:
 Step 2.3.1: If true, return false (indicating
the number is not decreasing).
3. Step 4: If the loop completes without
returning false, return true (indicating the number
is decreasing).
End Check Decreasing Method
80
Step 5: Display Method (display)
1. Print "OUTPUT: " to indicate the result will follow.
2. Check if num is less than 10:
 Step 2.1: If true, print "CANNOT BE
DETERMINED." and return.
3. Call the isIncreasing() method:
 Step 3.1: If it returns true, print "num IS AN
INCREASING NUMBER."
4. Call the isDecreasing() method:
 Step 4.1: If it returns true, print "num IS A
DECREASING NUMBER."
5. If neither method returns true, print "num IS A
BOUNCY NUMBER."
End Display Method

End

81
OUTPUTS

1.

2.

3.

82
SOURCE CODE
//Program to check number is increasing, decreasing or bouncy
import java.util.Scanner;
class Number
{
private int num;
private void input()//to take number from user
{
Scanner sc = new Scanner(System.in);
do{
System.out.print("INPUT: Enter a number: ");
num=sc.nextInt();
}while(num<0);
}
private boolean isIncreasing()
{
int n=num;
while(n>9)
{
int d=n%10;//taking last digit
n/=10;//deleting last digit
if(d<n%10)
return false;
}
return true;
}
private boolean isDecreasing()
{
int n=num;
while(n>9)
{
int d=n%10;//taking last digit
n/=10;//deleting last digit
if(d>n%10)
return false;
}
return true;
}
private void display()//to print the kind of number
{
System.out.print("OUTPUT: ");
if(num<10)
{
System.out.println("CANNOT BE DETERMINED.");
return;
}
if(isIncreasing())
System.out.println(num+" IS AN INCREASING NUMBER.");
else if(isDecreasing())
System.out.println(num+" IS A DECREASING NUMBER.");
else
System.out.println(num+" IS A BOUNCY NUMBER.");
}
public static void main(String a[])
{
Number ob = new Number();
ob.input();
ob.display();
}
}

83
LISTINGS
Class Listing
Class
Name Purpose

This class is designed to determine whether a


given number is increasing, decreasing, or
bouncy. It includes methods for inputting the
Numb number, checking its type, and displaying the
er result.

Method Listing
Method
Prototype Purpose

To take a non-negative integer input


void input() from the user.

boolean To check if the digits of the number are


isIncreasing() in increasing order.

boolean
isDecreasing( To check if the digits of the number are
) in decreasing order.

To display the type of the number


void display() (increasing, decreasing, or bouncy).

The main method to execute the


static void program, create an instance of
main(String[] the Number class, and call the input and
a) display methods.

84
Variable Listing
Variabl
e Data
Name Type Scope Purpose

To store the input number


num int Instance from the user.

Local To hold a copy of num for


to isIncreasin processing in
n int g() the isIncreasing() method.

Local To hold a copy of num for


to isDecreasi processing in
n int ng() the isDecreasing() method.

Local To store the last digit


to isIncreasin of n during the checks
d int g() in isIncreasing().

Local To store the last digit


to isDecreasi of n during the checks
d int ng() in isDecreasing().

Parameter for
the main method, used to
Strin Local accept command-line
a g[] to main() arguments.

85
ASSIGNMENT 13
Program Description
Q13. Write a program to accept a paragraph
containing two sentences only. The sentences
may be terminated by either ‘.’ , ‘?’ or ‘!’ only.
Any other character may be ignored. The words
are to be separated by a single blank space and
are in UPPER CASE.
Perform the following tasks:
(a) Accept the paragraph and check for validity
(b) Obtain the length/size of the two sentences
separately
(number of words)
(c) Find the common words which occur in both
the sentences

Algorithm for Finding Common Words in Two


Sentences

Start
Step 1: Main Method (main)
1. Create an instance of the Common class named ob.
2. Call the input() method on the instance ob to gather
input from the user.
3. Call the display() method on the instance ob to
process and display the results.
End Main Method

Step 2: Input Method (input)


1. Start a do-while loop:
 Step 2.1: Print "INPUT: " to prompt the user for
input.
 Step 2.2: Read the input paragraph
using Scanner, trim any leading or trailing
whitespace, and store it in the variable para.
 Step 2.3: Call the check() method to validate the
input.
 Step 2.4: If the input is invalid, print "INVALID.
Re-enter."
2. Step 3: After a valid input is received:
 Step 3.1: Replace multiple spaces with a single
space in para.
86
 Step 3.2: Convert the entire paragraph to
uppercase.
End Input Method

Step 3: Check Method (check)


1. Initialize an integer variable punc to 0 (to count
sentence terminators).
2. Start a for loop to iterate through each character
in para:
 Step 2.1: Get the current character ch.
 Step 2.2: If ch is a sentence terminator (., ?, !),
increment punc by 1.
 Step 2.3: Check if the last character is not a
terminator:
 If true, return false.
 Step 2.4: Check if the first character is a
terminator:
 If true, return false.
3. Step 4: After the loop, check if punc is equal to 2:
 If true, return true (indicating valid input).
 Else, return false.
End Check Method

Step 4: Display Method (display)


1. Declare two string variables sen1 and sen2 to store
the two sentences.
2. Initialize an integer variable i to store the index of
the terminator of the first sentence.
3. Start a for loop to find the index of the first sentence
terminator:
 Step 2.1: If the current character is a terminator,
break the loop.
4. Step 3: Extract the first sentence
from para using substring(0, i) and trim it.
5. Step 4: Extract the second sentence
from para using substring(i + 1, para.length() - 1) and
trim it.
6. Step 5: Print the number of words in both sentences
using split(" ").length.
7. Step 6: Print "COMMON WORDS: " and call
the dispCommon() method, passing the arrays of
words from both sentences.
End Display Method

Step 5: Display Common Words Method (dispCommon)


1. Start an outer loop to iterate through each word in
the first sentence array s1:
87
 Step 2.1: Check if the word has already been
printed:
 If true, continue to the next iteration.
2.

Start an inner loop to iterate through each word in the


second sentence array s2:
 Step 3.1: If the current word from s1 matches a
word in s2:
 Check if the word has already been printed
from s2:
 If true, continue to the next iteration.
 Print the common word.
End Display Common Words Method

End

OUTPUTS

1.

88
2.

SOURCE CODE
//Program to find common words in both sentences
import java.util.Scanner;
class Common
{
private String para="";
private void input()//to take paragraph from user
{
do{
System.out.print("INPUT: ");
para=new Scanner(System.in).nextLine().trim();
if(!check())
System.out.println("INVALID. Re-enter.");
}while(!check());//validity check
para=para.replaceAll("\\s+"," ");//ensuring single space between words
para=para.toUpperCase();//ensuring words are in uppercase
}
private boolean check()
{
int punc=0;//stores no. of sentence terminators
for(int i=0;i<para.length();i++)
{
char ch=para.charAt(i);
if(ch=='.'||ch=='?'||ch=='!')
punc++;
if(i==para.length()-1 && !(ch=='.'||ch=='?'||ch=='!'))//if last character is not terminator
return false;

89
if(i==0 && (ch=='.'||ch=='?'||ch=='!'))//if first character is terminator
return false;
}
if(punc==2)//no. of terminators is equal to no. of sentences
return true;
else
return false;
}
private void display()//to display no. of words in two sentences and common words
{
String sen1="",sen2=""; //stores 2 sentences separately
int i;//to store index of terminator of first sentence;
for(i=0;i<para.length();i++)
{
char ch=para.charAt(i);
if(ch=='.'||ch=='?'||ch=='!')
break;
}
sen1=para.substring(0,i).trim();
sen2=para.substring(i+1,para.length()-1).trim();
System.out.println("OUTPUT: SENTENCE 1: "+sen1.split(" ").length+" WORDS");
System.out.println("SENTENCE 2: "+sen2.split(" ").length+" WORDS");
System.out.print("COMMON WORDS: ");
dispCommon(sen1.split(" "),sen2.split(" "));//passing arrays containing words of respective sentences
}
private void dispCommon(String s1[],String s2[])
{
X:for(int i=0;i<s1.length;i++)
{
for(int k=0;k<i;k++)
{
if(s1[i].equals(s1[k]))//checking if word is printed from first array
continue X;
}
for(int j=0;j<s2.length;j++)
{
if(s1[i].equals(s2[j]))//checking if word is common
{
for(int m=0;m<j;m++)//checking if word is printed from 2nd array
{
if(s2[m].equals(s2[j]))
continue X;
}
System.out.print(s1[i]+" ");
}
}
}
}
public static void main(String a[])
{
Common ob = new Common();
ob.input();
ob.display();
}
}

LISTINGS
Class Listing
Class
Name Purpose

This class is designed to find common words between


two sentences provided by the user. It includes methods
Commo for inputting the sentences, validating the input, and
n displaying the results.

Method Listing

90
Method Prototype Purpose

To take a paragraph input from the user


and ensure it contains exactly two
void input() sentences.

To validate the input paragraph for correct


boolean check() sentence structure and punctuation.

To display the number of words in each


sentence and the common words between
void display() them.

void
dispCommon(String To find and display the common words
s1[], String s2[]) between two arrays of words.

The main method to execute the program,


static void create an instance of the Common class,
main(String a[]) and call the input and display methods.

Variable Listing
Variabl Data
e Name Type Scope Purpose

To store the input


paragraph from the
para String Instance user.

To count the number


of sentence
terminators in the
punc int Local to check() method paragraph.

To store the index of


the terminator of the
i int Local to display() method first sentence.

To store the first


sentence extracted
sen1 String Local to display() method from the paragraph.

To store the second


sentence extracted
sen2 String Local to display() method from the paragraph.

91
Variabl Data
e Name Type Scope Purpose

To store the current


Local character being
to check() and display() met processed in the
ch char hods loops.

To store the array of


String Local words from the first
s1 [] to dispCommon() method sentence.

To store the array of


String Local words from the
s2 [] to dispCommon() method second sentence.

Loop index used to


Local iterate through the
to dispCommon() method second sentence's
j int (within inner loop) words.

Loop index used to


Local check for duplicates
to dispCommon() method in the first sentence's
k int (within inner loop) words.

Loop index used to


Local check for duplicates
to dispCommon() method in the second
m int (within inner loop) sentence's words.

ASSIGNMENT 14
Program Description
Q14. A class Collection contains an array of n integers.
Using the following class description create an array with
common elements from two integer arrays. The final array
92
must contain unique elements. Some of the members of
the class are given below:

Class name : Collection

Data members
arr[] : integer array
len : length of the array

Member functions
a. Collection() : default constructor
b. Collection(int) : parameterized constructor to assign the
length of the array.
c. void inparr() : to accept the array elements.
d. Collection common(Collection) : returns a Collection
containing the common elements of current Collection object
and the Collection object passed as a parameter.
e. void arrange() : sort the array elements of the object
containing common
elements in ascending order using any sorting technique
(Bubble or Exchange selection sort).
f. void display() : displays the array elements.
Algorithm for Finding Common
Elements in Two Integer Arrays
Start
Step 1: Main Method (main)
1. Create a Scanner object named sc to read user input.
2. Declare an integer variable l to store the length of the arrays.
3. For the first array:
 Start a do-while loop to prompt the user for the length of
the first array.
 Read the length using sc.nextInt().
 If the length is negative, print "INVALID SIZE. Re-
enter."
4. Create an instance of Collection named x with the specified
length and call the inparr() method to input the elements.
5. For the second array:
 Repeat steps 3.1 to 3.3 to get the length of the second
array.
6. Create an instance of Collection named y with the specified
length and call the inparr() method to input the elements.
7. Print "First Array: " and call the display() method on x to show
the first array.
8. Print "Second Array: " and call the display() method on y to
show the second array.
9. Create a new Collection object z by calling
the common() method on y, passing x as an argument.
10. Call the arrange() method on z to sort the common elements in
ascending order.
93
11.Print "Final Array with common elements: " and call
the display() method on z to show the common elements.
End Main Method

Step 2: Collection Class Constructor


1. Default Constructor:
 Initialize len to 0.
 Create an empty integer array arr of length 0.
2. Parameterized Constructor:
 Assign the provided length n to len.
 Create an integer array arr of length n.
End Collection Class Constructor

Step 3: Input Array Method (inparr)


1. Create a Scanner object named sc.
2. Start a for loop to iterate from 0 to len - 1:
 Prompt the user to enter an integer.
 Read the integer and store it in the arr array.
End Input Array Method

Step 4: Common Elements Method (common)


1. Initialize an integer variable l to 0 (to count common
elements).
2. Start a labeled outer loop X to iterate through each element in
the array a:
 Start an inner loop to check for duplicates in a:
 If a duplicate is found, continue to the next iteration
of X.
 Start another inner loop to check if the current element is
common in this.arr:
 If a common element is found, check for duplicates
in this.arr.
 If no duplicates are found, increment l.
3. Create a new Collection object ob with length l.
4. Reset l to 0.
5. Repeat the process to store common elements in ob.arr:
 Use the same logic as before to check for duplicates and
store common elements.
6. Return the Collection object ob containing the common
elements.
End Common Elements Method

Step 5: Arrange Method (arrange)


1. Start a for loop to iterate through the array for sorting:
 Initialize min to the current index i.
 Start an inner loop to find the index of the smallest
element:
 If a smaller element is found, update min.
 Swap the current element with the smallest element
found.
End Arrange Method

Step 6: Display Method (display)


1. Start a for loop to iterate through the array arr:

94
 For each index i, print the element arr[i] followed by a
comma and a space.
2. After the loop, print a newline character to move to the next
line.
End Display Method

End

OUTPUTS

1.

95
96
SOURCE CODE
//Program to create an array with common elements from two integer arrays
import java.util.Scanner;
class Collection
{
private int arr[];
private int len;
private Collection()//default constructor
{
len=0;
arr=new int[len];
}
private Collection(int n)//parameterized constructor to assign the length of the array.
{
len=n;
arr=new int[len];
}
private void inparr()//to accept the array elements
{
Scanner sc =new Scanner(System.in);
for(int i=0;i<len;i++)
{
System.out.print("Enter integer: ");
arr[i]=sc.nextInt();
}
}
private Collection common(Collection a)
{
int l=0;//to store length of common element array
//calculating length of common element array
X:for(int i=0;i<a.len;i++)
{
for(int k=0;k<i;k++)
{
if(a.arr[i]==a.arr[k])//checking if integer is counted from first array
continue X;
}
for(int j=0;j<this.len;j++)
{
if(a.arr[i]==this.arr[j])//checking if integer is common
{
for(int m=0;m<j;m++)//checking if integer is counted from 2nd array
{
if(this.arr[m]==this.arr[j])
continue X;
}
l++;
}
}
}
Collection ob = new Collection(l);
//storing common elements in array
l=0;
X:for(int i=0;i<a.len;i++)
{
for(int k=0;k<i;k++)
{
if(a.arr[i]==a.arr[k])//checking if integer is taken from 1st array
continue X;
}
for(int j=0;j<this.len;j++)
{
if(a.arr[i]==this.arr[j])//checking if integer is common
{
for(int m=0;m<j;m++)//checking if integer is taken from 2nd array
{

OUTPUTS
97
2.

98
if(this.arr[m]==this.arr[j])
continue X;
}
ob.arr[l++]=a.arr[i];
}

}
}
return ob;
}
private void arrange()//to sort elements in ascending order
{
for(int i=0;i<len-1;i++)//loop for no. of passes
{
int min=i; //stores index of smallest element among left elements
for(int j=i+1;j<len;j++)
{
if(arr[j]<arr[min])//finding index of smallest element
min=j;
}
int t=arr[i]; //swapping
arr[i]=arr[min];
arr[min]=t;
}
}
private void display()//to print array elements
{
for(int i=0;i<len;i++)
{
System.out.print(arr[i]+", ");
}
System.out.println();
}
public static void main(String a[])
{
Scanner sc = new Scanner(System.in);
//for 1st array
int l;
do{
System.out.print("Enter length of first array: ");
l=sc.nextInt();
if(l<0)
System.out.println("INVALID SIZE. Re-enter.");
}while(l<0);
Collection x=new Collection(l);
x.inparr();
//for 2nd array
do{
System.out.print("Enter length of second array: ");
l=sc.nextInt();
if(l<0)
System.out.println("INVALID SIZE. Re-enter.");
}while(l<0);
Collection y=new Collection(l);
y.inparr();

System.out.println("First Array: ");


x.display();
System.out.println("Second Array: ");
y.display();
Collection z=y.common(x);
z.arrange();
System.out.println("Final Array with common elements: ");
z.display();
}
}

LISTINGS
99
Class Listing
Class
Name Purpose

This class is designed to manage an array of


integers, allowing for input, finding common
Collecti elements between two arrays, sorting, and
on displaying the elements.

Method Listing
Method
Prototype Purpose

Default constructor that initializes


Collection() an empty array.

Parameterized constructor that


initializes an array of a specified
Collection(int n) length.

Accepts input from the user to


void inparr() populate the array.

Finds and returns a


Collection new Collection object containing
common(Collectio common elements from the current
n a) array and the provided array.

Sorts the elements of the array in


void arrange() ascending order.

void display() Prints the elements of the array.

The main method to execute the


program, create instances
static void of Collection, and manage user
main(String a[]) input and output.

100
Variable Listing
Varia
ble Data
Name Type Scope Purpose

To store the
integer
elements of the
arr int[] Instance array.

To store the
length of the
len int Instance array.

To store the
length of the
common
Local elements array
to main() and common() or the length of
l int methods the arrays.

Local To read user


Scanne to inparr() and main() m input from the
sc r ethods console.

Loop indices
used for
i, j, k, Local to various iterating
m int methods through arrays.

To store the
new Collection
object
containing
Collecti Local common
ob on to common() method elements.

min int Local To store the


to arrange() method index of the

101
Varia
ble Data
Name Type Scope Purpose

smallest
element during
sorting.

Temporary
variable used
for swapping
Local elements
t int to arrange() method during sorting.

102
ASSIGNMENT 15
Program Description
Q15. 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:
a. DeciOct(): constructor to initialize the data members n = 0,
oct = 0.
b. void getnum(int nn): assign nn to n
c. void deci_oct(): calculates the octal equivalent of ‘n’ and
stores it in oct using the recursive technique
d. void show(): displays the decimal number ‘n’, calls the
function deci_oct() and displays its octal equivalent.
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.

Algorithm for Converting Decimal to


Octal
Start
Step 1: Main Method (main)
1. Create a Scanner object named sc to read user input.
2. Declare an integer variable x to store the decimal
number.
3. Start a do-while loop:
 Prompt the user to enter a decimal number.
 Read the input using sc.nextInt().
 If the input is negative, repeat the prompt.
4. Create an instance of the DeciOct class named ob.
5. Call the getnum(int nn) method on ob, passing x as
an argument to set the decimal number.
6. Call the show() method on ob to display the octal
equivalent.
End Main Method

Step 2: DeciOct Class Constructor


1. Default Constructor:
103
 Initialize n and oct to 0.
End DeciOct Class Constructor

Step 3: Get Number Method (getnum)


1. Set the instance variable n to the value of the
parameter nn.
End Get Number Method

Step 4: Decimal to Octal Conversion Method (deci_oct)


1. Check if n is greater than 0:
 If true:
 Calculate the octal digit d as n % 8.
 Divide n by 8 (i.e., n /= 8).
 Recursively call deci_oct() to continue the
conversion.
 Update oct by multiplying it by 10 and
adding the digit d (i.e., oct = oct * 10 + d).
End Decimal to Octal Conversion Method

Step 5: Show Method (show)


1. Print the original decimal number n.
2. Call the deci_oct() method to perform the conversion.
3. Print the equivalent octal number stored in oct.
End Show Method

End

104
OUTPUTS

1.

2.

105
106
SOURCE CODE
//Program to convert a decimal number into its equivalent
octal number
import java.util.Scanner;
class DeciOct
{
int n,oct;
private DeciOct()//default constructor
{
n=oct=0;
}
private void getnum(int nn)
{
n=nn;
}
private void deci_oct()//to calculate the octa equivalent
{
if(n>0)//when number can be divided
{
int d=n%8;//taking octal digit
n/=8; //diving by 8;
deci_oct();
oct=oct*10+d;//adding digits in reverse order
}
}
private void show()//display octal equivalent
{
System.out.println("Decimal Number: "+n);
deci_oct();
System.out.println("Equivalent Octal Number: "+oct);
}
public static void main(String a[])
{
DeciOct ob = new DeciOct();
Scanner sc = new Scanner(System.in);
int x;
do{
System.out.print("Enter a decimal number: ");
x=sc.nextInt();
}while(x<0);
ob.getnum(x);
ob.show();
}
}

107
LISTINGS
Class Listing
Class
Name Purpose

This class is designed to convert a decimal


number into its equivalent octal number. It
includes methods for inputting the number,
DeciOc performing the conversion, and displaying the
t result.

Method Listing
Method
Prototype Purpose

Default constructor that initializes the


DeciOct() decimal number and octal number to 0.

void
getnum(int Sets the decimal number n to the value
nn) provided as an argument.

void Recursively calculates the octal


deci_oct() equivalent of the decimal number.

Displays the original decimal number


void show() and its equivalent octal number.

static void The main method to execute the


main(String program, create an instance of DeciOct,
a[]) and manage user input and output.

Variable Listing

108
Variabl
e Data
Name Type Scope Purpose

To store the decimal


number input by the
n int Instance user.

To store the equivalent


octal number during
oct int Instance conversion.

Local To temporarily store


to main() metho the user input for the
x int d decimal number.

Local
Scann to main() metho To read user input from
sc er d the console.

Local To hold the decimal


to getnum(int number passed to
nn int nn) the getnum method.

Local To store the current


to deci_oct() me octal digit during the
d int thod conversion process.

Instance of
Local the DeciOct class used
DeciO to main() metho to access its methods
ob ct d and variables.

109
ASSIGNMENT 16
Program Description
Q16. Write a program that will take a 2D array from the
user having m rows and n columns where (2<=m,n<=10).
Accept positive integers in the array where each of the
number have atleast 3 digits. For each of the element in
the array replace with another number by replacing prime
digit(s) in that number with next prime number in the
natural number series. Finally display original array and
updated array. If the elements in the array doesn`t have
any prime
digits the number will remain unchanged.
Example:
Input: m=2, n=3
231 145 437
646 764 3456
Output:
Updated array:
351 147 4511
646 1164 5476

Algorithm for Replacing Prime


Digits with Next Prime Digits
Start
Step 1: Main Method (main)
1. Create an instance of the ReplacePrime class
named ob.
2. Call the acceptSize() method on ob to accept the size
of the 2D array.
3. Call the acceptElements() method on ob to accept the
elements of the array.
4. Print "ORIGINAL" and call the display() method
on ob to show the original array.
5. Call the replace() method on ob to replace prime
digits with the next prime digits.
6. Print "UPDATED" and call the display() method
on ob to show the updated array.
End Main Method

Step 2: Accept Size Method (acceptSize)


1. Create a Scanner object named sc to read user input.
2. Declare integer variables m and n for the number of
rows and columns.

110
3. Print "Input: " and start a do-while loop:
 Prompt the user to enter the number of rows m.
 Prompt the user to enter the number of
columns n.
 Repeat until m is at least 2 and n is between 1
and 10 (inclusive).
4. Initialize the 2D array a with dimensions m by n.
End Accept Size Method

Step 3: Accept Elements Method (acceptElements)


1. Create a Scanner object named sc to read user input.
2. Start a nested for loop to iterate through each
element of the 2D array a:
 Prompt the user to enter a three-digit positive
integer.
 Check if the number of digits in the entered
integer is less than 3:
 If true, print "INVALID input. Re-enter." and
decrement the column index j to repeat the
input for that position.
End Accept Elements Method

Step 4: Replace Method (replace)


1. Start a nested for loop to access each element of the
2D array a:
 Convert the current integer to a string n.
 Replace the prime digits with the next prime
digits using String.replaceAll():
 Replace '7' with '11'
 Replace '5' with '7'
 Replace '3' with '5'
 Replace '2' with '3'
 Convert the updated string back to an integer
and update the corresponding element in the
array.
End Replace Method

Step 5: Display Method (display)


1. Print "ARRAY: " to indicate the start of the array
display.
2. Start a nested for loop to iterate through each
element of the 2D array a:
 Print each element followed by a tab character.
 After each row, print a newline character to
move to the next line.
End Display Method

111
End

112
OUTPUTS

1.

2.

113
SOURCE CODE
//Program to replace prime digits with next prime digits
import java.util.Scanner;
class ReplacePrime
{
private int a[][];
private void acceptSize()//to accept size of 2D array
{
Scanner sc =new Scanner(System.in);
int m,n;
System.out.println("Input: ");
do{
System.out.print("No. of rows m= ");
m=sc.nextInt();
System.out.print("No. of columns n= ");
n=sc.nextInt();
}while(m<2 || n>10 || n<=0);//checking given pre requisites
a=new int[m][n];//initialsing array
}
private void acceptElements()//to accept 3 digit positive integers
{
Scanner sc = new Scanner(System.in);
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print("Enter element: ");
a[i][j]=sc.nextInt();
if((int)Math.log10(a[i][j])+1 <3)//checking no. of digits of positive
{
System.out.println("INVALID input. Re-enter.");
j--;
}
}
}
}
private void replace()//to replace numbers in array
{
//to access each element
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
String n=""+a[i][j];//taking number as string
//replacing prime digits with next prime numbers.
n=n.replaceAll("7","11");
n=n.replaceAll("5","7");
n=n.replaceAll("3","5");
n=n.replaceAll("2","3");
a[i][j]=Integer.parseInt(n);//updating the number in array
}
}
}
private void display()//to print the array in matrix form
{
System.out.println("ARRAY: ");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();//taking cursor to next line
}
}
public static void main(String a[])
{
ReplacePrime ob =new ReplacePrime();
ob.acceptSize();
ob.acceptElements();
System.out.print("ORIGINAL ");
ob.display();
ob.replace();
System.out.print("UPDATED ");
ob.display();
}
}

114
LISTINGS
Class Listing
Class
Name Purpose

This class is designed to manage a 2D array


of integers, allowing for input, replacing
ReplacePr prime digits with the next prime digits, and
ime displaying the array.

Method Listing
Method
Prototype Purpose

Default constructor that initializes the


ReplacePrime() 2D array.

void Accepts the size of the 2D array from


acceptSize() the user.

void
acceptElement Accepts three-digit positive integers
s() to fill the 2D array.

Replaces prime digits in the array with


void replace() the next prime digits.

Displays the elements of the 2D array


void display() in matrix form.

The main method to execute the


static void program, create an instance
main(String of ReplacePrime, and manage user
a[]) input and output.

Variable Listing

115
Variab
le
Name Data Type Scope Purpose

A 2D array to store
the integers input
a int[][] Instance by the user.

To store the
number of rows for
m int Local to acceptSize() method the 2D array.

To store the
number of columns
n int Local to acceptSize() method for the 2D array.

Local
to acceptElements() and replace() Loop index for rows
i int methods in the 2D array.

Local Loop index for


to acceptElements() and replace() columns in the 2D
j int methods array.

Local
to acceptSize() and acceptElement To read user input
sc Scanner s() methods from the console.

To hold the string


representation of
the current integer
for digit
n String Local to replace() method replacement.

Instance of
the ReplacePrime cl
ass used to access
ReplacePr its methods and
ob ime Local to main() method variables.

116
ASSIGNMENT 17
Program Description
Q17. Write a program which will display all the
palindrome words among N words taken as input.
The words taken as input will be in uppercase.
Display only the palindrome words(words) whose
reverse word is the original word) in lowercase.
Class: PalinCase
Data members:
N: quantity of words
wds[]: array to store N words in uppercase
Methods:
a.Palin(int): parameterized constructor
b.void input(): accept N words and store in the
array
c. String reverse(String p): return reverse of the
string p in recursion logic.
d.String caseConvert(String p): returns the word
where the vowels in the palindrome word p are
only changed to lowercase. (use recursion) [Don`t
use any library method for case convert]
e. void display(): Display only palindrome words
among N words where vowels in the palindrome
word will be in lowercase. Call the required
methods accordingly.
Algorithm for Displaying Palindrome Words with
Vowels in Lowercase
Start
Step 1: Main Method (main)
1. Create a Scanner object named sc to read user input.
2. Declare an integer variable n to store the number of
words.
3. Start a do-while loop:
 Prompt the user to enter the number of words.
 Read the input using sc.nextInt().
 Repeat until n is non-negative.
4. Create an instance of the PalinCase class named ob,
passing n as an argument to the constructor.
5. Call the input() method on ob to accept words from the
user.

117
6. Call the display() method on ob to display the
palindrome words with vowels in lowercase.
End Main Method

Step 2: PalinCase Class Constructor


1. Parameterized Constructor:
 Assign the provided value n to the instance
variable N.
 Initialize the array wds with a size of N to store the
words.
End PalinCase Class Constructor

Step 3: Input Method (input)


1. Create a Scanner object named sc to read user input.
2. Start a for loop to iterate from 0 to N-1:
 Prompt the user to enter a word.
 Read the word and convert it to uppercase, storing
it in the wds array.
End Input Method

Step 4: Reverse Method (reverse)


1. Check if the input string p is empty:
 If true, return the empty string (base case).
2. Return the last character of p concatenated with the
result of calling reverse() on the substring of p that
excludes the last character (recursive case).
End Reverse Method

Step 5: Case Convert Method (caseConvert)


1. Check if the input string p is empty:
 If true, return the empty string.
2. Check if the first character of p is a vowel (i.e., if it is in
"AEIOU"):
 If true, convert the first character to lowercase (by
adding 32 to its ASCII value) and concatenate it
with the result of calling caseConvert() on the
substring of p that excludes the first character.
3. If the first character is not a vowel, concatenate the
first character with the result of
calling caseConvert() on the substring of p that
excludes the first character.
End Case Convert Method

Step 6: Display Method (display)


1. Print "PALINDROME WORDS: " to indicate the start of
the output.
2. Start a for loop to iterate through each word in
the wds array:

118
 Check if the current word is equal to its reverse
(using the reverse() method).
 If true, print the word after converting its vowels
to lowercase (using the caseConvert() method).
End Display Method

End

119
OUTPUTS

1.

2.

120
SOURCE CODE
//Program to display palindrome words with vowels in lowercase
import java.util.Scanner;
class PalinCase
{
private int N;
private String wds[];
private PalinCase(int n)//constructor to initialize data members
{
N=n;
wds=new String[N];
}
private void input()//to accept words from user
{
Scanner sc=new Scanner(System.in);
for(int i=0;i<N;i++)
{
System.out.print("Enter word: ");
wds[i]=sc.next().toUpperCase();
}
}
private String reverse(String p)//returns reverse of parameter string
{
if(p.equals("")) //base case to stop recursion
return p;
//recusive case
//taking and removing last character
return p.charAt(p.length()-1)+reverse(p.substring(0,p.length()-1));
}
private String caseConvert(String p)//returns parameter string with vowels in
lowercase
{
if(p.equals(""))
return p;
else if("AEIOU".indexOf(p.charAt(0))>=0)//cecking if first character is vowel
return (char)(p.charAt(0)+32)+caseConvert(p.substring(1));//converting vowel
to lowercase
else
return p.charAt(0)+caseConvert(p.substring(1));//taking and removing first
charcter
}
private void display()//to display palindrome words
{
System.out.println("PALINDROME WORDS: ");
for(int i=0;i<N;i++)
{
if(wds[i].equals(reverse(wds[i])))
{
System.out.println(caseConvert(wds[i]));
}
}
}
public static void main(String a[])
{
Scanner sc = new Scanner(System.in);
int n;//stores number of words
do{
System.out.print("Enter number of words: ");
n=sc.nextInt();
}while(n<0);//negative check
PalinCase ob = new PalinCase(n);
ob.input();
ob.display();
}
}

121
LISTINGS
Class Listing
Class
Name Purpose

This class is designed to manage a list of


words, allowing for input, checking for
PalinCa palindromes, converting vowels to lowercase,
se and displaying the results.

Method Listing
Method
Prototype Purpose

Constructor that initializes the


number of words and the array to
PalinCase(int n) store them.

Accepts words from the user and


void input() stores them in uppercase.

String
reverse(String Returns the reverse of the input
p) string p.

String
caseConvert(Stri Converts vowels in the input
ng p) string p to lowercase.

Displays the palindrome words with


void display() vowels in lowercase.

The main method to execute the


program, create an instance
static void of PalinCase, and manage user input
main(String a[]) and output.

122
Variable Listing
Varia
ble Data
Name Type Scope Purpose

Stores the
number of
words to be
N int Instance processed.

An array to
store the
String[ words input
wds ] Instance by the user.

Stores the
number of
words input
n int Local to main() method by the user.

Loop index for


Local iterating
to input() and display() meth through the
i int ods words.

Local To read user


Scanne to input() and main() method input from the
sc r s console.

The string to
be reversed or
Parameter processed for
in reverse() and caseConvert vowel
p String () methods conversion.

ob PalinCa Local to main() method Instance of


se the PalinCase
123
Varia
ble Data
Name Type Scope Purpose

class used to
access its
methods and
variables.

124
ASSIGNMENT 18
Program Description
Q18. Write a program that will create a pattern with
Fibonacci numbers in pyramid shape.
Numbers in the pattern i.e Fibonacci numbers must be
generated using recursive technique.
Take number of lines to print as input and display the
Fibonacci pattern.
Example: n=5
Output:
0
11
235
8 13 21 34
55 89 144 233 377

Algorithm for Printing a Pyramid


with Fibonacci Numbers
Start
Step 1: Main Method (main)
1. Create an instance of the patFibo class named ob.
2. Call the input() method on ob to take the number of
lines for the pyramid from the user.
3. Call the print() method on ob to print the pyramid
with Fibonacci numbers.
End Main Method

Step 2: Input Method (input)


1. Create a Scanner object named sc to read user
input.
2. Start a do-while loop:
 Prompt the user to enter the number of lines.
 Read the input using sc.nextInt().
 Repeat until N is a natural number (greater
than 0).
End Input Method

Step 3: Print Method (print)


1. Initialize an integer variable n to 0 to count the
number of Fibonacci terms printed.
2. Start a loop from i = 1 to N (inclusive) to iterate
through each line of the pyramid:
125
 Start a nested loop to print spaces:
 For each line, print N - i spaces to center
the pyramid.
 Start another nested loop from j =
1 to i (inclusive) to print Fibonacci numbers:
 Call the fibo() method with ++n as the
argument to get the next Fibonacci
number and print it.
 Print a newline character to move to the next
line after printing all numbers in the current
line.
End Print Method

Step 4: Fibonacci Method (fibo)


1. Check if x is equal to 1:
 If true, return 0 (the first term of the Fibonacci
series).
2. Check if x is equal to 2:
 If true, return 1 (the second term of the
Fibonacci series).
3. If x is greater than 2, return the sum of the results
of calling fibo(x-1) and fibo(x-2) (the recursive case
to calculate the Fibonacci term).
End Fibonacci Method

End

126
OUTPUTS

1.

2.

SOURCE CODE
//Program to print a pyramid with fibonacci numbers
127
import java.util.Scanner;
class patFibo
{
private int N;
private void input()//to take number of lines from user
{
Scanner sc=new Scanner(System.in);
do{
System.out.print("Enter number of lines: ");
N=sc.nextInt();
}while(N<=0);//number of lines must be a natural number
}
private void print()//to print pyramid with fibonacci numbers
{
int n=0;//to count no. of terms printed
for(int i=1;i<=N;i++)//loop for line number
{
for(int s=1;s<=(N-i);s++)//loop for printing space
{
System.out.print(" ");
}
for(int j=1;j<=i;j++)//loop for printing numbers
{
System.out.print(fibo(++n)+" ");//printing fibonacci
numbers
}
System.out.println();//changing line
}
}
private int fibo(int x)//to return nth fibo term
{
if(x==1)
return 0; //first term of fibonacci series is 0
else if(x==2)
return 1; //second term of fibonacci series is 1
else
return fibo(x-1)+fibo(x-2); //any term of fibonacci is sum of
two preceeding terms
}
public static void main(String a[])
{
patFibo ob = new patFibo();
ob.input();
ob.print();
}
}

LISTINGS
128
Class Listing
Class
Name Purpose

This class is designed to manage the input and


output of a pyramid structure filled with
Fibonacci numbers. It includes methods for
patFib taking user input, printing the pyramid, and
o calculating Fibonacci numbers.

Method Listing
Method
Prototype Purpose

Default constructor that initializes the


patFibo() class.

Accepts the number of lines for the


void input() pyramid from the user.

Prints the pyramid structure with


void print() Fibonacci numbers.

Returns the x-th Fibonacci number using


int fibo(int x) recursion.

static void The main method to execute the


main(String program, create an instance of patFibo,
a[]) and manage user input and output.

Variable Listing
Variabl
e Data
Name Type Scope Purpose

Stores the number of


N int Instance lines for the pyramid.

n int Local Counts the number of


129
Variabl
e Data
Name Type Scope Purpose

to print() meth Fibonacci terms


od printed.

Local Loop index for the


to print() meth current line number in
i int od the pyramid.

Local Loop index for printing


to print() meth spaces before the
s int od Fibonacci numbers.

Local Loop index for printing


to print() meth Fibonacci numbers in
j int od the current line.

Local
Scann to input() meth To read user input from
sc er od the console.

The position in the


Parameter Fibonacci sequence for
in fibo(int which the value is
x int x) method calculated.

Instance of
Local the patFibo class used
patFib to main() meth to access its methods
ob o od and variables.

130
ASSIGNMENT 19
Program Description
Q19. Write a program using byte oriented file handling
concept where your program will maintain student`s
database of class XI Sc. Create a file stud.dat which will
store student`s roll, name, DOB, ICSE average marks,
father` mobile number, mother`s mobile number and
address for N students. Average marks to be taken out
of 100. Write a logic for updation of DOB of a student
where roll number of the student must be considered
for searching and new DOB to be updated to be taken as
input, which will automatically update the DOB of that
student. Display the contents of the file before and after
updation.

Algorithm for Maintaining


Students Database
Start
Step 1: Main Method (main)
1. Create an instance of the Student class named obj.
2. Call the input() method on obj to take student
details and create a file.
3. Print "The file before updation: ".
4. Call the display() method on obj to display the
contents of the file.
5. Call the update() method on obj to update the date
of birth (DOB) of a student.
6. Print "The file after updation: ".
7. Call the display() method on obj to display the
updated contents of the file.
End Main Method

Step 2: Input Method (input)


1. Create a Scanner object named sc to read user
input.
2. Create a FileOutputStream object to create a file
named "stud.dat".
3. Create a DataOutputStream object to write data to
the file.
4. Print "STUDENTS DATABASE OF CLASS XI Sc."
5. Start a do-while loop:

131
 Prompt the user to enter the number of
students.
 Read the input using sc.nextInt().
 Repeat until N is a natural number (greater
than 0).
6. Start a loop from 1 to N to take details of each
student:
 Prompt for and read the roll number, name,
date of birth, ICSE average marks, father's
mobile number, mother's mobile number, and
address.
 Write each detail to the file using
the DataOutputStream.
7. Close
the DataOutputStream and FileOutputStream to
save the file.
End Input Method

Step 3: Display Method (display)


1. Create a FileInputStream object to read from the
file "stud.dat".
2. Create a DataInputStream object to read data from
the file.
3. Start a loop from 1 to N to read and display each
student's details:
 Read and print the roll number, name, date of
birth, ICSE average marks, father's mobile
number, mother's mobile number, and address.
4. Close the DataInputStream and FileInputStream.
End Display Method

Step 4: Update Method (update)


1. Create a Scanner object to read user input.
2. Prompt the user to enter the roll number of the
student whose DOB needs to be updated.
3. Create a FileInputStream object to read from the
file "stud.dat".
4. Create a DataInputStream object to read data from
the file.
5. Create a FileOutputStream object to create a new
file named "stud1.dat".
6. Create a DataOutputStream object to write data to
the new file.
7. Start a loop from 1 to N to read each student's
details:
132
 Read the roll number.
 If the roll number matches the input roll
number:
 Write the roll number and name to the new
file.
 Prompt for and read the new DOB, writing
it to the new file.
 Ignore the old DOB.
 If the roll number does not match:
 Copy the old data (roll number, name, old
DOB, average marks, mobile numbers, and
address) to the new file.
8. Close the DataOutputStream and FileOutputStream.
9. Close the DataInputStream and FileInputStream.
10. Delete the old file "stud.dat".
11. Rename "stud1.dat" to "stud.dat".
End Update Method

End

133
OUTPUTS

1.

134
SOURCE CODE
//Program to maintain students database of class XI Sc
import java.util.Scanner;
import java.io.*;
class Student
{
private int N;
private void input()throws IOException //to create file and take
details of students
{
Scanner sc=new Scanner(System.in);
FileOutputStream fos=new
FileOutputStream("stud.dat");//creating file
DataOutputStream dos=new DataOutputStream(fos);
System.out.println("STUDENTS DATABASE OF CLASS XI Sc. \n");
do{
System.out.print("Enter the number of students-> ");
N=sc.nextInt();
}while(N<=0); //number of students must be a natural no.
//taking details of all students from user
for(int i=1;i<=N;i++)
{
System.out.print("Enter roll no-> ");
dos.writeInt(sc.nextInt());
System.out.print("Enter name-> ");
dos.writeUTF(new Scanner(System.in).nextLine());
System.out.print("Enter date of birth -> ");
dos.writeUTF(new Scanner(System.in).next());
float f;
do{
System.out.print("Enter ICSE average marks-> ");
f=sc.nextFloat();
}while(f>100||f<0);
dos.writeFloat(f);
System.out.print("Enter father's mobile number-> ");
dos.writeLong(sc.nextLong());
System.out.print("Enter mother's mobile number-> ");
dos.writeLong(sc.nextLong());
System.out.print("Enter adress-> ");
dos.writeUTF(new Scanner(System.in).nextLine());
}
dos.close(); fos.close();//saving the file
}
private void display()throws IOException//to display the file
{
FileInputStream fis=new FileInputStream("stud.dat");
DataInputStream dis=new DataInputStream(fis);
for(int i=1;i<=N;i++)
{
System.out.println("Roll no. "+dis.readInt());
System.out.println("Name: "+dis.readUTF());
System.out.println("Date of Birth: "+dis.readUTF());
System.out.println("ICSE Average Marks: "+dis.readFloat());
System.out.println("Father's mobile number: "+dis.readLong());
System.out.println("Mother's mobile number: "+dis.readLong());
System.out.println("Address: "+dis.readUTF());

135
OUTPUTS

2.

136
}
fis.close(); dis.close();
}
void update()throws IOException //to update DOB
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the roll number of the student whose
DOB has to be updated-> ");
int roll=sc.nextInt();
FileInputStream fis=new FileInputStream("stud.dat");//to read the
file
DataInputStream dis=new DataInputStream(fis);
FileOutputStream fos=new
FileOutputStream("stud1.dat");//creating another file
DataOutputStream dos=new DataOutputStream(fos);
for(int i=1;i<=N;i++)//copying all data to other file with new DOB
{
int r= dis.readInt();
if(roll==r)//checking roll number matching or not
{
dos.writeInt(r);
dos.writeUTF(dis.readUTF());
System.out.print("Enter the new DOB -> ");
dos.writeUTF(new Scanner(System.in).nextLine());//storing
new DOB
dis.readUTF();//ignoring old DOB
}
else //when roll is not matching old data is copied
{
dos.writeInt(r);
dos.writeUTF(dis.readUTF());
dos.writeUTF(dis.readUTF());
}
dos.writeFloat(dis.readFloat());
dos.writeLong(dis.readLong());
dos.writeLong(dis.readLong());
dos.writeUTF(dis.readUTF());
}
dos.close(); fos.close(); //saving new file
dis.close(); fis.close();
File s=new File("stud.dat");
File s1=new File("stud1.dat");
s.delete(); //deleting old file
s1.renameTo(s); //renaming new file with old file's name

}
public static void main(String a[])throws IOException
{
Student obj=new Student();
obj.input();
System.out.println("The file before updation: ");
obj.display();
obj.update();
System.out.println("The file after updation: ");
obj.display();
}
137
}

LISTINGS
Class Listing
Class
Name Purpose

This class manages a student database, allowing for input,


Studen display, and updating of student details. It handles file
t operations to store and retrieve student information.

Method Listing
Method Prototype Purpose

Student() Constructor that initializes the class.

void input() throws Creates a file and takes details of students


IOException from the user.

void display() throws Displays the contents of the student


IOException database file.

void update() throws Updates the date of birth (DOB) of a student


IOException based on the roll number.

public static void The main method to execute the program,


main(String a[]) throws create an instance of Student, and manage
IOException user input and output.

Variable Listing
Variab
le
Name Data Type Scope Purpose

Stores the number of


students to be entered
N int Instance into the database.

Local to input(), display(), To read user input from


sc Scanner and update() methods the console.

Local
FileInputStrea to display() and update() m To read data from the
fis m ethods student database file.

138
Variab
le
Name Data Type Scope Purpose

Local
DataInputStre to display() and update() m To read data from
dis am ethods the FileInputStream.

Local To create and write to


FileOutputStr to input() and update() met the new student
fos eam hods database file.

Local
DataOutputSt to input() and update() met To write data to
dos ream hods the FileOutputStream.

Stores the roll number


of the student whose
roll int Local to update() method DOB is to be updated.

Temporary variable to
hold the roll number
r int Local to update() method read from the file.

Stores the ICSE average


f float Local to input() method marks input by the user.

Loop index for iterating


Local to input(), display(), through the number of
i int and update() methods students.

Instance of
the Student class used
to access its methods
obj Student Local to main() method and variables.

Represents the old


student database file
s File Local to update() method ("stud.dat").

Represents the new


student database file
s1 File Local to update() method ("stud1.dat").

139
ASSIGNMENT 20
Program Description
Q20. Write a program to create a text file named
words.txt which will store N words. Create another text
file updatewords.txt which will only store the words
which have unique characters.
For example: help is a word with unique character while
hello is a word with duplicate characters.
Algorithm for Storing Words with
Unique Characters
Start
Step 1: Main Method (main)
1. Create an instance of the UniqueWords class
named ob.
2. Call the input() method on ob to take words from
the user and store them in a file.
3. Print "ALL WORDS FROM FILE (words.txt)".
4. Call the display() method on ob with the filename
"words.txt" to display all words.
5. Call the separate() method on ob to filter and store
unique words in another file.
6. Print "WORDS WHICH HAVE UNIQUE CHARACTERS
FROM FILE (updatewords.txt)".
7. Call the display() method on ob with the filename
"updatewords.txt" to display unique words.
End Main Method

Step 2: Input Method (input)


1. Create a Scanner object named sc to read user
input.
2. Start a do-while loop:
 Prompt the user to enter the number of words.
 Read the input using sc.nextInt().
 Repeat until N is a natural number (greater
than 0).
3. Create a FileWriter object to create a file named
"words.txt".
4. Create a BufferedWriter object to write to the file.
5. Create a PrintWriter object to facilitate writing to
the file.

140
6. Start a loop from 1 to N to take words from the
user:
 Prompt for and read each word using sc.next().
 Write each word to the file using pw.println().
7. Close the PrintWriter, BufferedWriter,
and FileWriter to save the file.
End Input Method

Step 3: Separate Method (separate)


1. Create a FileReader object to read from the file
"words.txt".
2. Create a BufferedReader object to read data from
the file.
3. Create a FileWriter object to create a new file
named "updatewords.txt".
4. Create a BufferedWriter object to write to the new
file.
5. Create a PrintWriter object to facilitate writing to
the new file.
6. Start a loop from 1 to N to read each word from
"words.txt":
 Read a word using br.readLine().
 Call the isUnique() method with the word as an
argument to check if it has unique characters.
 If the word is unique, write it to
"updatewords.txt".
7. Close the PrintWriter, BufferedWriter,
and FileWriter to save the new file.
8. Close the BufferedReader and FileReader.
End Separate Method

Step 4: IsUnique Method (isUnique)


1. Convert the input string s to lowercase.
2. Start a loop from 0 to the length of the string:
 Get the character at index i.
 Start another loop from i + 1 to the length of
the string:
 If the character at index j is equal to the
character at index i,
return false (indicating the character is
not unique).
3. If no characters are repeated,
return true (indicating all characters are unique).
End IsUnique Method

141
Step 5: Display Method (display)
1. Create a FileReader object to read from the
specified file.
2. Create a BufferedReader object to read data from
the file.
3. Initialize a string variable t to store each word.
4. Start a loop to read each line from the file until the
end:
 Read a line using br.readLine().
 Print the line.
5. Close the BufferedReader and FileReader.
End Display Method

End

142
OUTPUTS

1.

143
2.

144
SOURCE CODE
//Program to store words which have unique characters
import java.util.Scanner;
import java.io.*;
class UniqueWords
{
private int N;
private void input()throws IOException //to take words from user and store in text file
{
Scanner sc = new Scanner(System.in);
do{
System.out.print("Enter number of words: ");
N=sc.nextInt();
}while(N<=0);//number of words must be a natural no.
FileWriter fw=new FileWriter("words.txt");//creating file
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
for(int i=1;i<=N;i++)
{
System.out.print("Enter a word: ");
pw.println(sc.next());//taking word from user and storing in file
}
pw.close(); bw.close(); fw.close(); //saving the file
}
private void separate()throws Exception //to store unique words in another file
{
FileReader fr=new FileReader("words.txt");//to read the words containing file
BufferedReader br=new BufferedReader(fr);
FileWriter fw=new FileWriter("updatewords.txt");//creating file
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
for(int i=1;i<=N;i++)
{
String w=br.readLine();//taking word from file
if(isUnique(w))
pw.println(w);
}
pw.close(); bw.close(); fw.close(); //saving new file
br.close(); fr.close();
}
private boolean isUnique(String s)//checks word has unique characters or not
{
s=s.toLowerCase();
for(int i=0;i<s.length();i++)//loop for searching for every character
{
char ch=s.charAt(i);//taking each character of word
for(int j=i+1;j<s.length();j++)//searching for the character in remaining part of word
{
if(ch==s.charAt(j))//if character is present again then it is not unique
return false;
}
}
//when no character is repeated
return true;
}
private void display(String filename)throws IOException//to display the specified file
{
FileReader fr=new FileReader(filename);//for reading the specified file
BufferedReader br=new BufferedReader(fr);
String t;//to store words
while((t=br.readLine())!=null)//checking till file ends
{
System.out.println(t);//printing each word
}
br.close(); fr.close();
}
public static void main(String a[])throws Exception
{
UniqueWords ob = new UniqueWords();
ob.input();
System.out.println("ALL WORDS FROM FILE (words.txt) ");
ob.display("words.txt");
ob.separate();
System.out.println("WORDS WHICH HAVE UNIQUE CHARACTERS FROM FILE (updatewords.txt) ");
ob.display("updatewords.txt");
}
}

145
LISTINGS
Class Listing
Class
Name Purpose

This class manages the input of words, checks for


UniqueWo unique characters, and stores the results in files. It
rds handles file operations to read and write words.

Method Listing
Method Prototype Purpose

UniqueWords() Constructor that initializes the class.

void input() throws Takes words from the user and stores
IOException them in a text file.

void separate() Stores words with unique characters in


throws Exception another file.

boolean
isUnique(String s) Checks if a word has unique characters.

void display(String
filename) throws Displays the contents of the specified
IOException file.

The main method to execute the


public static void program, create an instance
main(String a[]) of UniqueWords, and manage user input
throws Exception and output.

Variable Listing
Variab
le
Name Data Type Scope Purpose

N int Instance Stores the


number of words
to be entered by

146
Variab
le
Name Data Type Scope Purpose

the user.

To read user
input from the
sc Scanner Local to input() method console.

To create and
write to the
Local "words.txt" and
to input() and separate() "updatewords.tx
fw FileWriter methods t" files.

To buffer the
Local output for
BufferedWr to input() and separate() writing to the
bw iter methods files.

Local To facilitate
to input() and separate() writing to the
pw PrintWriter methods files.

Local To read from the


fr FileReader to separate() method "words.txt" file.

To read data
from the
Local "words.txt" and
BufferedRe to separate() and display( "updatewords.tx
br ader ) methods t" files.

Parameter The name of the


filena in display(String file to be
me String filename) method displayed.

To store each
word read from
t String Local to display() method the file.

w String Local To store each


to separate() method word read from
"words.txt" for
checking
147
Variab
le
Name Data Type Scope Purpose

uniqueness.

Represents the
word being
checked for
Local to isUnique(String unique
s String s) method characters.

To store each
character of the
word for
Local to isUnique(String uniqueness
ch char s) method checking.

Local Loop index for


to input(), separate(), iterating
and isUnique(String through words
i int s) methods and characters.

Loop index for


checking
Local to isUnique(String character
j int s) method uniqueness.

Instance of
the UniqueWords
class used to
UniqueWor access its
ob ds Local to main() method methods.

148

You might also like