Sunteți pe pagina 1din 135

BRINDAVAN PUBLIC SCHOOL

WELLINGTON-COONOOR
COMPUTER SCIENCE
Java on
BlueJ Environment

Practical Record
2014-15

Submitted by

Submitted to
Mrs. Shabeena Begum

BRINDAVAN PUBLIC SCHOOL-COONOOR


Project for the Indian School Certificate (I.S.C)
Examinations
COMPUTER SCIENCE
Name of the Student :

_________________

Roll Number

_________________

Register Number

_________________

Date of Submission

_________________

This is to certify that the project work in Java Programs on


BlueJ Environment is done by ________________ of Class XII for the
academic year 2014-15.

Internal Examiner

External Examiner

Principals Signature

Place : Wellington
Date :

TABLE OF CONTENTS
S.No

Name of the Program

Page
No.

Program to Determine the Prime Palindrome integers

1-4

3
4
5
6
7

Program to check if the given number is a Smith Number or


not
Program to check if the given number is a Kaprekar number or
not
Program to check if the given number is Emrip number or not
Program to check if the given number is Unique Number or
not
Program to Print the Lucky numbers
Program for swapping of two numbers without using any third
variable

5-7

8-10
11-13
14-15
16-18
19-20

Program to find the Day of the Given Date

21-23

Program to calculate the Future Date

24-26

10

Program to find the Difference between Two Dates

27-29

11

Program to convert time in numbers to time in World

30-32

12

Conversion of Decimal to a Hexa-Decimal number

33-34

Sign

13

Conversion of Decimal number to its equivalent binary form

35-36

14

Program to print the Fibonacci Series using Recursion

37-39

15

String Manipulation using Constructors

40-43

16

Program to print the frequency of an alphabet in a String

44-46

17

Program to print the first letter of each word of the sentence


in capital

47-48

18

Program to find the longest and shortest word in a sentence

49-51

19

Program to Translate a Word into a Pig Latin Word

52-53

TABLE OF CONTENTS
S.No

Name of the Program

Page
No.

20

Program to find the difference between two matrices

54-57

21

Program to find the product of two matrices

58-60

22

Program to Print the Denominations of an Input Amount

61-62

23

Program to Check if the ISBN code of the book is valid or not

63-64

24
25

Program to calculate the perimeter of the parallelogram using


Inheritance
Program to print the mark list for 50 students using Inheritance

Internal Examiner

Sign

65-68
69-72

External Examiner

Place : Wellington
Date :

Prime-Palindrome Integers

Question 1 :
A Prime palindrome integer is a positive integer (without
leading zeros)
which is prime as well as a palindrome. Given two positive integers m
and n,
where m<n, write a program to determine how many primepalindrome
integers are there in the range between m and n (both inclusive) and
output
them. The input contains two positive integers m and n where
m<3000 and
n<3000. Display the number of prime-palindrome integers in the
specified
range along with their values.
Aim :
To determine the prime palindrome integers within a given range
of
interval.

Algorithm to determine the prime palindrome integers


Step 1: Declare and initialize required variables such a x, count, rev,
dig.
Step 2: Declare a function isPrime() which returns true when the
number x is

prime and false if it is not prime.


Step 3: Within function isPrime() write the iterative function using for
loop to
find the factors of x.
Step 4: If the count value is==2 return that the number is a prime
number i.e.
return true else false.
Step 5: Declare another function isPalin() that returns true when x is a
palindrome and false if it is not a palindrome.
Step 6: Within the function isPalin() using while loop find the reverse
of the
number x and store it in copy.
Step 7: If reverse==copy return that the number is a palindrome i.e.
true else
return false.
Step 8: Declare another function showPalPrime() that accepts the
upper and
lower limits and prints all the palprime numbers in between
that range
by sending each numbers in the range to both the function
isPrime()
isPalin().
Step 9: Within the function showPalPrime() declare the variable m, n
and c as
integer data types.
Step 10: Enter the lower limit and the upper limit to print the palprime
numbers
Step 11: Check if the range entered is within the limits

Step 12: If the range entered is correct then write a for loop that
generates
every number starting from m till n and sends it to both
functions
isPalin() and isPrime(), to check whether they are both
Palindrome and
Prime or not. If yes, then they are printed.
Step 13: In the main method create an object of Palprime Class that
calls the
function showPalPrime().
Step 14: End the program.

Program to Determine Prime-Palindrome Integers:


import java.io.*;
class PalPrime
{
DataInputStream in=new DataInputStream(System.in);
int i,rev=0,dig;
boolean isPrime(int x) //returns true when the input is prime and false if it is not
{
int count=0;
for(i=1;i<=x;i++)
{
if(x%1==0)
count++;
}

if(count==2)
return true;
else
return false;
}
boolean isPalin(int x) //returns true when input is a Palindrome and false if it is not
{
int copy=x;
while(x>0)
{
dig=x%10;
rev=rev*10+dig;
x=x/10;
}
if(rev==copy)
return true;
else
return false;
}

public void showPalPrime()throws IOException


/*accepts the lower & upper limits and prints all the PalPrime numbers in between
that
range by sending each numbers in the range to both the functions isPrime() and
isPalin()*/
{
int m,n,c=0;
System.out.println("Enter the Lower Limit");
m=Integer.parseInt(in.readLine());
System.out.println("Enter the Upper Limit");

n=Integer.parseInt(in.readLine());
if((m>=n||m>=3000||n>=3000))//checking the range of limits as given in the
question
System.out.println("Out of Range...");
else
{
System.out.println("The Prime Palindrome integers are:");
/*the below for loop generates every number starting from m till n and sends it
to both
functions isPalin() and isPrime(), to check whether they are both Palindrome
and Prime
or not. If yes, then they are printed*/
for(i=m;i<=n;i++)
{
if(isPrime(i)==true&&isPalin(i)==true)
{
if(c==0)
System.out.print(i);//
/*prints the first PalPrime number in order to maintain the sequence of
giving
comma',' before every next PalPrime number as given in the Sample
output
else*/
System.out.print(","+i);
c++;//counting the number of PalPrime numbers by incrementing the
counter
}
}
System.out.println("Freqency of Prime Palindrome integers:"+c);
}
}
public static void main()throws IOException
/*The main method creates an object of PalPrime Class and calls the function

showPalPrime
{
PalPrime ob=new PalPrime();
ob.showPalPrime();
}
}

Output
Example 1:
Input:
m =100
n =1000
Output:
The Prime Palindrome Integers are:
101,131,151,181,191,313,353,373,383,727,757,787,797,919,929

The frequency of Prime Palindrome Integers:15

Example 2:
Input:
m =100
n

=3001

Output:
Out of Range

Result
Thus the above program has been executed successfully and the
output had
been verified

4
Brindavan Public School-Coonoor

Smith Number

Question 2 :
A Smith Number is a composite number, the sum of whose
digits is
the sum of the digits of its prime factors obtained as a result of prime
factorization (excluding 1). The first few such numbers are
4,22,27,58,85,94,122...
Example
666
Prime factors are 2,3,3 and 37
Sum of the digits are(6+6+6)=18
Sum of the digits of the factors(2+3+3+(3+7))=18
Aim :
To determine if the given number is Smith number or not

Algorithm to determine the Smith number


Step 1: Start
Step 2: Create a class called Smith.
Step 3: Within the class Smith create a function sumDig() for finding
the sum
of the digits.
Step 4: Find the sum of the digits using the while loop and store the
sum in s
Step 5: Return the value of s to the function sumDig() using the return

statement
Step 6: Create another function sumPrimeFact() for generating the
prime
factors and finding their sum
Step 7: Within the function sumPrimeFact() using the while loop find
the
prime factor of the number and also find its sum and return it
Step 8: Create a main function and within the main function create an
object
ob for the class Smith to call the member functions
Step 9:

Compare the values returned by both the member functions

Step 10: If the values returned are equal then print that the number is
Smith
number
Step 11: Else print that the number is not a prime number
Step 12: Stop

Program to check if the given number is Smith number or not:


import java.io.*;
class Smith
{
static DataInputStream in=new DataInputStream(System.in);
int sumDig(int n)//function to find the sum of the digits
{
int s=0;
while(n>0)
{

s=s+n%10;
n=n/10;
}
return s;
}
int sumPrimeFact(int n)//function for generating prime factors and finding their
sum
{
int i=2,sum=0;
while (n>1)
{
if(n%i==0)
{
sum=sum+sumDig(i);//here 'i' is the prime factor of 'n' and we are finding
its sum
n=n/i;
}
else
i++;
}
return sum;
}
public static void main()throws IOException
{
Smith ob=new Smith();
System.out.println("Enter a Number: ");
int n=Integer.parseInt(in.readLine());
int a=ob.sumDig(n);//finding the sum of the digit
int b=ob.sumPrimeFact(n);//finding sum of the prime factors
System.out.println("Sum of the Digit="+a);
System.out.println("Sum of Prime Factors="+b);
if(a==b)
System.out.println("It's a Smith Number");

else
System.out.println("It's not a Smith Number");
}
}

Output
Example 1:
Input:
Enter the number:
4937775
Output:
Sum of the Digit=42
Sum of Prime Factors=42
It's a Smith Number

Example 2:
Input:
Enter a Number:
78
Output:

Sum of the Digit=15


Sum of Prime Factors=9
It's not a Smith Number

Result
Thus the above program has been executed successfully and the
output had
been verified

7
Brindavan Public School-Coonoor

Kaprekar Number

Question 3 :
Write a program in Java to input a number and check whether
it is a
Kaprekar Number or not. Note: A positive number n that had d
number of
digits is squared and split into two pieces, a right-hand piece that has
d
digits and a left-hand piece that has remaining d or d-1 digits. If the
sum of
the two digits is equal to the number then n is a Kaprekar number.
Example
9
92 = 81;right-hand pieces of 81 = 1 and left hand piece of 81 = 8
Sum = 1+8=9,i.e. equal to the number
Hence, 9 is a Kaprekar number.
Aim :
To determine if the given number is Kaprekar number or not

Algorithm to determine the Kaprekar number


Step 1: Start
Step 2: Create a class called Kaprekar.
Step 3: Within the main functions declare all the variables such as n,
sq

Step 4: Enter the number which is to be checked if it is a Kaprekar


number
and store it in n
Step 5: Find the square of the number entered and store it in sq
Step 6: Convert the square of the number obtained into its string
value using
the Integer.toString() function and store it in s
Step 7: Check if the value of s is less than or equal to 9
Step 8: If the value is less than 9 then add 0 to the value of s
Step 9:

Using the length() function find the length(i.e. number of

digits in the
square) and store it in l
Step 10: Find the middle point of I by dividing the l value by 2 and
store it
in mid.
Step 11: Extract the left digits from the square using the function
s.substring(0, mid) and store it in left
Step 12: Extract the right digits from the square using the function
s.substring(mid) and store it in right
Step 13: Convert the left string into integer value using the function
Interger.parseInt(left) and store it in x
Step 14: Convert the right string into integer value using the function
Interger.parseInt(right) and store it in y
Step 15: Check if the sum of left and right numbers are equal to the
original
number
Step 16: If the numbers are equal then print the number is Kaprekar

number
Step 17: Else print the number is not a Kaprekar number
Step 18: Stop

Program to check if the given number is Kaprekar number or not:


import java.io.*;
class Kaprekar
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Number");
int n=Integer.parseInt(in.readLine());//to input a number
int sq=n*n;//to find the square of the number
String s=Integer.toString(sq);//converting the square into a String
if(sq<9)
s="0"+s;
int l=s.length();//to fing the length
int mid=l/2;//finding the middle point
String left=s.substring(0,mid);//extracting the left digits from the square
String right=s.substring(mid);//extracting the right digits from the square
int x=Integer.parseInt(left);//converting the left string into integer
int y=Integer.parseInt(right);//converting the right string into integer
if(x+y==n)//to determine whether the sum of left and right digits is equal to the
original
number
System.out.println(n+" is a Kaprekar number");
else
System.out.println(n+" is not a Kaprekar number");
}

Output
Example 1:
Input:
Enter the number:
45
Output:
45 is a Kaprekar number
Example 2:
Input:
Enter a Number:
67
Output:
67 is not a Kaprekar number

Result
Thus the above program has been executed successfully and the
output had
been verified

10
Brindavan Public School-Coonoor

Emirp Number

Question 4 :
An Emirp Number is a number which is prime backwards and
forwards.
Example:13 and 31 are both prime numbers. Thus, 13 is a Emirp
number.
Design a class Emirp to check if a given number is Emirp number or
not.
Some of the members of the class are given below
Class name: Emirp
Data members/instance variable:
n : to store the number
rev : stores the reverse of the number
f : stores the divisor
Member functions:
Emirp(int nn) : to assign n=nn, rev=0 and f=2
int isprime(int x) : check if the number is prime using the recursive
technique return 1 if prime otherwise return 0
void isEmpire() : reverse the given and check if both the original number
and the reverse number are prime, by involving the function isprime(int)
and display the result with an appropriate message
Specify the class Emirp giving details of the constructor(int), int isprime(int) and
void
isEmirp(). Define the main() function to create an object and call the to check for
Emirp number.

Aim :
To determine if the given number is Emirp number or not

Algorithm to determine the Emirp number


Step 1: Start
Step 2: Create a class called Emirp.
Step 3: Declare the required variable such as n, rev, f
Step 4: Create a parameterised constructor Emirp(int nn) and pass the
arguments nn
Step 5: Initialize the variables rev=0, f=2
Step 6: Create a recursive function isPrime(int x) for checking whether
x is
prime or not
Step 7: Check if the value of f is less than or equal to x
Step 8: If the condition is satisfied check x is modulus f is not equal to
0
Step 9:

If the condition is satisfied then the value of f is incremented

every
time we dont get a factor
Step 10: Since f was increasing every time we do not get a factor
hence, if f
becomes equal to the number then that means that the number
is not
divisible by any other number except by 1 and itself its a prime
Step 11: If the value of f is equal to value of x then return 1 else
return 0
Step 12: Create another function isEmirp()
Step 13: Within the function isEmirp() write the code for reversing the
original

number and store the reversed number in d


Step 14: Call the function isPrime(n) to check whether the original
number is
prime or not and store the returned value in a
Step 15: Reset the value of f as 2 to check whether the reversed
number is
prime or not
Step 16: Call the isPrime(rev) function to check whether the reversed
number
is prime or not and store the returned value in b
Step 17: Check if the value of a and b is equal to 1
Step 18: If the both the original and the reversed number are prime
then print
the number is an Emirp number
Step 19: Else print the number is not an Emirp number
Step 20: Stop

Program to check if the given number is a Emirp number or not:


import java.io.*;
class Emirp
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n,rev,f;
Emirp(int nn)//parameterised constructor
{
n=nn;
rev=0;
f=2;

}
int isPrime(int x)//recursive function for checking whether 'x' is Prime or not
{
if(f<=x)
{
if(x%f!=0)//f is increasing everytime we are not getting any factor
{
f++;
isPrime(x);
}
}
if(f==x)
return 1;
else
return 0;
}
void isEmirp()
{
int copy=n,d;
while(copy>0)//code for reversing a number
{
d=copy%10;
rev=rev*10+d;
copy=copy/10;
}
int a=isPrime(n);//checking whether the original number is prime or not
f=2;//resetting of f for checking whether the reversed number is prime or not
int b=isPrime(rev);//checking whether the reversed number is prime or not
if(a==1&&b==1)//if bothe original and reversed are prime then it is emirp
number
System.out.println(n+" is an Emirp number");
else
System.out.println(n+" is not an Emirp number");

}
public static void mian()throws IOException
{
System.out.println("Enter any number");//to input thw original number
int n=Integer.parseInt(in.readLine());
Emirp ob=new Emirp(n);
ob.isEmirp();
}
}

Output
Enter any number:13
13 is a Emirp number
Enter any number:41
41 is not an Emirp number

Result
Thus the above program has been executed successfully and the output
has
been verified

13
Brindavan Public School-Coonoor

Unique Number

Question 5 :
Write a program in Java to input a number and check whether
it is a
Unique number or not.
Note: A unique number is a positive integer(without leading zeros)
with
no duplicate digits. For example 7,133,214 are all unique numbers
whereas
33,3121,200 are not
Aim :
To determine if the given number is Unique number or not

Algorithm to determine the Unique number


Step 1: Start
Step 2: Create a class called Unique
Step 3: Within the main functions declare all the required variables
Step 4: Enter the number which is to be checked if it is a Unique
number
and store it in n
Step 5: Convert the number to its equivalent string value using the
function
Interger.toString(n) function and store it in s
Step 6: Find the length of s using s.length() function and stoer it in l
Step 7: Write a for loop for checking if there are any repeated digits

Step 8: If there are any repeated numbers then print the number is
not an
Unique number
Step 9:

Else print the number is an Unique number

Step 10: Stop

Program to check if the given number is a Unique number or not:


import java.io.*;
class unique
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any number");
int n=Integer.parseInt(in.readLine());
String s=Integer.toString(n);//converting the number into String form
int l=s.length();
int flag=0;
for(int i=0;i<=l-1;i++)//for loop for checking whether there are repeated digits
{
for(int j=i+1;j<1;j++)
{
if(s.charAt(i)==s.charAt(j))// if any digits match, then we know it is not a
Unique
number
{
flag=1;
break;
}
}

}
if(flag==0)
System.out.println("**** The number is a Unique number ****");
else
System.out.println("**** The number is not a Unique number ****");
}
}

Output
Enter any number:13
**** The number is a Unique number ****
Enter any number:44
**** The number is not a Unique number ****

Result
Thus the above program has been executed successfully and the output
has
been verified

15
Brindavan Public School-Coonoor

Lucky Number

Question 6 :
Consider the sequence of natural numbers
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
Removing the second number produces the sequence
1,3,5,7,9,11,13,15,17,19,21,23,25
Removing the third number produces the sequence
1,3,7,9,13,15,19,21,25
This process continues indefinitely by removing the fourth, fifth
and so
on, till after a fixed number of steps, certain natural numbers remain
indefinitely. These are known as Lucky numbers.
Write a program to generate and print lucky numbers less than
a given
number N.
Aim :
To generate and print the lucky numbers within a given range

Algorithm to print the Lucky number


Step 1: Start
Step 2: Create a class named LuckyNumbers
Step 3: Within the main functions declare all the required variables
Step 4: Enter the number of elements or the limit and store it in n
Step 5: Create an array named a[] of size based on the number of

elements
Step 6: Using a while loop consider the sequence of natural numbers
up to
the given limit n
Step 7: Remove the second number to produce another sequence
Step 8: Remove the third number from the previous sequence to
produce
another sequence
Step 9:

Continue the process indefinitely by removing the fourth,

fifth.. and
so on till after a fixed number of steps certainly natural number
remain
indefinitely. Print the numbers which remain till the end. These
numbers
are known as lucky number.
Step 10: Stop

Program to print the Lucky Number:


import java.io.*;
class LuckyNumbers
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of elements");
int n=Integer.parseInt(in.readLine());
int a[]=new int[n];
int c=n;

for(int i=0;i<n;i++)
{
a[i]=i+1;
}
int del=1;
System.out.println("\nLucky Number Operation :\n");
while(del<n)
{
for(int i=del;i<n;i+=del)
{
for(int j=i;j<n-1;j++)
{
a[j]=a[j+1];
}
n--;
}
del++;
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
}//end of while loop
System.out.print("\nHence, the Lucky Numbers less than "+c+" are:");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
}
}

Output
Enter the number of elements
25
Lucky Number Operation :
1 3 5 7 9 11 13 15 17 19 21 23 25
1 3 7 9 13 15 19 21 25
1 3 7 13 15 19 25
1 3 7 13 19 25
1 3 7 13 19
Hence, the Lucky Numbers less than 25 are:1 3 7 13 19

Result
Thus the above program has been executed successfully and the output
has
been verified

18
Brindavan Public School-Coonoor

Swapping of two Number

Question 7 :
Write a program for swapping of two numbers without using
any third
variable.
Aim :
To write a program for swapping of two numbers without using
any third
variable.

Algorithm to determine the Unique number


Step 1: Start
Step 2: Create a class named Swapping_Method
Step 3: Within the main functions declare all the required variables
Step 4: Enter two numbers and store them in a and b
Step 5: Calculate the value of a power b and store it in a
Step 6: Now once again calculate the value of a power b and store
it in b
Step 7: Once again calculate the value of a power b and store it in
a
Step 8: Print the Swapped values for a and b
Step 9: Stop

Program for Swapping two numbers without using any third variable:

import java.io.*;
class Swapping_Method
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int a,b;
System.out.println("Enter the 1st Number");
a=Integer.parseInt(in.readLine());
System.out.println("Enter the 2nd Number");
b=Integer.parseInt(in.readLine());
System.out.println("--------------------");
System.out.println("The Numbers before Swapping are");
System.out.println("a="+a);
System.out.println("b="+b);
//beginning of swapping
a=a^b;
b=a^b;
a=a^b;
//end of swapping
System.out.println("--------------------");
System.out.println("The Numbers after Swapping are");
System.out.println("a="+a);
System.out.println("b="+b);
}
}

Output
Enter the 1st Number
56
Enter the 2nd Number
54

-------------------The Numbers before Swapping are


a=56
b=54
-------------------The Numbers after Swapping are
a=54
b=56

Result
Thus the above program has been executed successfully and the output
has
been verified

20
Brindavan Public School-Coonoor

Find the Day of the given Date

Question 8 :
Write

program

to

accept

date

in

the

string

format(dd/mm/yyyy) and
accept the name of the day on first of January of the corresponding
year.
Find the day for the given date.
Example:
Input:
Date:5/7/2001
Day on first January : Monday
Output:
Day on 5/7/2001 : Thursday
Aim :
To write a program to find the day of the given date.

Algorithm to find the day of the given date


Step 1: Start
Step 2: Create a class named DateDay
Step 3: Within the main functions create an array int month[] and
store the
number of days in each month in the array[]
Step 4: Create another array String days[] and store the days of the
week in
the array[]

Step 5: Enter the date whose day is to be found


Step 6: Store the day, month and year values of the date entered
separately
in the variables d, m, y respectively
Step 7: Check if the year entered is a leap year
Step 8: If the year is a leap year then store month[2] as 29 days
Step 9: Check if the date entered is valid date
Step 10: Calculate the day number in the year for the given date
Step 11: Enter the day on first January in the year of the date entered
and
store it in s
Step 12: Find the day of the week which corresponds to the given day
name
Step 13: Calculate the name of day of the week, of the given date
using the
value calculated in the previous steps
Step 14: Print the day of the given date
Step 15: Stop
Program to find the day of the given date:
import java.io.*;
class DateDay
{
public static void mian()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
String
days[]={,Sunday,Monday,TuesDay,Wednesday,Thursday,Friday,Saturday};

System.out.println(Enter the date in (dd/mm/yyyy) format);


String date=in.readLine().trim();
int p=date.indexOf(/);
int d=Integer.parseInt(date.substring(0,p));
int q=date.lastIndexOf(/);
int m=Integer.parseInt(date.substring(p+1,q));
int y=Integer.parseInt(date.substring(q+1));
if((y%400==0)||((y%100!=0)&&(y%4==0)))//condtion for leap year
month[2]=29;
if(d>0&&d<=month[m]&&m>0&&m<=12&&y>0&&y<=9999)//condtions for
date to be valid
{
//calculating the day in the year, of the given date
int dn=0;
for(int i=1;i<m;i++)
{
dn=dn+month[i];
}
dn=dn+d;
System.out.println(Enter the Day on 1st January in this Year);
String s=in.readLine().trim();
//finding the day of the week which corresponds to the given day name
int x=0;
for(int i=1;i<=7;i++)
{
if(s.equalsIgnoreCase(days[i]))
x=i;
}
//the main calculation of finding the name of the day of the week of the given
date
48tarts here
for(int i=1;i<dn;i++)
{

x++;
if(x==8)
x=1;
}
System.out.println(Output : Day on +date+ : +days[x]);
}
else
System.out.println(Invalid Date);
}
}

Output
Enter the date in (dd/mm/yyyy) format
5/7/2014
Enter the Day on 1st January in this Year
Wednesday
Output : Day on 5/7/2014:Saturday

Result
Thus the above program has been executed successfully and the output
has
been verified

23
Brindavan Public School-Coonoor

Future Date

Question 9 :
Write

program

to

accept

date

in

the

string

format(dd/mm/yyyy)
check whether the date entered is valid or not if it is valid then input a
certain number of days and calculate and print the future date after
adding
given number of days if the future date is valid. If the date entered is
invalid
then display a proper error message.
Example:
Input:
Date:7/4/2014
Enter the additional days:7
Output:
Entered date: 7/4/2014
Future date: 14/4/2014
Aim :
To write a program to find the future date.

Algorithm to determine the Future date


Step 1: Start
Step 2: Create a class named FutureDate
Step 3: Within the main functions create an array int month[] and
store the

number of days in each month in the array[]


Step 4: Enter the date from which the future date is to be calculated
Step 5: Store the day, month and year values of the date entered
separately
in the variables d, m, y respectively
Step 6: Enter the number of days after which the future date has to
be
calculated
Step 7: Check if the year entered is a leap year, if the year is a leap
year then
store month[2] as 29 days
Step 8: Check if the date entered is valid date
Step 9: If the date entered is valid then add the number of days
entered to
the given date
Step 10: Implement the values of d, m and y according to the
values
calculated
Step 11: Print the future date that is calculated
Step 12: Stop.

Program to calculate the future date:


import java.io.*;
class FutureDate
{
public static void mian()throws IOException

{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
System.out.println(Enter the date in (dd/mm/yyyy) format);
String date=in.readLine().trim();
int p=date.indexOf(/);
int d=Integer.parseInt(date.substring(0,p));
int q=date.lastIndexOf(/);
int m=Integer.parseInt(date.substring(p+1,q));
int y=Integer.parseInt(date.substring(q+1));
System.out.println(Enter the number of days after which the future date is to be
found);
int days=Integer.parseInt(in.readLine());
System.out.println(Entered Date : +date);//printing the enetered date
if((y%400==0)||((y%100!=0)&&(y%4==0)))//condtion for leap year
month[2]=29;
if(d>0&&d<=month[m]&&m>0&&m<=12&&y>0&&y<=9999)//condtions for
date to be valid
{
int count=0;
while(count<days)
{
d++;
count++;
if(d>month[m])
{
d=1;
m++;
}
if(m>12)
{
m=1;
y++;

if(y%400==0||((y%100!=0)&&(y%4==0)))
month[2]=29;
else
month[2]=28;
}
}
System.out.println(Future Date : +d+/+m+/+y);
}
else
System.out.println(Invalid Date);
}
}

Output
Enter the date in (dd/mm/yyyy) format
12/12/12
Enter the number of days after which the future date is to be found
365
Entered Date : 12/12/12
Future Date : 12/12/13

Result
Thus the above program has been executed successfully and the output
has

been verified

26
Brindavan Public School-Coonoor

Difference between Two Dates


Question 10 :
Write

program

to

accept

two

date

in

the

string

format(dd/mm/yyyy)
and find the difference between two dates
Example:
Input:
Date:20/12/2012
Date1:11/2/2013
Output:
Difference : 54 days
Aim :
To write a program to find the difference between two dates

Algorithm to find the difference between two dates


Step 1: Start
Step 2: Create a class named Date_Difference
Step 3: Create a function isLeap() create an array int month[] and
store the
number of days in each month within the fucntion
Step 4: Check if the year is leap year using the function isLeap()
Step 5: If the year is leap then return true else return false
Step 6: Check if the date entered is valid using the function
dateValidate()

Step 7: Return true if the date entered is valid and false if it is not
Step 8: If the year is a leap year then add+366 to the value of dn else
add
+365 to the value of dn
Step 9: Within the main function create an object for the class
Date_Difference as ob
Step 10: Enter both the dates whose difference is to be calculated
Step 11: Store values of day, month and year separately of both dates
using
the variables d, m, y and d1, m1, y1 respectively
Step 12: Using the object created ob call the functions to calculate
the
difference between two dates
Step 13: Print the difference between the dates
Step 14: Stop.

Program to calculate the difference between two dates:


import java.io.*;
class Date_Difference
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int month []={0,31,28,31,30,31,30,31,31,30,31,30,31};
boolean isLeap(int y)
{
if((y%400==0) || ((y%100!=0)&&(y%4==0)))
return true;
else
return false;

}
boolean dateValidate(int d,int m,int y)
{
if(d>0&&d<=month[m]&& m>0&&m<=12&& y>0&&y<=9999)
return true;
else
return false;
}
int dayno(int d, int m, int y)
{
int dn=0;
for(int i=1;i<m;i++)
{
dn=dn+month[i];
}
dn=dn+d;
for (int i=1;i<y;i++)
{
if(isLeap(i)==true)
dn=dn+366;
else
dn=dn+365;
}
return dn;
}
public static void main()throws IOException
{
Date_Difference ob=new Date_Difference();
System.out.println("Enter the 1st date in dd/mm/yyyy) format:");
String date1=in.readLine().trim();
int p,q;
p=date1.indexOf("/");
int d1=Integer.parseInt(date1.substring(0,p));

q=date1.lastIndexOf("/");
int m1=Integer.parseInt(date1.substring(p+1,q));
int y1=Integer.parseInt(date1.substring(q+1));
System.out.println("Enter the 2nd date in (dd/mm/yyy) farmat:");
String date2=in.readLine().trim();
p=date2.indexOf("/");
int d2=Integer.parseInt(date2.substring(0,p));
q=date2.lastIndexOf("/");
Int m2=Integer.parseInt(date2.substring(p+1,q));
int y2=Integer.parseInt(date2.substring(q+1));
if(ob.dateValidate(d1,m1,y1)==true&&ob.dateValidate(d2,m2,y2)==true)
{
int a=ob.dayno(d1,m1,y1);
int b=ob.dayno(d2,m2,y2);
System.out.println("Output: Difference of days="+Math.abs(a-b));
}
else
System.out.println("Invalid Date");
}
}

Output
Enter the 1st date in dd/mm/yyyy) format:
20/12/2012
Enter the 2nd date in (dd/mm/yyy) farmat:
11/02/2013
Output: Difference of days=54

Result
Thus the above program has been executed successfully and the output
has
been verified

29
Brindavan Public School-Coonoor

Conversion of Time in Numbers to Time in Words

Question 11 :
Given a time in numbers we can convert it into words. For
example:
5.10 --- Ten minutes past Five
Write a program which inputs two integers, the first between 1
and 12
and the second between 0 and 59 and then prints out the time they
represents, in words.
Sample Data:
1. Input: Time-3:0
Output: Three o clock
2. Input: Time-7:29
Output: Twenty nine minutes past Seven

Aim :
To write a program to print the given time in words

Algorithm to convert time in numbers to time in words


Step 1: Start
Step 2: Create a class named TimeInWords
Step 3: Within the main function declare all required variables
Step 4: Enter hours ans store it in h
Step 5: Enter minutes and store it in m
Step 6: Check if the date entered is valid using the function

dateValidate()
Step 7: Return true if the date entered is valid and false if it is not
Step 8: If the year is a leap year then add+366 to the value of dn else
add
+365 to the value of dn
Step 9: Within the main function create an object for the class
Date_Difference as ob
Step 10: Enter both the dates whose difference is to be calculated
Step 11: Store values of day, month and year separately of both dates
using
the variables d, m, y and d1, m1, y1 respectively
Step 12: Using the object created ob call the functions to calculate
the
difference between two dates
Step 13: Print the difference between the dates
Step 14: Stop.

Program for converting time in number to time in words:

import java.io.*;
class TimeInWords
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
/*inputting hours and minutes*/
System.out.println("Enter hours");
int h=Integer.parseInt(in.readLine());

System.out.println("Enter the minutes");


int m=Integer.parseInt(in.readLine());
if((h>=1&&h<=12)&&(m>=0&&m<59))//validation of the given time
{
//Creating an array containing numbers from 1-29 in words
String
words[]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen",
"Nineteen","Twenty","Twenty One","Twenty Two","Twenty Three","Twenty Four",
"Twenty Five","Twenty Six","Twenty Seven","Twenty Eight","Twenty Nine"};
//the following code is for finding whether to print thr word 'minute or
'minutes'
String plu,a;
if(m==1)
plu=" Minute ";
else
plu=" Minutes ";
//the below code is to decides whether to print what hour to print in words if
the given
minute is from 31-59
if(h==12)
a=words[1];//storing one when hour is twelwe
else
a=words[h+1];//if hour is not 12 then storing in words an hour ahead of given
hour
System.out.print("\nOutput: "+h+":"+m+" ---- ");
if(m==0)
System.out.println(words[h]+ " O' Clock");
else if(m==15)
System.out.println("Quarter past "+words[h]);
else if(m==30)
System.out.println("Half past "+words[h]);
else if(m==45)

System.out.println("Quater to "+a);
else if(m<30)//condition for minutes between 1-29
System.out.println(words[m]+""+plu+ "past "+words[h]);
else //condition for minutes between 31-59
System.out.println(words[60-m]+""+plu+"to "+a);
}//end of outer if
else
System.out.println("Invalid Input...");//printing error message for illegel output
}
}

Output
Enter hours
5
Enter the minutes
34
Output: 5:34 ---- Twenty Six Minutes to Six

Result
Thus the above program has been executed successfully and the output
has
been verified

32
Brindavan Public School-Coonoor

Decimal to Hexa-Decimal Conversion

Question 12 :
Write a program in Java to input a number in Decimal number
system
convert it into its equivalent number in the Hexadecimal number
system.
Note: Hexadecimal number system is a number system which can
represent
a number in any other number system in terms of digits ranging from
0-9
and then from A-F only. This number system consists of only sixteen
basic
digits.

Aim :
To write a program to input a Decimal number and convert it to its
equivalent number in Hexadecimal number system.
Algorithm to convert decimal to hexa-decimal number
Step 1: Start
Step 2: Create a class named Dec2Hex
Step 3: Within the main function declare all required variables
Step 4: Declare a variable s for storing the result as null
Step 5: Create an array of character data type named dig[] to store
the
hexa-decimal values

Step 6: Enter the decimal number that is to be converted and store it


in n
Step 7: Check if the value of the number entered is greater than 0
Step 8: If the value is greater than 0 then find the modulus value the
number
n when divided by 16
Step 9: Then add the remainder obtained from the previous operation
to the
result s
Step 10: Divide the number n by 16 and store it in n
Step 11: Repeat steps 8,9,10 until the value of n is greater than 0
Step 12: If the value of n becomes less than or equal to 0 then print
the
output
Step 13: Stop.

Program for converting Decimal number to its equivalent


Hexa-Decimal Number:

import java.io.*;
class Dec2Hex

{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a decimal number");
int n=Integer.parseInt(in.readLine());
int r;
String s="";//variable for storing the result
char dig[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};//array storing the digits
in a hexadecimal
number system
while(n>0)
{
r=n%16;//finding remainder by dividing the number by 16
s=dig[r]+s;//adding the remainder to the result
n=n/16;
}
System.out.println("Output ="+s);
}
}

Output
Enter a decimal number
78
Output =4E

Result
Thus the above program has been executed successfully and the output
has

been verified

34
Brindavan Public School-Coonoor

Decimal to Binary Conversion

Question 13 :
Write a program in Java to input a number in Decimal number
system
convert it into its equivalent number in the Binary number system.
Note: Binary number system is a number system which can represent a
number in any other number system in terms of 0,1 only. This
number
system consists of only two basic digits.
Aim :
To write a program to input a Decimal number and convert it to its
equivalent number in Binary number system.
Algorithm to convert decimal to binary number
Step 1: Start
Step 2: Create a class named Dec2Bin
Step 3: Within the main function declare all required variables
Step 4: Declare a variable s for storing the result as null
Step 5: Create an array of character data type named dig[] to store
the
values Binary number system
Step 6: Enter the decimal number that is to be converted and store it
in n
Step 7: Check if the value of the number entered is greater than 0
Step 8: If the value is greater than 0 then find the modulus value the
number

n when divided by 2
Step 9: Then add the remainder obtained from the previous operation
to the
result s
Step 10: Divide the number n by 2 and store it in n
Step 11: Repeat steps 8,9,10 until the value of n is greater than 0
Step 12: If the value of n becomes less than or equal to 0 then print
the
output
Step 13: Stop.

Program for converting Decimal number to its Binary form:


import java.io.*;
class Dec2Bin
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter a decimal number);
int n=Integer.parseInt(in.readLine());
int r;
String s=;//variable for stroring the result
char dig[]={0,1};//array storing the digits in binary number system
while(n>0)
{

r=n%2;//finding remainder by dividing the number by 2


s=dig[r]+s;//adding the remainder to the result and reversing at the same time
n=n/2;
}
System.out.println(Output =+s);
}
}

Output
Enter a decimal number
25
Output =11001

Result
Thus the above program has been executed successfully and the output
has
been verified

36
Brindavan Public School-Coonoor

Fibonacci Series

Question 14 :
A class recursion as been defined to find the Fibonacci series
upto a
limit. Some of the members are given below
Class Name: Recursion
Data Members/Instance Variables
a, b, c, limit(all integer variables)
Member function/Method
Recuriosn()-Constructor to assign a, b, c with appropriate values
void input()-To accept the limit of the series
int fib(int n)-To return the nth Fibonacci term using recursive
technique
void generate_fibseries()-To generate the fibonacci series upto
the
given limit
Specify the class Recursion giving the details of the main methods,
you
may assume other functions are written for you and you need not
write the
main function.
Aim :
To find the fibonacci series upto the limit using recursion.
Algorithm to print the Fibonacci series

Step 1: Start
Step 2: Create a class named Recursion
Step 3: Within the main function declare all required variables
Step 4: Create a constructor called Recursion() and initialize variables
a, c,
limit as 0 and b as 1
Step 5: Create a function named input() to input the limits
Step 6: Within the function input() enter the limit of the series and
store the
limit in limit
Step 7: Create a recursion function named fib(int n) for generating nth
term of
the fibonacci series
Step 8: Within the function fib(int n) check if the value of n is less
than or
equal to one
Step 9: If the condition is satisfied return the value of a
Step 10: Otherwise if the value of n is equal to two return the value
of b
Step 11: If both the condition are not satisfied then return (fib(n1)+fib(n-2))
Step 12: Create another function named generate_fibseries() for
generating
all the fibonacci series numbers upto n terms.
Step 13: Within the main function create an object called ob to call
the
member function
Step 14: Print the fibonacci series within the range limit

Step 15: Stop.


Program to print the Fibonacci series using Recursion:
import java.io.*;
class Recursion
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int a,b,c,limit;
Recursion()//Constructor
{
a=0;
b=1;
c=0;
limit=0;
}
void input()throws IOException//function to input the limit
{
System.out.println("Enter the limit");
limit=Integer.parseInt(in.readLine());
}
int fib(int n)//recursive function generating the 'nth' term of Fibonacci Series
{
if(n<=1)
return a;
else if(n==2)
return b;
else
return (fib(n-1)+fib(n-2));
}
void generate_fibseries()//function generating all the fibonacci series numbers upto
'n'
terms

{
System.out.println("The fibonacci Series is:");
for(int i=1;i<=limit;i++)
{
c=fib(i);
System.out.print(c+" ");
}
}

public static void main()throws IOException


{
Recursion ob=new Recursion();
ob.input();
ob.generate_fibseries();
}
}

Output
Enter the limit
20
The fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Enter the limit


11
The fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 55

Result
Thus the above program has been executed successfully and the output
has
been verified

39
Brindavan Public School-Coonoor

String manipulation using Constructor

Question 15 :
Design

a class exchange to accept a sentence and interchange

the
first alphabet with the last alphabet for each word in the sentence,
with single
letter word remaining unchanged. The words in the input sentence are
separated by single blank space and terminated by a full stop.
Example input : it is warm day
Output : tl si a marw yad
Some of the data members and member functions are given
below :
Class name: Exchange
Data members/instance variables
Sent: store the sentence
Rev: to store the new sentence
Size: stores the length of the sentence
Member function:
Exchange (): default_constructor
void readsentence (): to accept the sentence
void exfirstlast(): extract each word and interchange

the

first and
the last alphabet of the word and form a new sentence rev using
the
changed words
void display (): display the original sentence along with the
new
changed sentence.

Specify the class Exchange giving details of the


constructor (),
void readsentence(),

void exfirstlast() and void display(). Define the

main ()
function to create an object

and call the function accordingly to

enable the
task.
Aim :
To accept a sentence and interchange the first alphabet with the last
alphabet

Algorithm to manipulate string using constuctor


Step 1: Start
Step 2: Create a class named Exchange
Step 3: Declare the variables sent, rev as string data type and size as
integer
data type
Step 4: Create a constructor named exchange and within the
constructor
initialize sent, rev as null and size as 0
Step 5: Create another function named readsentenc () and enter the
sentence which is to be stored in sent
Step 6: Calculate the length of the sentence using length() and store
it in
size
Step 7: Check whether the sentence ends with full stop or not. If not
then

add a full stop and increase the length by 1


Step 8: Create another function named exfirstlast() and declare
variable s1 as
string data type and ch as character data type
Step 9: Initialize s1 the temporary string variable for holding each as it
is
extracted as null
Step 10: Check if the character are the current position is a blank
space or
full stop
Step 11: If the condition is satisfied then add the character to the
temporary
variable
Step 12: If the condition is not satisfied then calculate the length of
the
extracted word and store it in 1
Step 13: Exchange the first alphabet with the last alphabet of the
word
Step 14: After exchanging all the characters in the sentence add the
characters to the reversed string
Step 15: After completion of a word add a space to the new string
Step 16: Empty the temporary string variable
Step 17: Create another class named display() and print original
sentence
and reversed sentenceusing the objects created with in the main
function
Step 18: Stop.

Program to execute String manipulation using constructor:


import java.io.*;
class Exchange
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String sent,rev;
int size;
Exchange()//default constructor
{
sent="";
rev="";
size=0;
}
void readsentence()throws IOException
{
System.out.println("Enter a sentence");
sent=in.readLine();
size=sent.length();
if(sent.charAt(size-1)!='.')//checking whether the senetence ends in a fullstop
or not
{
//if not then adding a full stop to it and increasing the length by 1
sent=sent+".";
size=size+1;
}
}
void exfirstlast()
{
String s1="";//temporary string variable for holding each word as it is
extracted
char ch;

for(int i=0;i<size;i++)
{
ch=sent.charAt(i);
if(ch!=' '&&ch!='.')
{
s1=s1+ch;
}
else
{
int l=s1.length();
for(int j=0;j<l;j++)
{
if(j==0)
ch=s1.charAt(l-1);
else if(j==(l-1))
ch=s1.charAt(0);
else
ch=s1.charAt(j);
rev=rev+ch;
}
rev=rev+" ";
s1="";
}
}
}
void display()
{
System.out.println("The Original Sentence is : " +sent);
System.out.println("The Reversed Sentence is : " +rev);
}
public static void main()throws IOException
{
Exchange ob=new Exchange();

ob.readsentence();
ob.exfirstlast();
ob.display();
}
}

Output
Enter a sentence
This is my house
The Original Sentence is : This is my house.
The Reversed Sentence is : shiT si ym eoush

Result
Thus the above program has been executed successfully and the output
has
been verified

43
Brindavan Public School-Coonoor

Frequency of an Alphabet in a String

Question 16 :
Write a java program to input a String and convert it to
lowercase letters. Count and print the frequency of each alphabet
present in the string.
Aim :
To count and print the frequency of a alphabet in a string
Algorithm to print the frequency of an alphabet in a string
Step 1: Start
Step 2: Create a class named Alphabet_Freq
Step 3: Within the main function declare all the required variables
Step 4: Enter a string and store it in s
Step 5: Convert the string s to lower case using the function
toLowerCase()
and store it in s
Step 6: Calculate the length of the sentence using length() and store it
in l
Step 7: Create an array named alpha[] of character data type to store
the
alphabets from a to z
Step 8: Create another array named freq[] of integer data type to
store the
frequency of all alphabets
Step 9: Initialize the variable c as a
Step 10: Using the for loop store all the alphabets from a to z in
alpha[]

Step 11: Create a nested for loop and extract the chracters from the
string
s on by one
Step 12: Then check the whole string for a and then b and so on
Step 13: Increase the count of those alphabets which are present in
the
string
Step 14: Print only those alphabets whose count is not equal to 0
along with
their frequencies
Step 15: Stop.

Program to print the frequency of an alphabet in a String


import java.io.*;
class Alphabet_Freq
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String");
String s=in.readLine();
s=s.toLowerCase();//converting string into lowercase
int l=s.length();//finding the length of the string

char alph[]=new char[26];//array for storing alphabets from 'a' to 'z'


int freq[]=new int[26];//array for stroing frequency of all alphabets
char c='a';
for(int i=0;i<26;i++)
{
alph[i]=c;//strong all alphabets from 'a' till 'z' in alph[] array
freq[i]=0;//initializing the count of every alpbhabet with '0'
c++;
}
char ch;
System.out.println("Output");
System.out.println("******");
System.out.println("Alphabet\tFrequency");
System.out.println("\t ******");
for(int i=0;i<26;i++)
{
for(int j=0;j<1;j++)
{
ch=s.charAt(j);//extrating characters of the string one by one
if(ch==alph[i])//first checking the whole string for 'a'. then 'b' and so on
{
freq[i]++;//increasing count of those alphabets which are present in the
string
}
}
}
for(int i=0;i<26;i++)
{
if(freq[i]!=0)//printing only those alphabets whose count is not '0'
System.out.println(" "+alph[i]+"\t\t "+freq[i]);
}
}
}

Output
Enter any string
ilovejavaforschool

Output:
******
Alphabet

Frequency
******

a
c
e
f
h
i
j
l
o
r
s
v

2
1
1
1
1
1
1
2
4
1
1
2

Result
Thus the above program has been executed successfully and the output
has
been verified

46
Brindavan Public School-Coonoor

String Manipulation
Question 17 :
Write a program to accept a sentence and print only the first
letter of the
sentence in capital letters separated by a fullstop
Aim :
To write a program to print the first letter of each word in a given
sentence
Algorithm to print the first letter of each word
Step 1: Start
Step 2: Create a class named Initials
Step 3: Within the main function declare all the required variables
Step 4: Enter a string and store it in s
Step 5: Add space in front of the inputted sentence
Step 6: Convert the string to Uppercase using function toUpperCase()
Step 7: Calculate the length of the sentence using length()
Step 8: For printing the output take out one character at a time
Step 9: If the character is a space then print the next character along
with a
fullstop
Step 10: The desired output is printed
Step 11: Stop.

Program to print the first letter of each word of the sentence

import java.io.*;
class Initials
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.println("Enter the Sentence");
s=in.readLine();
s=" "+s;//adding a space infront of the sentence
s=s.toUpperCase();//converting the string into upper case
l=s.length();//finding the length of the string
System.out.print("Output = ");
for(int i=0;i<l;i++)
{
x=s.charAt(i);//taking out one character at a time from the sentence
if(x==' ')//if the character is a space, printing the next character along with a
fullstop
System.out.print(s.charAt(i+1)+".");
}
}
}

Output
Enter the Sentence
this is my project
Output = T.I.M.P.

Result
Thus the above program has been executed successfully and the output
has
been verified

48
Brindavan Public School-Coonoor

Longest and Shortest word in a Sentence

Question 18 :
Write a program to find the shortest and longest word in a
sentence and
print them along with their length
Aim :
To find the shortest and longest word in a given sentence
Algorithm to determine longest and shortest word in a sentence
Step 1: Start
Step 2: Create a class named Short_Long_Word
Step 3: Within the main function declare all the required variables
Step 4: Enter a string and store it in s
Step 5: Add a space at the end of the string, to extract the last word
also
Step 6: Calculate the length of the sentence using length() and store it
in l
Step 7: Initialize variables x, maxw, minw as null using string data
type
Step 8: Using for loop extract the chracters of the string
Step 9: If the characters extracted is not a blank space then add the
characters to the variable x
Step 10: If the character extracted is a blank space then check the
word for
maximum and minimum length
Step 11: If the length of the word is less than the minimum length
then store

the word in minw


Step 12: If the length of the word is more than the minimum length
then store
the word in maxw
Step 13: Print the longest word and its length
Step 14: Print the shortest word and its length
Step 15: Stop.

Program to print the first letter of each word of the sentence


import java.io.*;
class Short_Long_Word
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Sentence");
String s=in.readLine();
s=s+" ";//adding a space at the end of the sentence

s=s.toUpperCase();//converting the string into upper case


int l=s.length();//finding the length of the string
String x="",maxw="",minw="";
char ch;
int p,maxl=0,minl=l;
for(int i=0;i<l;i++)
{
ch=s.charAt(i);//extracting characters of the string one at a time
if(ch!=' ')
{
x=x+ch;//adding characters to form word if characters is not space
}
else
{
p=x.length();
if(p<minl)//checking for minimum length
{
minl=p;
minw=x;
}
if(p>maxl)//checking for maximum length
{
maxl=p;
maxw=x;
}
x="";//emptying the temporary variable to store next word
}
}
System.out.println("Shortest word = "+minw+"\nLength = "+minl);
System.out.println("Longest word = "+maxw+"\nLength = "+maxl);
}
}

Output
Enter the Sentence
I am learning java
Shortest word = I
Length = 1
Longest word = LEARNING
Length = 8

Result
Thus the above program has been executed successfully and the output
has
been verified

51
Brindavan Public School-Coonoor

Encoding a Word into a Piglatin word

Question 19 :
Write a program that encodes a word into Piglatin word. To
translate a
word into a piglatin word, convert the word into uppercase and then
place
the first vowel of the original word as the start of the new word along
with
the remaining alphabets. The alphabets present before the vowel
being
shifted towards the end followed by AY
Aim :
To write a program to translate a word into a Piglatin word
Algorithm to encode a word into a piglatin word
Step 1: Start
Step 2: Create a class named Piglatin
Step 3: Within the main function declare all the required variables
Step 4: Enter a string and store it in s
Step 5: Change the word to capital letters using toUpperCase()
function
Step 6: Store the position of the first vowel in the word pos
Step 7: Extracting all alphabets in the word beginning from the first
vowel
using the function s.substring(pos)
Step 8: Extract the alphabets present before the first vowel using the
function

s.substring(0,9)
Step 9: Add AY at the end of the extracted words after joining them
Step 10: Print the Piglatin word
Step 11: Stop.
Program to print the first letter of each word of the sentence
import java.io.*;
class Piglatin
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String");
String s=in.readLine();
s=s.toUpperCase();//converting the string into upper case
int l=s.length();//finding the length of the string
char ch;
int pos=0;
for(int i=0;i<l;i++)
{
ch=s.charAt(i);
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
{
pos=i;//storing the index of the first vowel
break;
}
}
String a=s.substring(pos);//enxtracting all alphabets in the word begining from thw
first
vowel
String b=s.substring(0,pos);//extracting the alphabets present before the firts vowel

String pig=a+b+"AY";//adding "AY" at the end of the extractd words after joining
them
System.out.println("The Piglatin of the word = "+pig);
}
}

Output
Enter the String
computer
The Piglatin of the word = OMPUTERCAY

Result
Thus the above program has been executed successfully and the output
has
been verified

53
Brindavan Public School-Coonoor

Difference between Two Matrices

Question 19 :
A class Matrix contains a two dimensional integer array of order
[m x n].
The maximum value possible for both m and n is 25. Design a class
Matrix
to find the difference of the matrices. The details of the members of
the class
are given below
Class name: Matrix
Data members/instance variables
arr[][]: store the matrix elements
m: integer to store the number of rows
n: integer to store the number of columns
Member function:
Matrix(int mm, int nn): To initialize size of the matrix
void fillarray(): to enter the elements of the matrix
Matrix SubMat(Matrix A): subtract the current object from
the
matrix of the parameterized object and return the resulting
object
void display (): display the matrix elements
Specify

the

class

Matrix

giving

details

of

the

constructor, void
filarray(), Matrix SubMat() and void siplay(). Define the main()
function to
create objects and call function accordingly to enable the task

Aim :
To design a class Matrix to find the difference of the matrices
Algorithm to determine difference between two matrices
Step 1: Start
Step 2: Create a class named Matrix and within the class declare an
double
dimensional array named arr[][]
Step 3: Create a parameterized constructor named Matrix() and pass
the
arguments mm, nn
Step 4: Store the values of the array arr[][]
Step 5: Create a function SubMat() calling the object matrix from
matrix A
Step 6: Create an object c for storing the resultant matrix
Step 7: subtract the Matrix A from the object matrix using the this
keyword
which will call function SubMat(Matrix)
Step 8: Return the resultant matrix using the return keyword
Step 9: Create a function display() for displaying the resultant matrix c
Step 10: Create the main function
Step 11: Within the main function enter the row and column limit
Step 12: If the row value or the column value is greater then 25 then
print
Out of Range
Step 13: Create the first matrix x using the matrix(r, c) function
Step 14: Create the second matrix y using the matrix(r, c) function

Step 15: Create the third matrix z using the matrix(r, c) function
Step 16: Enter the elements for the first matrix using the x.fillarray()
function
Step 17: Enter the elements for the second matrix using the y.fillarray()
function
Step 18: Display both the matrixes using the display () function
Step 19: Call the x.SubMat(y) for subtracting both the matrices
Step 20: Display the resultant matrix using z.display() function
Step 21: Stop.
Program to find the difference between two matrices
import java.io.*;
class Matrix
{
static BufferedReader in=new BufferedReader (new InputStreamReader(System.in));
int arr[][];
int m,n;
Matrix(int mm, int nn) //parameterised constructor
{
m=mm;
n=nn;
arr=new int[m][n];
}
void fillarray()throws IOException //function for inputting the values in the Matrix
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print("Enter Element at ["+i+"]["+j+"]:");
arr[i][j]=Integer.parseInt(in.readLine());

}
}
}
Matrix SubMat(Matrix A)
Matrix C=new Matrix(m,n); //Object for storing the result
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
C.arr[i][j]=A.arr[i][j]-this.arr[i][j]; //keyword 'this' is referring to the object which will
call the
function SubMat(Matrix)
}
}
return C;
}
void display()//function for displaying the Matrix
{
for(int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
public static void main()throws IOException
{
System.out.print("Enter the number of Rows:");//Inputting Number of Rows
int r=Integer.parseInt(in.readLine());
System.out.print("Enter the number of columns:");//Inputting Number of Columns
int c=Integer.parseInt(in.readLine());

if(r>25|| c>25)
System.out.println("Out of Range");
else
{
Matrix X=new Matrix(r,c);//The 1st Matrix
Matrix Y=new Matrix(r,c);//The 2nd Matrix
Matrix Z=new Matrix(r,c);//The Resultant Matrix
System.out.println("\nEnter the 1st Matrix");//Inputting 1st Matrix by calling the
function
fillarray()
X.fillarray();
System.out.println("\nEnter the 2nd Matrix");//Inputting 2nd Matrix by calling
the
function fillarray()
Y.fillarray();
System.out.println("\nEnter the 1st Matrix");//Inputting 1st Matrix by calling
the function
display()
X.display();
System.out.println("\nEnter the 2nd Matrix");//Inputting 2nd Matrix by calling
the
function display()
Y.display();
Z=X.SubMat(Y);
/*Calling the function SubMat()using the object'X'in order to subtract the
values of
Matrix X from Matrix Y*/
System.out.println("\nThe Resultant Matrix");//Displaying the resultant Matrix by
calling the
function display()
Z.display();
}

}
}

Output
Enter the number of Rows:2
Enter the number of columns:3
Enter the 1st Matrix
Enter Element at [0][0]:15
Enter Element at [0][1]:2
Enter Element at [0][2]:4
Enter Element at [1][0]:53
Enter Element at [1][1]:19
Enter Element at [1][2]:37
Enter the 2nd Matrix
Enter Element at [0][0]:11
Enter Element at [0][1]:50
Enter Element at [0][2]:3
Enter Element at [1][0]:9
Enter Element at [1][1]:45
Enter Element at [1][2]:8
Enter the 1st Matrix
15
53

19

37

Enter the 2nd Matrix


11

50

45

The Resultant Matrix


-4

48

-1

-44

26

-29

Result
Thus the above program has been executed successfully and the output
has
been verified

57
Brindavan Public School-Coonoor

Matrix Multiplication

Question 21 :
A class MatrixMultiplication contains a two dimensional integer
array of
order[m x n]. The maximum value for both m and n is 25. Design a
class
MatrixMultiplication to find the product of two matrices.
Aim :
To design a class matrix to find the product of the matrices
Algorithm to execute matrix multiplication
Step 1: Start
Step 2: Create a class named MatrixMultiplication
Step 3: Within the main function declare all the required variables
Step 4: Enter and store the number of columns and rows of matrix A
in the
variables columnsInA and rowsInA
Step 5: Enter and store the number of columns and rows of matrix B
in the
variables columnsInA and columns in B
Step 6: Create a double dimensional array named a and b
Step 7: Enter the elements of the matrix a and b
Step 8: Create another matrix named c for storing the product of
matrix A
and Matrix B
Step 9: Create a main function named multiply(a,b) for multiplying
both the

matrices
Step 10: Within the function multiply() multiply both the matrices
using the
formula c[i][j]=c[i][j]+a[i][k]*b[k][i]
Step 11: Print the product of both the matrices
Step 12: Stop.
Program to find the product of two matrices
import java.util.*;
class MatrixMultiplication
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(Enter number of rows in A);
int rowsInA=s.nextInt();
System.out.println(Enter the columns in A/rows in B);
int columnsInA=s.nextInt();
System.out.println(Enter the columns B);
int columnsInB=s.nextInt();
int [][] a=new int[rowsInA][columnsInB];
int [][] b=new int[columnsInB][columnsInB];
System.out.println(Enter matrix A);
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
a[i][j]=s.nextInt();
}
}
System.out.println(Enter matrix B);

for(int i=0;i<b.length;i++)
{
for(int j=0;j<b[0].length;j++)
{
b[i][j]=s.nextInt();
}
}
int[][]c=multiply(a,b);
System.out.println(The product of A and B is);
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
System.out.print(c[i][j]+ );
}
System.out.println();
}
}
public static int[][] multiply(int[][] a,int[][] b)
{
int rowsInA=a.length;
int columnsInA=a[0].length;
int columnsInB=b.length;
int[][] c=new int[rowsInA][columnsInB];
for(int i=0;i<rowsInA;i++)
{
for(int j=0;j<columnsInB;j++)
{
for(int k=0;k<columnsInA;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}

}
return c;
}
}

Output
Enter number of rows in A
2
Enter the columns in A/rows in B
3
Enter the columns B
2
Enter matrix A
3
4
5
6
Enter matrix B
7
8
9
4
The product of A and B is
57 40
89 64

Result
Thus the above program has been executed successfully and the output

has
been verified

60
Brindavan Public School-Coonoor

Denomination of an Input Amount

Question 22 :
A bank intends to design a program to display the denomination
of an
input amount up to 5 digit. The available denomination with the bank
are of
rupees 1000, 500, 100, 50, 20, 10, 5, 2, 1. Design a program to accept
the
amount from the user and display the break up in descending order of
denomination along with the total number of notes.
Aim :
To design a program to accept the amount and display the breakup in
descending order of denomination, along with the total number of
notes.
Algorithm to determine denomination of an input amount
Step 1: Start
Step 2: Create a class named Denominations
Step 3: Within the main function declare all the required variables
Step 4: Create an array[] named den and store all the denominations
in the
array
Step 5: Enter the amount and store the amount in the variable
amount
Step 6: Make a exact copy of the amount and store it in copy
Step 7: Initialize the variables totalNotes=0 and count=0

Step 8: Since there are 9 different types of notes, hence check for
each note
Step 9: Count the number of denominations for each note
Step 10: Print the denominations if the count is not equal to 0
Step 11: Print the result
Step 12: Stop.
Program to print the Denominations of the input amount
import java.io.*;
class Denominations
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int den[]={1000,500,100,50,20,10,5,2,1};//storing all the denominations in an array
System.out.println(Enter any Amount);//entering an amount
int amount=Integer.parseInt(in.readLine());
int copy=amount;//making a copy of the amount
int totalNotes=0,count=0;
System.out.println(\nDENOMINATIONS\n);
for(int i=0;i<9;i++)//since there are 9 different types of notes,hence we check for
each
note
{
count=amount/den[i];//counting number of den[i] notes
if(count!=0)//printing that denomination if the count is not zero
{
System.out.println(den[i]+\tx\t+count+\t= +den[i]*count);
}
totalNotes=totalNotes+count;//finding the total number of notes
amount=amount%den[i];//finding their remaining amount whose

denominations is to be
found
}
System.out.println(________________________________);
System.out.println(Total\t\t\t= +copy);//printing the total
System.out.println(________________________________);
System.out.println(Total number of notes\t= +totalNotes);//printing the total
number of
notes
}
}

Output
Enter any Amount
189272
DENOMINATIONS
1000

189

= 189000

100

= 200

50

= 50

20

= 20

=2

________________________________
Total

= 189272

________________________________
Total number of notes

= 194

Result
Thus the above program has been executed successfully and the output
has
been verified

62
Brindavan Public School-Coonoor

ISBN Code Checking for a Book

Question 23 :
An ISBN is a ten digit code which uniquely identifies a book. The
first nine
digits represent the Group, Publisher and Title of the book and the last
digit is
used to check whether ISBN is correct or not. Each of the first nine digits
of
the code can take a value between 0 and 9. Create a class to check
whether
the entered code is ISBN or not. A code is ISBN if the sum of the digits
leaves
no remainder when divided by 11.
Aim :
To check whether the entered code is ISBN or not
Algorithm to determine the validity of ISDN code
Step 1: Start
Step 2: Create a class named ISBN
Step 3: Within the main function declare all the required variables
Step 4: Enter the 10 digit ISBN code and store it as string data type in
s
Step 5: Calculate the length of the code entered using the length()
function
and store it in len
Step 6: If the length is less than 10 then display that the input is
invalid

Step 7: To verify if the ISBN code is valid or not calculate 10 times the
first
digits, plus 9 times the second digit, plus 8 times the third digit
and so
on until we add 1 time the last digit
Step 8: If the final number(i.e. the sum of all the digits) leaves no
remainder
when divided 11 then print the code is valid ISBN
Step 9: Stop.
Program to check if the ISBN code is valid or not
import java.io.*;
class ISBN
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter a 10 digit code);
String s=in.readLine();
int len=s.length();
if(len!=10)
{
System.out.println(Input Invalid...);
}
else
{
char ch;
int dig=0,sum=0,k=10;
for(int i=0;i<len;i++)
{

ch=s.charAt(i);
if(ch==X)
dig=10;
else
dig=ch-48;
sum=sum+dig*k;
k--;
}
System.out.println(Output:Sum = +sum);
if(sum%11==0)
System.out.println(Leaves No Remainder-Valid ISBN Code);
else
System.out.println(Leaves Remainder-Invalid ISBN Code);
}
}
}

Output
Enter a 10 digit code
1876901810
Output : Sum = 264
Leaves No Remainder-Valid ISBN Code

Result
Thus the above program has been executed successfully and the output
has
been verified

64
Brindavan Public School-Coonoor

Perimeter of parallelogram using Inheritance

Question 24 :
A superclass Perimeter has been defined to calculate the
perimeter of a
parallelogram. Define a subclass Area to compute the area of the
parallelogram by using the required data members of the superclass.
The
details are given below
Class name: Perimeter
Data members / instance variables:
a: to store the length in decimal
b: to store the breadth in decimal
Member functions:
Perimeter(): Parameterized constructor to assign values to data
members
double Calculate(): Calculate and return the perimeter of a
parallelogram
as 2*(length+breadth)
void show (): to display the data members along with the
perimeter
Class name: Area
Data members/instance variables:
h: to store the height in decimal
area: to store the area of the parallelogram
Member functions
Area(): Parameterized constructor to assign values to data members
of

both the classes


void doarea (): compute the area as (breadth*length)
void show (): displays the data members of both the classes
Specify the class Perimeter giving details of all the member methods
of
superclass. Using the concept of inheritance, specify the class Area
giving
details of all its member functions
Aim :
To define a super class Perimeter to calculate the perimeter of
parallelogram and a subclass Area to compute the area of the
parallelogram by
using the required data members from the super class.

Algorithm to determine perimeter and area using inheritance


Step 1: Start
Step 2: Create a super class named Perimeter
Step 3: Within the super class create a constructor function named
Perimeter() and pass the arguments x, y
Step 4: Create another function called Calulate() to calculate the
perimeter of
the parallelogram
Step 5: Create a function named show() to display the length, breadth

and
perimeter of the parallelogram
Step 6: Create another subclass named Area and inherit all the
properties of
the super class Perimeter using the keyword extends
Step 7: Create a constructor function named Area() and pass the
arguments
x, y, z
Step 8: Create another function named doarea() to calculate the area
of the
parallelogram
Step 9: Create another function named show() for calling the super
class
Step 10: Print the area and perimeter of the parallelogram using the
main
function
Step 11: Stop.

Program to calculate the perimeter and area of parallelogram


using inheritance
import java.io.*;
class Perimeter//superclass
{
double a,b;
Perimeter(double x,double y)
{
a=x;
b=y;

}
double Calculate()
{
double p=2*(a+b);
return p;
}
void show()
{
System.out.println(Length = +a);
System.out.println(Breadth = +b);
System.out.println(Perimeter = +Calculate());//printing perimeter by calling
Calculate()
}
}//end of superclass Perimeter

class Area extends Perimeter//subclass


{
double h,area;
Area(double x,double y,double z)
{
super(x,y);//initializing data memebers of superclass by calling its constructor
h=z;
}
void doarea()
{
area=b*h;
}
void show()
{
super.show();//calling the superclass function show()
System.out.println(Height = +h);
System.out.println(Area = +area);

}
}//end of subclass
public class Main
{
public static void main()throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println(Enter the Length);
double x=Double.parseDouble(in.readLine());
System.out.println(Enter the Breadth);
double y=Double.parseDouble(in.readLine());
System.out.println(Enter the Height);
double z=Double.parseDouble(in.readLine());
Area ob=new Area(x,y,z);//creating object of subclass
System.out.println(***OUTPUT***);
ob.doarea();
ob.show();//calling show() function of subclass
}
}

Output
Enter the Length
3

Enter the Breadth


5
Enter the Height
7
***OUTPUT***
Length = 3.0
Breadth = 5.0
Perimeter = 16.0
Height = 7.0
Area = 35.0

Result
Thus the above program has been executed successfully and the output
has
been verified

68
Brindavan Public School-Coonoor

Mark list for 50 Students

Question 25
A super class record has been defined to store the names and ranks
of 50
students. Define a sub class rank to find the highest rank with the
name. The
details of both classes are given below:
Class name: record
Data members / instance variables:
Name []: to store the names of the students
Rnk []: to store the ranks of the students
Member functions:
Record (): constructor to initialize data members
void readvalues (): to store name and ranks
void display (): displays the names and corresponding ranks
Class name: rank
Data members/instance variables:
index: integer to store the index of the topmost rank
Member functions
Rank (): constructor to invoke the base class constructor and to
initialize
index to 0.
void highest (): finds the index location of the topmost rank and
stores it in
index without sorting the array 6
void display (): displays the name and ranks along with the
topmost rank
Specify the class record giving details of void display (), void

readvalues(),
constructor(). Using the concept of inheritance, specify the class rank
giving
details of constructor (), void highest (), and void display ().
Aim:
To define a super class record to store the names and ranks of 50
students
and to define a sub class rank to find the highest rank along with the
name

Algorithm
Step 1: Start
Step 2: create a super class name record and declare all the required
variables
Step 3: Create an array for storing the name and rank of all the
students as
name [] and rnk []
Step 4: Create a constructor named record () and store the size of the
array
as 50
Step 5: Create a function name readvalues () and enter the names and
ranks
of 50 students in respective arrays
Step 6: Create another class named display () and display the name
and rank

of 50 students
Step 7: Create another class named as rank which inherits all the
properties
of super class record using the keyword extends
Step 8: Within the constructor rank () invoke the constructor super ()
of the
super class
Step 9: Create a function highest () and sort the array rnk in
descending order
Step 10: Create a function display () and call the super class function
display
Step 11: With in the main function create an object ob for the subclass
Step 12: Using the object ob call the readvalues () function of
superclass to
input the names and ranks
Step 13: Using the object ob call the function highest () for finding the
index of
topmost rank
Step 14: Using the object ob call the function display for displaying the
display function of super class
Step 15: Stop
Program to input marks of 50 students and print the result
import java.io.*;
class Record //superclass
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String name[];

int rnk[];
Record()
{
name = new String[50];
rnk = new int[50];
}
void readvalues()throws IOException
{
System.out.println("*** Inputting The Names And Ranks ***");
for(int i=0;i<50;i++)
{
System.out.print("Enter name of student "+(i+1)+" : ");
name[i]=br.readLine();
System.out.print("Enter his rank : ");
rnk[i]=Integer.parseInt(br.readLine());
}
}
void display()
{
System.out.println("NamettRank");
System.out.println("-------tt-------"); //this is just for styling the output. You can
skip it !
for(int i=0;i<50;i++)
{
System.out.println(name[i]+"tt"+rnk[i]);
}
}
} //end of superclass Record
class Rank extends Record //subclass
{
int index;
Rank()

{
super(); //invoking the constructor of superclass
index = 0;
}
void highest()
{
int min = rnk[0];
for(int i=0;i<50;i++)
{
if(rnk[i]<min)
{
index = i;
}
}
}
void display()
{
super.display(); //calling the superclass function display()
System.out.println("nTop most rank = "+rnk[index]);
System.out.println("Student with topmost rank = "+name[index]);
}
} //end of subclass Rank
public class MainObject //Class which will contain the main() method and execute
the
program
{
public static void main()throws IOException
{
Rank ob=new Rank(); //creating object of subclass
ob.readvalues(); //calling radvalues() function of superclass to input the names
and
ranks
ob.highest(); //calling the function highest() for finding index of topmost rank

System.out.println("*** Output ***");


ob.display(); //calling display() function of subclass
}
}

Output
Enter the Length
3
Enter the Breadth
5
Enter the Height
7
***OUTPUT***
Length = 3.0
Breadth = 5.0
Perimeter = 16.0
Height = 7.0
Area = 35.0

Result
Thus the above program has been executed successfully and the output
has
been verified

72
Brindavan Public School-Coonoor

S-ar putea să vă placă și