Assignment 1
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,…
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
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.
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).
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).
1. Print the name of the student with the lowest average marks using name.
2. Print the lowest average marks using marks.
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
Method Listing
Metho
d
Name Prototype Purpose
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
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.
14
Step 2: Input Method (input)
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.
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
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
Method Listing
Method
Name Prototype Purpose
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.
32
Variable Listing
Variab
le Data
Name Type Scope Purpose
Local
(in rearrange( Temporary array to store the
x int[] )) rearranged integers.
Local
(in input(), so
rt(),
and rearrange Loop counter used to iterate
i int ()) through the arrays.
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
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
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
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.
Variable Listing
40
Variab
le Data
Name Type Scope Purpose
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.
41
Variab
le Data
Name Type Scope Purpose
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
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
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
49
Variabl Data
e Name Type Scope Purpose
Local
Scann (in acceptWo Used to read user input
sc er rd()) from the console.
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]
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
Method Listing
Method
Name Prototype Purpose
56
Variabl
e Data
Name Type Scope Purpose
octal numbers.
Parameter
(in check(in The octal number being
x int t x)) checked for validity.
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.
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
Method Listing
Method
Name Prototype Purpose
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
63
Variabl
e Data
Name Type Scope Purpose
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.
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
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
Method Listing
Method
Prototype Purpose
70
Variable Listing
Variabl
e Data
Name Type Scope Purpose
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.
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
Method Listing
Method
Prototype Purpose
Variable Listing
Variab
le
Name Data Type Scope Purpose
76
Variab
le
Name Data Type Scope Purpose
the user.
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.
77
Variab
le
Name Data Type Scope Purpose
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.
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
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
Method Listing
Method
Prototype Purpose
boolean
isDecreasing( To check if the digits of the number are
) in decreasing order.
84
Variable Listing
Variabl
e Data
Name Type Scope Purpose
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
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
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
Method Listing
90
Method Prototype Purpose
void
dispCommon(String To find and display the common words
s1[], String s2[]) between two arrays of words.
Variable Listing
Variabl Data
e Name Type Scope Purpose
91
Variabl Data
e Name Type Scope Purpose
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:
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
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();
LISTINGS
99
Class Listing
Class
Name Purpose
Method Listing
Method
Prototype Purpose
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.
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.
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:
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
Method Listing
Method
Prototype Purpose
void
getnum(int Sets the decimal number n to the value
nn) provided as an argument.
Variable Listing
108
Variabl
e Data
Name Type Scope Purpose
Local
Scann to main() metho To read user input from
sc er d the console.
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
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
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
Method Listing
Method
Prototype Purpose
void
acceptElement Accepts three-digit positive integers
s() to fill the 2D array.
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
to acceptSize() and acceptElement To read user input
sc Scanner s() methods from the console.
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
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
Method Listing
Method
Prototype Purpose
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.
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.
The string to
be reversed or
Parameter processed for
in reverse() and caseConvert vowel
p String () methods conversion.
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
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
Method Listing
Method
Prototype Purpose
Variable Listing
Variabl
e Data
Name Type Scope Purpose
Local
Scann to input() meth To read user input from
sc er od the console.
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.
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
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
Method Listing
Method Prototype Purpose
Variable Listing
Variab
le
Name Data Type Scope Purpose
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
DataOutputSt to input() and update() met To write data to
dos ream hods the FileOutputStream.
Temporary variable to
hold the roll number
r int Local to update() method read from the file.
Instance of
the Student class used
to access its methods
obj Student Local to main() method and variables.
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
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
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
Method Listing
Method Prototype Purpose
void input() throws Takes words from the user and stores
IOException them in a text 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.
Variable Listing
Variab
le
Name Data Type Scope Purpose
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.
To read data
from the
Local "words.txt" and
BufferedRe to separate() and display( "updatewords.tx
br ader ) methods t" files.
To store each
word read from
t String Local to display() method the file.
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.
Instance of
the UniqueWords
class used to
UniqueWor access its
ob ds Local to main() method methods.
148