ICSE Computer Project

Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

ICSE Computer

Project

Assigned by Mrs. D.B.Flynn,

Name: Agnibho Guru


Class: X-A
Roll Number- 5.
Registration Number-12224
Index
● Hotel Reservation Mini Software

Programs:

1)Palindrome Strings
2)Kaprekar Numbers
3)Line in Lowercase
4)Word Anagrams
5)Name
6)Happy Number
7)String Permutations
8)Frequency of a Letter
9)Circular and Co-prime
10)Time Period
11)Square-free Number
12)Processing a Number
13)Duplicate elements in an array.
14)Amicable Numbers.
15)Customizing an Array.
16)Areas of Geometrical Figures
17)Student Subjective Makrs
18)Student Ranking Record
19)Separation of Digits
20)Patterns
Introduction

To the reader, a hearty welcome. This project has been in the


works for hundreds of hours, and is the result of countless
sleepless nights. It does a great job in summing up the things I
learnt throughout the year, and I believe that although the
difficulty in programs here is quite mediocre, it is a perfect
guide to any student who wishes to obtain a bunch of
programs that one will enjoy doing, as well as learn a lot from.
Starting from the mini-software, which took an eternity to get
right, to the program to customize an array, I have done my
best to compile a few of the delightful programs I have done in
the extremely hot afternoons of summer, rainy evenings in the
monsoon, and cold nights in winter. I hope the reader
thoroughly enjoys themself while going through this(very) long
project.
Mini-Software

Topic: Hotel Reservation Software

Source Code:
import java.util.*;
public class Hotel_Management
{ Scanner sc= new Scanner(System.in);
int days, room;
boolean Type[];
String date, name, gen, occp, add, pur, rname, email;
int adults, child, no;
double bill;
boolean breakfast;
//all the various variables are initialized.
public static void main()
{
Hotel_Management ob=new Hotel_Management();
ob.input();
ob.roomBook();
ob.registration();
ob.billCalc();
}

public void input()

{
//This is simply done to make the WELCOME page more flashy, purely done because
of the ample amount of time I seem to have.
System.out.print(" ");
System.out.println(" # # ####### ####### ####### # ######
####### ###### ##### ####### # ###### ");
System.out.print(" "); System.out.println(" # # # # # # # #
## # # # # # # # # # ");
System.out.print(" "); System.out.println(" # # # # # # # #
## # # # # # # # #");
System.out.print(" "); System.out.println(" ####### # # # #####
# ###### ##### # # ##### # # # ######");
System.out.print(" "); System.out.println(" # # # # # # # #
# # # # # # ####### # # ");
System.out.print(" "); System.out.println(" # # # # # # # #
# # # # # # # # # # # ");
System.out.print(" "); System.out.println(" # # ####### #
####### ####### # # ####### ###### ##### # # # #
");
System.out.println();
//prints a design with HOTEL RED STAR written.
System.out.println(" ^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^ ");
System.out.println(" MARUNOUCHI TRUST TOWER MAIN, 1 Chome-8-3
Marunouchi, Chiyoda City, Tokyo 100-8283, Japan ");
System.out.println();
System.out.println("Dear customer,");
System.out.println("A warm welcome to our online booking site,for the greatest hotel
in Tokyo,");
System.out.println("built in the year 1967, dedicated to the rich cultural history of our
country ");
System.out.println("At Hotel Red Star, we bring to you absolut ely modern living in
utmost comfort, ");
System.out.println("amidst the fragrance of our glorious heritage.");
System.out.println();
System.out.println("Be you a native weekend tourist, or be you an international tourist
coming ");
System.out.println("to witness the wonders of Japan, be assured that we will take up
the ");
System.out.println("responsibity of making your stay a memorable one.");
System.out.println();
System.out.println("Do you want to book a room in our grand hotel?");
System.out.println("Please reply in Yes or No: ");
if((sc.nextLine()).equalsIgnoreCase("Yes"))
{
System.out.println();
System.out.println("Please state your date of visit, and the number of days you
intend to stay");
System.out.print("Date: ");
date=sc.nextLine();
System.out.print("Number of days: ");
days=sc.nextInt();
}
else
{
System.out.println("Thank you for visiting the website of Hotel Red Star, Tokyo!");
System.exit(0);
}

}
public void roomBook()
{
boolean King[]=new boolean[5];
boolean Queen[]= new boolean[5];
boolean AC[]= new boolean[15];
boolean Non[]= new boolean[15];
King=randomFiller(King);
Queen=randomFiller(Queen);
AC=randomFiller(AC);
Non=randomFiller(Non);
System.out.println("Please select the type of room you prefer. ");
System.out.println("1. King Suite");
System.out.println("2. Queen Suite");
System.out.println("3. AC Deluxe");
System.out.println("4. Non-AC Deluxe");
Hotel_Management object=new Hotel_Management() ;
System.out.println("Do you wish to obtain a description of the rooms?( Answer with a
Yes or a No)");
sc.nextLine();
String s=sc.nextLine();
//program statements do a good job at replacing comments, to make the user
understand the function of each part.
if(s.equalsIgnoreCase("yes"))
{
System.out.print("Which one do you wish to obtain?");
System.out.print("The number corresponding to the room whose description you
want to obtain: ");
int option=sc.nextInt();
switch(option)
{
case 1:
if(object.king()==true)
{
Type= King;
rname="King Suite";
}
else
{
roomBook();//reruns the method.
}

break;
case 2:
if(object.queen()==true)
{
Type= Queen;
rname="Queen Suite";
}
else
{
roomBook();
}

break;
case 3:
if(object.ac()==true)
{
Type= AC;
rname="AC Deluxe";
}
else
{
roomBook();
}

break;
case 4:
if(object.non()==true)
{
Type= Non;
rname="Non-AC Deluxe";
}
else
{
roomBook();
}

break;
default:
System.out.println("INPUT IS INVALID!!! PLEASE RE-ENTER YOUR CHOICE. ");
roomBook();
}
}

else if(s.equalsIgnoreCase("no"))
{
System.out.print("Enter your choice of the preferred room: ");
int ch=sc.nextInt();
switch(ch)
{
case 1:
Type= King;
rname="King Suite";
break;
case 2:
Type= Queen;
rname="Queen Suite";
break;
case 3:
Type= AC;
rname="AC Deluxe";
break;
case 4:
Type= Non;
rname="Non-AC Deluxe ";
break;
default:System.out.println("Input is invalid! Plese re-enter your choice. ");
roomBook();
}
}
else
{
System.out.println("Your input is not valid, please try again.");
roomBook();
}
System.out.println("Single bed or double bed? ");
sc.nextLine();
String bed=sc.nextLine();
System.out.println("Checking for room availibilty.........");
for(long i=0; i<1599999999; i++); //A loop to imitate searching .
System.out.println("DONE!");
int cn;
System.out.println("Rooms available= 5");
for(int i=0; i<Type.length; i++)
{
if(bed.equalsIgnoreCase("single")||bed.equalsIgnoreCase("single bed"))
{
if(Type[i]==true&&i<=(Type.length/2))
{
System.out.println("Room "+(i+1));
room=i;
}
}
else if(bed.equalsIgnoreCase("double")||bed.equalsIgnoreCase("double bed"))
{
if(Type[i]==true&&i>(Type.length/2))
{
System.out.println("Room "+(i+1));
room=i;
}
}
}
System.out.println("We have assigned room "+(room+1)+" for you ");
System.out.println("Let us now proceed to the registration");
}

public boolean[] randomFiller(boolean A[]) //random room assignment is made here.


{
for(int i=0; i<A.length; i++)
{
int rand= (int)(Math.random()+0.5);
if(rand==1)
A[i]=true;
else if(rand==0)
A[i]=false;
}
return A;
}

void registration()
{
System.out.println();
System.out.println(" _________________________________________
__________________________________________________________
____________ _______________________");
System.out.println(" REGISTRATION "); System.out.println(" ''''''''''''''");
System.out.println(" _________________________________________
__________________________________________________________
____________ _______________________");
System.out.println(" ");
System.out.print("Name: ");
name=sc.nextLine();
System.out.print("Gender: ");
gen=sc.nextLine();
System.out.print("Residential Address: ");
add=sc.nextLine();
System.out.print("Occupation: ");
occp=sc.nextLine();
System.out.print("Purpose of visit: ");
pur=sc.nextLine();
System.out.print("Registered Email: ");
email=sc.nextLine();
System.out.print("Number of rooms booked: ");
no=sc.nextInt();
System.out.print("Total number of adults: ");
adults=sc.nextInt();
System.out.print("Total number of children(below 18): ");
child=sc.nextInt();
System.out.println("Do you wish to have complimentary breakfast (yes/no)? ");
//increases the cost, 'complimentary' was a lie.
sc.nextLine();
String bk=sc.nextLine();
System.out.println("Thank You for registering with Hotel Red Star,Tokyo! ");
breakfast=bk.equalsIgnoreCase("yes");
}

public void billCalc()


{
int rate=0;
if(rname.equals("King Suite"))
rate=8000;
else if(rname.equals("Queen Suite"))
rate=5000;
else if(rname.equals("AC Deluxe"))
rate=3000;

else if(rname.equals("Non-AC Deluxe"))


rate=2500;
int add=0,rent=rate*days;
if(adults>(no*2))
add=200*days;
if(child>(no))
add+=100*days;
if(breakfast)
{
add+=days*(adults+child)*200;
}
int gross=rent+add;
display(gross);
}

void display(int n)
{
System.out.println();
System.out.println(" __ ");
System.out.println(" |__) * | |");
System.out.println(" |__) | |__ |__");
System.out.println();
System.out.println(" HOTEL RED STAR ");
System.out.println(" ^^^^^^^^^^ ^^^^^^ ");
System.out.println();
System.out.println(" Room type: "+ rname);
System.out.println(" Room number= "+room);
System.out.println(" Customer Name: "+name);
System.out.println(" Total number of people= "+(adults+child));
System.out.println(" Date of check-in: "+date);
System.out.println(" Days stayed= "+days);
System.out.println();
System.out.println(" Gross amount= "+n);
double servtax=(5.0/100)*n;
double gst=(14.5/100)*(servtax+n);
bill=servtax+gst+n;
System.out.println(" Taxes= "+gst);
System.out.println(" Net amount= "+bill);
System.out.println();
System.out.print(" Please enter custom mode of payment: ");
String mode=sc.nextLine();
System.out.println(" Your booking has been confirmed!");
System.out.println(" An email regarding the details and payment credit
will be sent shortly to your registered email ID.");
System.out.println(" Thank You for choosing Hotel Red Star!");
}
// Will contain the descriptions of the rooms.
//When the user inputs his choice, a description will be available, which will be
accessible through this class.
public boolean king()
{
//the various descriptions of the rooms are given in this method.
boolean a=false;
System.out.println("KING SUITE");
System.out.println("");
System.out.println("The King Suite is for the very best of our guests. With world class
");
System.out.println("features, and excellent room décor, this suite is nothing short of ");
System.out.println("perfection, which is desired by many. The room is spacy, and the ");
System.out.println("cosiness of it makes one feel at home, albeit a more comfortable
and ");
System.out.println("more exquisite one. We assure you, that if this shall be your choice,
you ");
System.out.println("shall regret the day of your departure.");
System.out.println(""); System.out.println("Features");
System.out.println("^^^^^^^^^");
System.out.println("");
System.out.println("> 350x200 ft. room, large, spacy and comfortable");
System.out.println("> A gigantic Double-bed, with Spektron-technology custom made
");
System.out.println(" mattress, for a good nights sleep.");
System.out.println("> Air-conditioned, with two split A/Cs.");
System.out.println("> A 42 inch LG Smart TV");
System.out.println("> Two large sofas, a bedside table, and a coffee table");
System.out.println("> A long balcony, with a stunning view of the Tokyo Tower, as well
as the ");
System.out.println(" rest of Tokyo");
System.out.println("> A mini-bar, with an assortment of the finest elixirs of Japan");
System.out.println("> A huge bathroom, fit for a king.");
System.out.println("");
System.out.println("The cost for this room (exclusive of taxes ) is = Rs. 8000/day");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Do you want to choose this type?");
System.out.println("Enter 'Yes' to book, or 'No' to go back to the menu: ");
if(sc.nextLine().equalsIgnoreCase("yes"))
a=true;
System.out.println("");
return a;
}

public boolean queen()


{
boolean a=false;
System.out.println("QUEEN SUITE");
System.out.println("");
System.out.println("The Queen Suite has an extra touch of comf ort. The features
available ");
System.out.println("are generally associated with cosy lifestyle. The rooms are such
made ");
System.out.println("that we assure you that you shall have no problem in blending in
with ");
System.out.println("the feel of it. The atmosphere created by this room is a calm and
");
System.out.println("peaceful one, in contrast to the loudness of the King Suite. If a
quiet ");
System.out.println("stay is what you desire, we take pleasure in welcoming you to the
");
System.out.println("grandeur of this room.");
System.out.println("");
System.out.println("Features");
System.out.println("^^^^^^^^^");
System.out.println("");
System.out.println("> 320x220 ft. room, cosy with a home-made feel.");
System.out.println("> A perfectly home-like double bed, with a plush
Kamarov-protocol ");
System.out.println(" custom made mattress.");
System.out.println("> Air-conditioned, with a split A/C and a bedside A/C.");
System.out.println("> A 42 inch LG Smart TV.");
System.out.println("> Two large sofas, two bedside tables.");
System.out.println("> A round balcony, with a spectacular view of Tokyo.");
System.out.println("> A wine counter, with vintage wines of Japan");
System.out.println("> A cosy, marble-and-graphite bathroom");
System.out.println("");
System.out.println("The cost for this room (exclusive of taxes ) is = Rs. 5000/day");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Do you want to choose this type?");
System.out.println("Enter 'yes' to book, or 'no' to go back to the menu: ");
if(sc.nextLine().equalsIgnoreCase("yes"))
a=true;
System.out.println("");
return a;
}

public boolean ac()


{
boolean a=false;
System.out.println("A/C Deluxe");
System.out.println("");
System.out.println("The A/C Deluxe is the standard room for our hotel. With an
affordable ");
System.out.println("price, and unbelievable comfort, the rooms will exceed your ");
System.out.println("expectations. The ambience is a very touri st-friendly one, and the
room ");
System.out.println("will surely make your stay at Hotel Red St ar, a very memorable
one.");
System.out.println("");
System.out.println("Features");
System.out.println("^^^^^^^^^");
System.out.println("");
System.out.println("> 200x150 ft. room, fully air conditioned. ");
System.out.println("> Choice of single or double bed, with a soft, comfortable
mattress.");
System.out.println("> A 54 inch LG LED TV");
System.out.println("> A large sofa, centre table, bedside table");
System.out.println("> A balcony, with a spectacular view of Tokyo");
System.out.println("> A well-furnished bathroom.");
System.out.println("");
System.out.println("The cost for this room (exclusive of taxes ) is = Rs. 3000/day");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Do you want to choose this type?");
System.out.println("Enter 'yes' to book, or 'no' to go back to the menu: ");
if(sc.nextLine().equalsIgnoreCase("yes"))
a=true;
System.out.println("");
return a;
}
public boolean non()
{
boolean a=false;
System.out.println("Non A/C Deluxe");
System.out.println("");
System.out.println("Dont like canned air? Feeling natural? Don't worry! Hotel Red Star
");
System.out.println("offers you a special Non A/C Deluxe suite with open windows to
enjoy ");
System.out.println("the scenic beauty of Tokyo. The air here is as fresh as it can be, and
the ");
System.out.println("natural way of life will surely make you feel like a part of Tokyo.");
System.out.println("");
System.out.println("Features");
System.out.println("^^^^^^^^^");
System.out.println("");
System.out.println("> 150x150 ft. room.");
System.out.println("> Four large open-able windows.");
System.out.println("> Choice of single or double bed, with a s oft, comfortable
mattress.");
System.out.println("> A 32 inch LG LED TV");
System.out.println("> A large sofa, centre table, bedside table");
System.out.println("> A balcony, with a spectacular view of Tokyo");
System.out.println("> A well-furnished bathroom.");
System.out.println("");
System.out.println("The cost for this room (exclusive of taxes ) is = Rs. 2500/day");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Do you want to choose this type?");
System.out.println("Enter 'yes' to book, or 'no' to go back to the menu: ");
if(sc.nextLine().equalsIgnoreCase("yes"))
a=true;
System.out.println("");
return a; } }
VDT
Name Datatype Description
days int Variable stores the value the user inputs for the number of days of stay.
room int Variable stores the value the user inputs for the number of days of stay.
This variable changes length based on the details of the room the user
Type[] boolean books,and is used while assigning a room
date String This variable stores the date the user wants to arrive.
name String This variable stores the name of the user, inputted by the user.
gen String This variable stores the gender of the user,inputted by the user.
occp String This variable stores the occupation of the user,inputted by the user.
add String This variable stores the residential address of the user.
pur String This variable stores the purpose of visit of the user,inputted by the user.
rname String Stores the name of the room that the user chooses to book.
email String This variable stores the email of the user,inputted by the user.
adults int This variable stores the number of adults visiting the hotel, inputted by the user.
This variable stores the number of children visiting the hotel, inputted by the
child int user.
no int This variable stores the number of rooms booked by the user.
bill double This variable stores the net amount in the bill.
breakfast boolean This variable changes value according to the user deciding to have breakfast.
bed String Variable stores the user input when the choice of beds is given.
Hotel_Man
ob agement Object of the class Hotel_Management.
King[] boolean Boolean array used in the assignment of a king sized room.
Queen[] boolean Boolean array used in the assignment of a queen sized room.
AC[] boolean Boolean array used in the assignment of an AC room.
Non[] boolean Boolean array used in the assignment of a NON AC room.
Hotel_Man
object agement Object of the class Hotel_Management.
Variable storing yes or no input of the user, inquiring whether they wanted
s String description of the rooms.
This variable is used in the switch case, storing the option the user chooses
option int when they need a description.
This variable is also used in the switch case, storing the option the user
ch int chooses.
i long Loop control variable to imitate a search.
i int Loop control variable.
This variable randomly obtains a number, which is then used as the room
rand int number assigned.
bk String This string obtains user input on whether they would like to have breakfast.
rate int This is the rate of the room which the user selects.
This variable covers extra cost, such as increasing the quantity of adults or
add int children.
rent int This variable stores the cost for the hotel room for the required number of days.
gross int This variable calculates the gross amount for the stay.
servtax double This variable stores the value of service tax by the hotel.
gst double The GST on the amount in the bill.
Variable remains false unless the user decides to book the type of room the
a boolean variable 'a' is represented in.
Java Terminal Window
--------x--------
Programs
Q1) Write a program to use method overloading to check if a user
inputted number is palindrome, along with a string, also inputted
by the user.

Source Code:

import java.util.*;
class Palindrome
{
public boolean isPalindrome(int n)//this is to check if a number is palindrome
{
int rev=0;
int copy=n;
while(copy!=0)//reverses the number
{
rev=(rev+copy%10)*10;
copy/=10;
}
rev/=10;
if(rev==n)//checks if the reversed number is equal to the original.
return true;
return false;
}

public boolean isPalindrome(String s)//this method checks if the string is palindrome


{
String rev="";
char c=0;
for(int i=s.length()-1;i>=0;i--)//extracts the characters of the string, and creates a new
string which is a reversed version of the original.
{
c=s.charAt(i);
rev=rev+c;//the characters are added to a new string
}
if(rev.equalsIgnoreCase(s)) //equalsIgnoreCase is to compare the two strings without
taking the 'case' of the letters into account.
return true;
return false;
}

public static void main()


{
Scanner sc=new Scanner (System.in);//scanner input is taken
System.out.println("Enter a word: ");
String s=sc.nextLine();
System.out.println("Enter a number: ");
int n=sc.nextInt();
Palindrome ob=new Palindrome();
//method overloading is used here.
{
if(ob.isPalindrome(n))
System.out.println("It is a palindrome number.");
else
System.out.println("It is not a palindrome number.");
}
{
if(ob.isPalindrome(s))
System.out.println("It is a palindrome word.");
else
System.out.println("It is not a palindrome word.");
}
//case appropriate statements are printed and the program terminates.
}
}
VDT

Name Datatype Description


rev int Variable storing value of the number after its digits are reversed.
copy int This variable stores the copied value of the original number.
c char This variable goes through, and temporarily stores all the characters of the string s.
i int Loop control variable, helping c go through all the characters of string s.
n int This variable stores the user input for the number they wish to check.
s String This string stores the user input for the word they wish to check.
ob Palindrome Object of class Palindrome.

Java Terminal Window


Q2) Write a program to check if a number is a Kaprekar Number.
Note: A Kaprekar number is a natural number in a given number base,
such that its square in that base can be split into two parts, the second part
having the same number of digits as the original number, that add up to the
original number.

Example: 77772 = 60481729


7777 = 6048+1729
Hence, 7777 is a Kaprekar number.

Source Code:

import java.util.*;
class Kaprekar
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number: " );
int n=sc.nextInt();
int sq=n*n; //takes the square of said number.
double copy=n;
int sum=0;
double count=0.0;
while(n>0)
{
n/=10;
count++;
}
double k= Math.pow(10.0,count);//done to divide the square to parts , with the second
part having the same number of digits as the original number.
int s=(int)k;
while(sq>0)//loop to calculate the sum of the two parts of the number.
{
sum=sum+(sq%s);
sq/=k;
}

if(copy==sum)//if the sum of the parts equal to the original number.


{
System.out.println("This number is a Kaprekar number.");
}
else
{
System.out.println("This number is not a Kaprekar number.");
}
}
}

VDT

Name Datatype Description


n int User inputted value for a number.
sq int The square of the number inputted by the user is stored by this variable .
copy double Stores the value of the original number.
sum int This variable is to store the sum of the two parts of the number.
count double Variable to count the number of digits in the original number.
Variable which is used to store an exponential value of 10, used to obtain parts
k double of the original number.
s int Stores the integer value of k.
Java Terminal Window

First Case:

Second Case:
Q3) Write a program to input a line using uppercase letters, and
convert the letters into lowercase, except for the first letter of
each word.

Source Code:

import java.util.*;
class Lowercase_Line
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a line in uppercase letters: ");
String str=sc.nextLine(); //this is the original string
String k="";
char c=0;
int a=0;
int p=0;
char temp=0;
System.out.println();
for(int i=0;i<str.length();i++)//this is a loop to go through all the characters of the
string.
{
//the line that is entered should be in uppercase, and should only contain letters in
the alphabet with a full stop or a comma.
c=str.charAt(i);
if(c==',') //detects a comma in the string.
{
//Not adding a space after the comma, as one normally should, disrupts the
functionality.
k=k+',';
continue;
}
if(c=='.')
{
k=k+'.';
continue;
}
a=(int)c+32;
temp=(char)a;
if(c==' ') //when it detects a space, a space is added, and the first letter is not
converted to lowercase.
{
p=i+1;
k=k+' ';
continue;
}
else if(p==i) //this lets the first letter of each word remain uppercase.
{
k=k+c;
continue;
}
k=k+temp; //this is the usual function where the letters get converted to lowercase.
}
System.out.print("The processed line is: "+k);//the processed string is printed.
}
}
VDT
Name Datatype Description
c char This variable goes through all characters of a string.
a int This variable stores the integer value of each character in the string, in lowercase.
p int This variable helps in skipping the first letter of each word when processing the line.
This variable stores the lowercase value of each letter in the line, and adds it after
temp char processing.
i int Loop control variable for loop which passes the value of each character of the string.

Java Terminal Window


Q4) Write a program to input two words using lowercase letters
and check if they are anagrams of each other.

Source Code:
import java.util.*;
class Anagram
{
public boolean isAnagram(String s,String str)
{
char c[]=new char[s.length()]; //array to hold characters of the first string.
char ch[]=new char[str.length()]; //array to hold characters of second string.
int i=0; //serves as a loop control variable several times.
int count=0;
if(s.length()==str.length()) //words cannot be anagrams of each other unless they have
the same number of characters.
{
for(i=0;i<s.length();i++) //extracting characters of the first word to an array.
{
c[i]=s.charAt(i);
}
for(i=0;i<str.length();i++) //extracting characters of the second word to an array.
{
ch[i]=str.charAt(i);
}

for(i=0;i<s.length();i++)
{
for(int j=0;j<ch.length;j++)
{
if(c[i]==ch[ j])
{
ch[ j]='+'; //this is done firstly to ensure that repeating elements do not count
again.
//the main reason is to check if all the elements of ch[] match the ones of c[].
//if all the elements of ch are +, then the words are anagrams of each other.
break;
}
}
}
for(i=0;i<str.length();i++)
{
if(ch[i]!='+') //checks all the elements of the array.
{
count++;
break;
}
}
if(count==0)
{
return true;
}
return false;
}
else
return false;
}

public static void main()


{
Scanner sc=new Scanner(System.in); //input is being taken.
System.out.print("Enter the first word: ");
String s=sc.nextLine();
System.out.print("Enter the second word: ");
String str=sc.nextLine();
Anagram ob=new Anagram();
if(ob.isAnagram(s,str)==true) //the print statements for either case are as follows.
{
System.out.println("The words are anagrams of each other.");
}
else
System.out.println("The words are not anagrams of each other.");
}
//The program will not retain its functionality if either of the words contain any
uppercase letters, which should not be inputted in this program.
}
VDT

Name Datatype Description


c[] char This array stores the characters of the first string.
ch[] char This array stores the characters of the second string.
i int Loop control variable for various loops used in the program.
Variable to calculate the number of times a character other than '+' was detected, in
count int the respective array.
j int Loop control variable to go through the characters of the second array.
s String User inputted , first string.
str String User inputted, second string.
ob Anagram Object of class Anagram.
Java Terminal Window

First Case:

Second Case:
Q5) Write a program to input a name which is three words long,
and the output being the last name followed by the first and
middle name.

Source Code:
import java.util.*;
class Name
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a name: ");
String s=sc.nextLine();
char c=s.charAt(0);
int count=0;
System.out.print("The name now is: ");
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c==' ')//detects whenever a space is inputted.
{
count++;
}
//it should be noted that multiple spaces must not be used.
if(count>=2)//after 2 spaces are detected, the program prints the last name.
{
System.out.print(c);
}
}
count=0;//the value of count is reset.
System.out.print(" ");
for(int i=0;i<s.length();i++)//this loop simply prints the first and middle name.
{
c=s.charAt(i);
if(c==' ')
{
count++;
}
if(count<2)//after 2 spaces are detected, the program terminates.c
{
System.out.print(c);
}
}
}
}

VDT
Name Datatype Description
c char This variable goes through all the characters of the string.
count int This variable is to count the number of times a space has been detected in the string.
i int Loop control variable.
s String The string contains the name which is 3 words long.

Java Terminal Window


Q6) Write a program to input a number and check if it is a Happy
number.

Note: A Happy number is a number which eventually reaches 1 when replaced


by the sum of the square of each digit.

Example:
13 is a happy number because,
12 +32=10
12 +0=1.

Source Code:
import java.util.*;
public class HappyNumber
{
public int happy(int n)
{
int r=0,s=0;
while(n>0)//loop which keeps adding the sum of the squares of the digits of the
number.
{
r=n%10;
s=s+(r*r);
n=n/10;
}
return s;
}

public static void main()


{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int n=sc.nextInt();
int result=n;
HappyNumber ob= new HappyNumber();
while((result!=1)&&(result!=4))//after the process , the number will either reach 1 or 4.
{
result=ob.happy(result);
}
if(result==1) // if the number reaches 1 after the loop , then the original no. is a happy
number.
System.out.println(n + " is a happy number.");
else if(result==4) //the appropriate statement if the number does not reach 1 is
printed.
System.out.println(n + " is not a happy number.");
}
}

VDT

Name Datatype Description


r int Variable to store the value of the last digit of the number.
s int This variable stores the value of the sum of all the squares of the digits of the numbers.
n int User inputted value to be checked for 'Happy Number' compatibility.
result int Stores the boolean value of the method which checks if the number is a happy number.
ob HappyNumber Object of the class HappyNumber.
Java Terminal Window

First Case:

Second Case:
Q7) Write a program to input a string and find all the possible
permutations of the string.

Source Code:

import java.util.*;
class String_Permutations
{
public static void Permutation(String s,String a)
{
if (s.length()==0)//this detects when string is empty
{
System.out.println(a);
return; //this is to escape out of recursive method
}
for (int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
String k=s.substring(0,i)+s.substring(i+1); //this calculates the possible permutations
System.out.println("k is "+k);
Permutation(k,a+ch); //recursive method call
}
}

public static void main()


{
System.out.print("Enter the string whose permutations are to be found: ");
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println("The permutations of the string are as follows: ");
Permutation(s," ");
}
VDT

Name Datatype Description


s String This is the Initial string inputted by the user.
a String Substring to be added recursively to the string to generate permutations.
i int Loop control variable to iterate through the string.
k String Stores the intermediate substring for permutation.
ch char Stores the character at ith position of the string.

Java Terminal Window


Q8) Write a program to input a line and find the frequency of a
certain letter in the line.

Source Code:

import java.util.*;
class String_Frequency
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a line: ");
String s=sc.nextLine();
System.out.print("Enter the letter which has to be checked for frequency: ");
char c=sc.next().charAt(0);
int count=0;
int c1=0;
char c2=0;
char chrtr=0;
if((int)c>97)//if the letter is in lowercase.
{
c1=(int)c-32;
c2=(char)c1; //uppercase of the letter
}
else //if the letter is in uppercase.
{
c1=(int)c+32;
c2=(char)c1; //lowercase of the letter
}

for(int i=0;i<s.length();i++)
{
chrtr=s.charAt(i);
if((chrtr==c)||(chrtr==c2))
{
count++; //counter variable to check for the frequency of required letter..
}
}
System.out.println("The frequency of letter is "+count+".");
}
}
VDT
Name Datatype Description
Variable to store value of character which is going to be checked for
c char frequency.
count int Variable storing the frequency of the given letter in the string.
c1 int Stores the typecasted value of the character c , but as an integer.
c2 char Stores the value of the character, but in the opposite case.
This variable is used to compare each character of the String s, to the given
chrtr char letter.
i int Loop control variable used to go through the characters of String s.
Java Terminal Window

First Case:

Second Case:
Q9) Write a menu driven program , giving the user an option to
check if two numbers are co-prime, or to check if a number is a
circular prime, i.e. All permutations of that number are primes.

Source Code:
import java.util.*;
class Primes
{
public boolean isPrime(int n)//checks if the number is prime.
{
if (n<=1)
return false;
if (n<=3)
return true;
if (n%2==0||n%3==0)//the two smallest cases, if the number is even then it is not
prime.
//and if it's divisible by 3, it is not.
return false;
for (int i=5;i*i<=n;i=i+6)
{
//value of i increases by 6, as the number not divisible by 6.
//due to the previous if conditions, the loop is shortened to check for much lesser
numbers.
if (n%i==0||n%(i+2)==0)
return false;
}
return true;
}

public boolean isCircular(int number)


{
int count=0,temp=number;
Primes obj=new Primes();
while (temp>0)
{
count++;
temp /= 10;
}
int num=number;
while (obj.isPrime(num)) //checks if all the permutations of the number are prime.
{
int rem=num%10;
int div=num/10;
num=(int)((Math.pow(10,count-1))*rem)+div;
if(num==number)//if all the permutations are gone through in the loop, 'num'
becomes the original number, hence, the number is a circular prime.
return true;
}
return false;
}

public int gcd(int n1,int n2)


{
if (n1==0||n2==0)//if either of the numbers is 0, the GCD is 0
return 0;
if (n1==n2)//if the numbers are equal, the GCD is the number itself.
return n1;
if (n1>n2) //this is for when the first number is larger than the second.
return gcd(n1-n2,n2);
return gcd(n1,n2-n1);
//hence, the gcd of the two numbers is calculated in this method.
}

public static void main ()


{
Primes obj=new Primes();//input is taken
System.out.println("Please enter the corresponding option to the required function:");
System.out.println ("1: Check if a number is a circular prime.");
System.out.println("2: Check if a pair of numbers are co-prime.");
System.out.println();
System.out.print("The input is: ");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
switch (n)//switch case begins .
{
case 1://for checking if two numbers are circular prime.
{
System.out.print("Enter a number: ");
int number=sc.nextInt();
if (obj.isCircular(number))
System.out.println("The number is a circular prime.");
else

System.out.println("The number is not a circular prime.");


break;
}
case 2://to check if the numbers are co prime.
{
System.out.println("Enter two numbers: ");
int n1=sc.nextInt();
int n2=sc.nextInt();
if(obj.gcd(n1,n2)==1) //if the GCD of two numbers is 1, then they are co-prime.
System.out.println("The numbers are co-prime.");
else
System.out.println("The numbers are not co-prime.");
break;
}
default:
{
System.out.println("Please enter a valid input.");
break;
}

}
}
}

VDT

Name Datatype Description


i int Loop control variable.
count int Stores the number of digits the original number has.
temp int Stores the value of the original variable, as a temporary one.
num int Variable to store the value of the original number, inputted by the user.
rem int Variable to store value of the last digit of the various permutations of the number.
div int Variable to obtain the number without the last digit.
number int The original number, inputted by the user.
n int The input for the switch case by the user.
n1 int Takes input for the first of two numbers, to check if they are co prime.
n2 int Takes input for the second of two numbers, to check if they are co prime.
obj Primes Object of the class Primes
Java Terminal Window

First Case:

Second Case:
Q10) Write a program, using overloaded constructors, to enter
two sets of time consisting of hours , minutes and seconds, in both
, and add the two time periods and print it.

Source Code:

import java.util.*;
class Time_Period
{
public static int hours,min,sec,hours1,min1,sec1;

public static void main()


{
//two values of set time are taken , and added, and the total time is printed.
Scanner sc=new Scanner(System.in);
System.out.println();
int k=0;
System.out.println("Set 1:");
System.out.println();
System.out.print("Enter the number of hours: ");
int h=sc.nextInt();
System.out.print("Enter the number of minutes: ");
int m=sc.nextInt();
System.out.print("Enter the number of seconds: ");
int s=sc.nextInt();
System.out.println();
System.out.print("Set 2: ");
System.out.println();
System.out.print("Enter the number of hours: ");
int h1=sc.nextInt();
System.out.print("Enter the number of minutes: ");
int m1=sc.nextInt();
System.out.print("Enter the number of seconds: ");
int s1=sc.nextInt();
//constructors are called.
Time_Period ob=new Time_Period(h,m,s,k);
Time_Period obj=new Time_Period(h1,m1,s1);
ob.calculator(hours1,min1,sec1);
}

Time_Period(int h,int m,int s,int k )//constructor to initialize the first set of number of
hours, minutes and seconds.
{
hours=h;
min=m;
sec=s;
}

Time_Period(int h1,int m1,int s1)//constructor to initialize the first set of number of


hours, minutes and seconds.
{
hours1=hours+h1;
min1=min+m1;
sec1=sec+s1;
}

public static void calculator(int hours1,int min1,int sec1)//constructors to add the values
of the variables, and increase the value of hours or minutes after minutes or seconds,
reaches a number more than 60, respectively.
{
if(min1>=60)
{
hours1=hours1+(min1/60);
min1=min1%60;
}
if(sec1>=60)
{
min1=min1+(sec1/60);
sec1=sec1%60;
}
//time is printed in hh:mm:ss format.
System.out.println("Total Time- "+hours1+" : "+min1+" : "+sec1);//prints the time after
adding the two sets of time.
}

}
VDT

Name Datatype Description


k int Variable serves no real purpose, except for distinguishing the overloaded constructors.
h int Variable stores the value of hours inputted by the user in the first set of time period.
m int Variable stores the value of minutes inputted by the user in the first set of time period.
s int Variable stores the value of seconds inputted by the user in the first set of time period.
h1 int Variable stores the value of hours inputted by the user in the second set of time period.
m1 int Variable stores the value of minutes inputted by the user in the second set of time period.
s1 int Variable stores the value of seconds inputted by the user in the second set of time period.
Variable initialized in an overloaded constructor stores the value of hours in the first set of
hours int time period.
Variable initialized in an overloaded constructor stores the value of minutes in the first set
min int of time period.
Variable used overloaded constructor stores the number of seconds in the first set of time
sec int period.
hours1 int This variable used in an overloaded constructor stores the total value of hours.
min1 int This variable used in an overloaded constructor stores the total value of minutes.
sec1 int This variable initialized in an overloaded constructor stores a total value of seconds.

Java Terminal Window


Q11) WAP to demonstrate how to check if a number is
square-free. Put a random number to demonstrate how to
check, and call the method where it is checked from the
main method.
Note:
● 1 is not considered a square, squares of values more than 2 are
considered.

● Use a void method without parameters.

Source Code:

class SquareFree

public void squarefree()

int n=121; //With a different value of n, the output might be different.

int c=0;

if (n%2==0) //This checks if n is divisible by 2.

n=n/2; // Now n is divided once by two.

if (n%2==0) // If 2 divides n again , then it is trivial to see that n is not


a square free number.

c++; //This increases the value of c, so as to check if this n is


divisible by 2 twice.Value of c remains unchanged if it is a square free
number.
}

// If n is not divisible by 2 twice, now n is odd.

// Loop runs through all the odd natural numbers starting from 3 till the
square root of the number as the square of the square root of the number is
the number itself.

for (int i=3;i<=Math.sqrt(n);i=i+2)

{
if (n%i==0) //If n can be divided by i twice, then n is not a square

free number. {

n=n/i; //n is divided once by i.

if (n % i == 0) //n's divisibility by i is checked.If this returns true,


then n is not a square free number.

c++;

//If n passes all the above tests and the value of c remains unchanged, then the
number n is a square free number.

if (c==0)

System.out.println("The number is a square free number.");

else //If the value of c increases,it means that it is divisible by a

square number. System.out.println("The number is not a square

free number.");

public static void main()

SquareFree obj=new SquareFree();

obj.squarefree();//calls the method.

}
VDT

Name Datatype Description

n int This variable stores the value which is to be checked to be square free.

c int This variable increases in value when the number is found to be divisible by a
square.

i int Loop control variable to check if the number is divisible by any odd
number,twice.

obj SquareFree Object of the class SquareFree.

Output:

The number is a square free number.


Q12) WAP to input two numbers, one of them being
minimum of 6 digits and maximum being 9, and another
being a number between 1 and 5(both included). Process
the first number through the following steps in an
example:
Input: 123897 and 4.
Step 1: Divide the number into two parts respective to the
second number(in this case, 4): 1238 and 97
Step 2: Reverse each part: 8321 and 79
Step 3: Exchange the positions of the two parts and
merge them: 798321

Step 4: Display the prime position digits reverse


order: 2,8,9.

Display the number after processing it through each step.

Source Code:
import java.util.*;

class Processing

public void execution(int n,int k,int count)

double i=Math.pow(10.0,count-k);//this variable is used in the process of creating two


parts.

double f=n%i;//This creates one of the parts of the number,one containing


(count-k) digits in it after the first step .

double p=n/i; //This creates the other part of the number, containing 'k'

number of digits. double no=0.0;

double m=Math.pow(10.0,count);//this variable is used in the process of


merging the two reversed parts.

int part1=0;

int part2=0;

int sa = (int) p; //Typecasting is used to initialize the integer value of s into


variable sa,thus removing the digits after the decimal dot.

int fa=(int) f; //Typecasting is used to initialize the integer value of f into variable fa.
System.out.println("The numbers after the first step are: "+sa+" and

"+fa+"."); while(fa!=0) //another loop is started to reverse one of the parts

created in the first step. {

int r2=fa%10;

part2=(part2*10 + r2);

fa=fa /10;

no=no+r2*m;//Operates within the loop to create the merged number.

m=m/10; //Divides 'm' by 10 so that the number gets reversed and

merged correctly. }

no=no/10; //To remove the last digit in the loop(which is an extra 0).

while(sa!=0) //another loop is started to reverse the other part created in

the first step. {

int r2=sa % 10; //variable 'r2' is reused in this loop.

part1 = (part1*10 + r2);

sa = sa /10;

m=m/10;

no=no+r2*m; // The second reversed part merges with the

first in this loop. }

int rev=(int)no; //Typecasting is used to initialize the integer value of no


into variable rev. int prime=0;

System.out.println("The numbers after the second step are: "+part1+" and

"+part2+"."); System.out.println("The number after the third step is:

"+rev+".");

System.out.print("The prime position digits are:");

for(;count>0;count--) //A loop is started to calculate the prime position


digits, running the number of times as the digits in the number.

prime=rev%10; //this will isolate the last digit of the program to check if it

is prime or not. if((count==2)||(count==3)||(count==5)|| (count==7))

//As the maximum number that is considered a valid input is 9


digits, the only prime position digits can be the ones which are in the
2,3,5 or 7th place.

{
System.out.print(prime+","); //the prime digits are printed here.

rev=rev/10;

public static void main()

Scanner sc=new Scanner(System.in);

System.out.print("Enter a number of minimum 6-digits ,and

maximum of 9-digits: "); int n=sc.nextInt();

System.out.print("Enter a number between 1 and 5,both

numbers included: "); int k=sc.nextInt();

int count=0;//Variable to count the number of digits in the number

inputted by the user. int copy=n; //Variable to copy the value of n.


for( count=0;copy!=0;count++)

copy=copy/10;

Processing obj=new Processing(); //Object of the class is created.

System.out.println("You have entered a "+count+"-digit number.");

if((count>=6)&&(count<=9)&&(k>=1)&&(k<=5)) //Verifies if the input is

valid or not. {

obj.execution(n,k,count);

else //runs if the input is invalid.

System.out.println("Please run the program again as the input has been


determined to be invalid.");

Input:
Enter a number of minimum 6-digits ,and maximum of 9-digits:

1236789

Enter a number between 1 and 5,both numbers included: 5

Output:

You have entered a 7-digit number.


The numbers after the first step are: 12367 and 89.
The numbers after the second step are: 76321 and 98.
The number after the third step is: 9876321.
The prime position digits are:1,3,7,8,

VDT

Name Datatype Description

i double This variable creates an exponent of 10 used to process the number.

f double This variable holds the value of the remainder of the original number divided by 'i',
hence the second part.

p double This variable holds the value of the quotient of the original number divided by 'i',
hence the first part.

no double Variable holds the value after merging the two parts of the number as described in
step 3.

m double Variable holds an exponent value of 10 which helps in merging the digits of the two parts
after step 2.

part1 int This variable contains the reversed value of the first part after step 1.

part2 int This variable contains the reversed value of the first part after step 2.

sa int Variable contains the integer value of p.

fa int Variable contains the integer value of f.


First, it helps reverse the first and second part after step 1, later, helps in merging
r2 int the two reversed parts.
rev int This variable holds the integer value of the variable 'no'.

prime int This variable holds the value of each digit in the number after step 4, enabling the
check for prime position digits.

n int User inputted variable for the first number .

k int User inputted variable for the second number between 1-5 .

count int Counts the number of digits in the first number.

copy int Copies the value of the variable 'n',so that the value of n does not change when
counting digits in the first number.

obj Processing Object of the class Processing.


Q13) WAP to demonstrate how to find a single element in the array
that has been repeated more than once in it. Use two methods for this
program, one of them being a method with a return value.

Source Code:
import java.util.*;

class Duplicate

public static int arr()

int a[]={2,3,2,45,6,8,323,9}; //This line initializes the eight elements

of the array. int n=0;

for(int i=0;i<8;i++) //A loop is run going through the eight elements

of the array. {

for(int j=0;j<8;j++) //This loop is for checking the array for the

duplicate element. {

if(j==i) //This ensures that when the loop skips checking the same
element as the duplicate is another element with the same value in the array.

continue;

else if(a[i]==a[ j]) //This checks the corresponding element for the

duplicate element. {

return a[i] ; // If a duplicate element is found, the return value is


passed and the method is terminated.

//The loop repeats.

}
}

return 0; // If a duplicate element is not found, a return value of 0 is passed.


}

public static void main()

Duplicate obj=new Duplicate();

if(obj.arr()!=0)

System.out.println("The duplicate element is: "+obj.arr()); //this statement


prints the return value of the method 'arr',hence the duplicate element in the
array.

else

System.out.println("There is no duplicate element in the array.");

VDT

Name Datatype Description


a[] int This array stores the initial elements of the array in the code.
Loop control variable goes through each element in the array,holding the i'th element whilst
i int it is checked.
Loop control variable which checks each element to be duplicate in comparison to the i'th
j int index element in the array.

obj Duplicate Object of the class Duplicate.


Java Terminal Window
Q14) WAP to input two numbers and check if they are
amicable with respect to each other.
Amicable numbers are two different numbers related in
such a way that the sum of the proper divisors of each is
equal to the other number.
Eg. 220,284.

Source Code:

import java.util.*;

class Amicable

public static int divSum(int n) //method to find the sum of

divisors of a number. {

int result = 0;

// Finding all divisors that divide a number.

for (int i=2;i<=Math.sqrt(n);i++)

if (n%i==0) // If 'i' is divisor of 'n'

if (i==(n/i)) // If both divisors are the same then it is added once.

result+=i;

else //Otherwise both are added.

result+=(i+n/i);

}
// Adding 1 and n to result as above loop, because by the above loop,1 is not
considered a proper divisor.
return (result+1);

public static boolean areAmicable(int x, int y)

if (divSum(x)!=y)

return false; // Returns false if x and y are not Amicable .

return(divSum(y)==x); // Returns true if x and y are Amicable .

public static void main ()

Scanner sc=new Scanner(System.in);

System.out.println("Please enter two numbers which are to be checked


for properties of amicable numbers:") ;

int x=sc.nextInt();

int y=sc.nextInt();

if (areAmicable(x, y)) //if the method returns true,this

statement is printed. System.out.println( "Yes,the numbers

are amicable.");

else //else the method returns true,this statement is printed.

System.out.println("No,the numbers are not amicable.");

Input:
Please enter two numbers which are to be checked for properties of
amicable numbers:
5564
5020

Output:
Yes,the numbers are amicable.

VDT
Name Datatype Description

n int This variable holds the value of either x and y in the program to
calculate the sum of their factors, respectively.

result int This variable holds the value of the sum of the factors of the
parameter which is passed.

i int Loop control variable to check for the factors of the number.

x int This variable holds an user inputted value to check if it is amicable


with the other number.

y int This variable holds an user inputted value to check if it is amicable


with the other number.
Q15) WAP to create an empty 10-element integer array, and
offer the user a choice to modify it by adding or deleting
elements. Have an option for printing the array as well as
ending the program after displaying the final state of the
array.

Source Code:
import java.util.*;

class Customize_Array

void insert(int [] a,int c) //method to insert an element into

an array. {

for(int i=0;i<10;i++)

if(a[i]==0) //Loop to search for '0',hence an empty element in the

array. {

a[i]=c;//This inserts the user inputted value inside an empty element


in the array.

System.out.println("The number "+c+" has been added in the array.");

break; //ends the loop if an empty element is found and replaced with the
user inputted number.

else if(i!=9)

continue;// prevents the loop to reach the else statement until the last
element of the array is checked to be empty.

else // runs if there is no empty element in the array.

{
System.out.println("There is no empty element in the array,please
remove an element before adding one.");
}

void remove(int [] a,int p) // method to remove an element from an

array. {

for(int i=0;i<10;i++) // loop to find the user inputted element in the

array. {

if(a[i]==p)

a[i]=0; // replaces the user inputted element(if found) with


0,making it an empty element in the array .

System.out.println("The number "+p+" has been removed from the

array."); break;

else if(i!=9) //prevents the loop from reaching the else statement until
the last element of the array is checked to be the user inputted element.

continue;

else //statement is printed if the user inputted element is not found in the

array. {

System.out.println("The number you want to remove is not


present in the array,please enter a valid number which is present in the
array.");

void display(int [] a) //method to display the current elements in the


array. {

System.out.print("The current elements of the array are: ");


for(int i=0;i<10;i++) //loop to print the elements of the array.

if(i<9)

System.out.print(a[i]+", ");

else if(i==9) //prints a full stop after the array has been printed.

System.out.println(a[i]+".");

void end(int [] a) //method to end the program after displaying the final
elements in the array.

System.out.print("The final elements of the array are: ");

for(int i=0;i<10;i++) //loop to print the final elements in

the array. {

if(i<9)

System.out.print(a[i]+", ");

else if(i==9)

System.out.println(a[i]+".");

System.out.println();

System.out.println("Ending the program...");

System.out.println("The program has been terminated. " );

System.exit(2); //function to end the program after 2 seconds.

}
public static void main()

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

int a[]=new int[10]; //initializes an array of length 10.

int n=0;

System.out.println("Disclaimer: The element containing the number


'0',is considered to be empty ,and can be replaced by another number
further on in the program.");

//statement to familiarize the user with the definition of an empty element


in the array, as used in the program.

System.out.println("Enter the ten elements of the array: ");

for(int i=0;i<10;i++) //the elements of the array are inputted.

a[i]=sc.nextInt();

System.out.print("The initial elements of the array are: "); //prints the


elements in the array.

for(int i=0;i<10;i++)

if(i<9)

System.out.print(a[i]+", ");

else if(i==9)

System.out.println(a[i]+".");

System.out.println();

System.out.println("1 : Insert a number into any empty element of the array .");

System.out.println("2 : Remove a number from the array ,creating an


empty element inside the array.");
System.out.println("3 : Print the current elements of the array.");

System.out.println("4 : Print the final elements of the array end the program. ");
//group of statements to familiarize the user with the various uses of the

program. System.out.println();

while(true) // takes input from the user in a loop, ending the program
when the corresponding input is received.

System.out.println();

System.out.print("Enter the number corresponding to the required task: ");

n=sc.nextInt(); //the function of the program which would run is decided


by the value of this variable.

Customize_Array obj=new Customize_Array(); //an object of the


class is created.

switch(n) //switch case runs to call the respective method.

case 1: //calls the method to insert an element in the array.

System.out.println("Enter the number which you want to input in


the array: ");

int c=sc.nextInt();

obj.insert(a,c); //a is passed by reference and c is passed by

value. break;

case 2: //calls the method to remove an element from the array.

System.out.println("Enter the number in the array you want to

remove: "); int p=sc.nextInt();

obj.remove(a,p); //a is passed by reference and p is passed by

value. break;

case 3 : //calls the method to display the elements in the array.

obj.display(a); //a is passed by reference.

break;
case 4: //calls the method to end the program.

obj.end(a); //a is passed by reference.


break;

default : //runs if the user inputted a wrong input.

System.out.println("The program has failed to run,the most


probable cause being an invalid input by the user.");

VDT
Name Datatype Description

a[] int This array stores all the initial elements that the user inputs and gets
customized accordingly.

c int This variable takes a user inputted value that it has to replace an empty
element of the array with.

i int Loop control variable for various loops for the array throughout the program.

p int This variable takes a user inputted value which has to be removed from
the array once, if present.

n int This variable helps the user operate the program and choose what process
is to be conducted.

obj Customize_Array. Object of class Customize_Array.


Java Terminal Window
Q16) WAP to find the area/ volume of 4 geometric
figures using constructors and a user defined function.
Write 4 parameterized constructors overloaded to
initialize data members of each figure. Use one or more
functions to calculate area/volume. Write main () to call
objects and methods and for input. A menu driven
program might be used.

Source Code:

import java.util.*;

class Areas

static int side,side2,side3;

static double radius,areaC ,areaS,areaT,areaRH;

//the global variables are initialized.

Areas(int a) // constructor to the side of a regular hexagon.

side=a;

Areas(double b) //constructor to initialize the radius of the circle.

radius=b;

Areas(int a,int c,int d) //constructor to initialize the three sides of a triangle.


{
side=a; //variable 'side' is reused here, but with a different user inputted value.
side2=c;

side3=d;

public void aCircle() //method to calculate area of the circle.

areaC=2*radius*3.14; //area if the circle is calculated by the

formula πr^2=area. System.out.println("The area of the circle is:

"+areaC);

public void aTriangle() //method to calculate area of the triangle.

double s=(1.0/2.0)*(side+side2+side3);

//s measures the perimeter of the triangle divided by 2.

areaT=Math.sqrt(s*(s-side)*(s-side2)*(s-side3)) ;

//Heron's formula is used to calculate the area. Note that if a triangle cannot be
formed by the inputted sides, the area would be ‘NaN’, as the formula only works if
the geometry of a triangle is acknowledged.

System.out.println("The area of the triangle is: "+areaT);

public void v3DSphere()

areaS=(4/3)*3.14*Math.pow(radius,3) ; //the formula for a


three-dimensional sphere is calculated by a formula-4*πr^2=area.

System.out.println("The area of the 3D sphere is: "+areaS);

}
public void aHexagon() //method to calculate the area of a

regular hexagon. {

areaRH=((3*Math.sqrt(3))/2)*Math.pow(side,2);
System.out.println("The area of the hexagon is: "+areaRH);

public static void main() //main method to take the user input and call the

respective methods. {

Scanner sc=new Scanner(System.in);

System.out.println();

System.out.println("1: Area of a circle with the radius as inputted by

the user."); System.out.println("2: Area of a triangle with the sides as

inputted by the user."); System.out.println("3: Area of a 3D Sphere with

the radius as inputted by the user."); System.out.println("4: Area of a

hexagon with the side as inputted by the user."); System.out.println("5:

Exit the program.");

System.out.println();

//statements to describe the menu driven program.

while(true) // loop to take input, loop stops when the corresponding 'terminate
program 'option is chosen.

System.out.println();

System.out.println("Please enter the number corresponding to the required

area or volume: "); int n=sc.nextInt();

//different objects have to be taken for different constructors.

switch(n) //switch case to call the respective methods and take the

respective inputs. {

case 1:
{

System.out.print("Enter the radius of the circle: ");

double b=sc.nextDouble();

Areas ob=new Areas(b);

ob.aCircle();

break;
}

case 2:

System.out.print("Enter the length of the first side of

a triangle: "); int a=sc.nextInt();

System.out.print("Enter the length of the second side of

the triangle: "); int c=sc.nextInt();

System.out.print("Enter the length of the third side of

the triangle: "); int d=sc.nextInt();

Areas obje=new Areas(a,c,d);

obje.aTriangle();

break;

case 3:

System.out.print("Enter the radius of the sphere: ");

double b=sc.nextDouble();

Areas ob=new Areas(b);

ob.v3DSphere();

break;

case 4:
{

System.out.print("Enter the length of the side of

the hexagon: "); int a=sc.nextInt();

Areas obj=new Areas(a);

obj.aHexagon();

break;

}
case 5:

System.out.println("The program has been ended.Thank You!");

System.exit(0); //this terminates the program.

default:

System.out.println("The program has failed to run,the cause


being invalid input by the user.");

break;

}
Input:
1: Area of a circle with the radius as inputted by the
user. 2: Area of a triangle with the sides as inputted
by the user. 3: Area of a 3D Sphere with the radius as
inputted by the user. 4: Area of a hexagon with the
side as inputted by the user. 5: Exit the program.

Please enter the number corresponding to the required area or


volume: 2 Enter the length of the first side of a triangle: 12
Enter the length of the second side of the triangle: 5
Enter the length of the third side of the triangle: 9

Output:
The area of the triangle is: 20.396078054371138
VDT
Name Datatype Description

side int This variable stores the value of the first side of the triangle.

side2 int This variable stores the value of the second side of the triangle.

side3 int This variable stores the value of the third side of the triangle.

radius double This variable stores the value of the radius of the circle or sphere.

areaC double This variable stores the value of area of the circle

areaS double This variable stores the value of the three dimensional sphere.

areaT double This variable stores the value of the area triangle.

areaRH double This variable stores the value of the area of the regular hexagon .

b int Parameter for user inputted value of radius of the circle or sphere.

a int Parameter for user inputted value of the respective side of a triangle
or a regular hexagon.

c int Parameter for user inputted value of respective side of a triangle.

d int Parameter for user inputted value of the respective side of a triangle.

n int Variable to operate the switch case, hence taking the user's choice.

s double Variable to calculate half of the perimeter of the hypothetical triangle


.

obj Areas Object of the class Areas.

ob Areas Object of the class Areas.

obje Areas Object of the class Areas.


Q17) WAP to input marks of a student in 5 subjects using a
parameterized constructor, calculate and display average
marks of the student for those 5 subjects using 2 separate
methods to find the average and display data. Write main ()
to create object and call methods.

Source Code:
import java.util.*;

class Average_Marks

static int a,b,c,d,e,avg; //global variables are initialized.

public Average_Marks(int a1,int b1,int c1,int d1,int e1) //Constructor


initializes all the global variables.

a=a1;

b=b1;

c=c1;

d=d1;

e=e1;

public void Con1() //method to calculate the average of the five marks.

avg=(a+b+c+d+e)/5;

public void display() //method to display the average marks.


{

System.out.println("The average marks of the student is: "+avg);

}
public static void main()

Scanner sc=new Scanner(System.in);

//Variables below take input of the marks of the student in 5

different subjects. System.out.print("Enter the marks of the

student in the first subject: "); a=sc.nextInt();

System.out.print("Enter the marks of the student in the

second subject: "); b=sc.nextInt();

System.out.print("Enter the marks of the student in the

third subject: "); c=sc.nextInt();

System.out.print("Enter the marks of the student in the

fourth subject: "); d=sc.nextInt();

System.out.print("Enter the marks of the student in the

fifth subject: "); e=sc.nextInt();

Average_Marks ob=new Average_Marks(a,b,c,d,e); //The variables are


passed to the constructor to initialize the values into global variables.

ob.Con1(); //The method to calculate the average marks is called.

ob.display(); //The method to display the average marks is called.

}
Input:
Enter the marks of the student in the first subject: 56
Enter the marks of the student in the second subject: 89
Enter the marks of the student in the third subject: 75
Enter the marks of the student in the fourth subject: 96
Enter the marks of the student in the fifth subject: 100

Output:
The average marks of the student is: 83

VDT
Name Datatype Description
a int Variable for storing marks of the first subject.
b int Variable for storing marks of the second subject.
c int Variable for storing marks of the third subject.
d int Variable for storing marks of the fourth subject.
e int Variable for storing marks of the fifth subject.
avg int Variable to store the average marks of the student.
a1 int Parameter for user inputted marks in the first subject.
b1 int Parameter for user inputted marks in the second subject.
c1 int Parameter for user inputted marks in the third subject.
d1 int Parameter for user inputted marks in the fourth subject.
e1 int Parameter for user inputted marks in the fifth subject.
ob Average_Marks Object of class Average_Marks.
Q18) WAP to input the names and ranks of ten students,
and then display the name corresponding to the rank the
user wants to obtain. No two students can have the same
rank.

Source Code:
import java.util.*;

class BinarySearch

public static void main() //function to call various methods and print

the final output. {

BinarySearch obj=new BinarySearch();

int rank[]=new int [10];

String name[]=new String [10];

obj.input(name,rank); //method to take input is called.The arrays are passed

by reference. Scanner sc=new Scanner(System.in);

System.out.println();

System.out.print("Enter the rank that is to be found: ");

int n=sc.nextInt();

int r=obj.search(rank,n); //initializes the return value of 'search' into r.

//the value of r represents the index the rank was found in,hence the
corresponding name can be found from the other

//array as it is also present in the same index.

if(r==0) //If the rank that is searched for is not present.

System.out.println("No student achieved that rank.");

else

System.out.println("The student who was ranked "+n+" is

"+name[r]+"."); //the statement prints the rank and the


corresponding name.

}
public void input(String name[],int rank[]) //method to take the user input
for the name and corresponding rank.

Scanner sc=new Scanner(System.in);

for(int i=0;i<10;i++) //loop runs to take input for 10 students.

System.out.println(" Student:"+(i+1));

System.out.print(" Please enter the name of the student: ");

name[i]=sc.nextLine();

System.out.print(" Please enter the rank of the respective student: ");

//no two students can have the same rank.

rank[i]=sc.nextInt();

sc.nextLine(); //to avoid skips in String input.

System.out.println();

public static int search(int rank[],int n ) //method to search for the name
corresponding to the rank to be searched.

int low=0, high=rank.length-1;

while(low<=high)

int mid=low+(high-low)/2;

if(rank[mid]==n)

return mid;
if (rank[mid]<n)

low=mid+1;

else
high=mid-1;

return 0; //If the required rank is not found in the given array then

this returns 0. }

Input:
Student:1
Please enter the name of the student: Evan
Please enter the rank of the respective student: 2

Student:2
Please enter the name of the student: Guru
Please enter the rank of the respective student: 4

Student:3
Please enter the name of the student: Georgio
Please enter the rank of the respective student: 7

Student:4
Please enter the name of the student: Simon
Please enter the rank of the respective student: 8

Student:5
Please enter the name of the student: Krish
Please enter the rank of the respective student: 1

Student:6
Please enter the name of the student: Aryan
Please enter the rank of the respective student: 3

Student:7
Please enter the name of the student: Sasha
Please enter the rank of the respective student: 5

Student:8
Please enter the name of the student:
Anant Please enter the rank of the
respective student: 10

Student:9
Please enter the name of the student:
Ojas Please enter the rank of the
respective student: 6

Student:10
Please enter the name of the student:
Anubhav Please enter the rank of the
respective student: 9

Output:

Enter the rank that is to be found: 5


The student who was ranked 5 is Sasha.
VDT
Name Datatype Description

rank[] int This array stores the ranks of the corresponding students.

name int This array stores the names of the corresponding students.

r int This array stores the return value of the method 'search'.

i int Loop control variable for input loop.

low int Variable used in binary search loop to set the lower limit.

high int Variable used in binary search loop to set the upper limit.

mid int Variable used in binary search loop to store the value of the middle
index between the two limits.

n int Variable that has user inputted value for specific rank whose
corresponding name has to be found.

obj BinarySearch .Object of class BinarySearch.


Q19) WAP to input a number and then input the digits
of the number to an array. Arrange the array in
descending order and display the number obtained after
merging the elements of the array.

Source Code:
import java.util.*;

class Digit_Seperation

public void digit(int n,int count)

int a[]=new int [count];

for(int i=count-1;i>=0;i--) //The digits in the number are initialized as


individual elements in the array.

//i is initialized to be 1 less than the number of digits to ensure that the
array elements correspond with the digits.

//First digit in the number would be the lower bound,the last digit would
be the upper bound.

a[i]=n%10;

n/=10;

System.out.print("The array containing the digits of the number is: ");

for(int i=0;i<count;i++) //loop to print the elements in the array.

if(i==count-1) //This prints a full stop after the array is printed.

System.out.println(a[i]+".");

continue;
}

System.out.print(a[i]+",");

}
int i,j, small,temp,pos;

int h=count;

int f=0;

for(i=0;i<h;i++) //selection sorts the array in descending order.

small=a[i];

pos=i;

for(j=i+1;j<h;j++)

if(a[ j]>small)

small=a[ j];

pos=j;

temp=a[i];

a[i]=small;

a[pos]=temp;

for(i=0;i<count;i++) //loop to take the elements of the array in order and


print the number formed.

if(i==count-1)

f=(a[i]+f);
break;

f=(a[i]+f)*10;

}
System.out.println("The final number is: "+f);

public static void main()

Scanner sc=new Scanner(System.in);

System.out.print("Enter the number: ");

int n=sc.nextInt();

int count=0;

int copy=n; //This is done so that the value of n remains

unchanged. while(copy!=0) //loop to calculate the

number of digits in the number. {

copy/=10;

count++;

Digit_Seperation ob=new Digit_Seperation(); //object of the

class is created. ob.digit(n,count);

}
Input:
Enter the number: 589612

Output:
The array containing the digits of the number is:
5,8,9,6,1,2. The final number is: 986521
VDT

Name Datatype Description


a[] int This array stores the digit of the number as its respective elements.
Loop control variable to initialize the digits of the number to the respective
i int elements of the array.
n int This variable is the number inputted by the user.
This variable is the value of the number of digits present in the user inputted
count int number.
Loop control variable used in selection sort, arranging array into descending
j int order.
small int Variable storing the value of the respective element of the array in the loop.
Temporary variable storing value of the element in the 'pos'th index of the
temp int array,used in selection sort.
Variable to change accordingly in both of the selection sort loops storing values
pos int of different indices.
h int Variable copies the value of count.
Variable holds the value of the newly created number after array is sorted and
f int elements are merged.
copy int Variable copying the value of n, used in checking the number of digits in n.
Digit_Sepe
ob ration Object of class Digit_Seperation.
Q20) Write a menu-driven program to print these
patterns with the user choosing the number of rows to
be printed in each case:

i) # # # # # # #
######
#####
####
###
##
#

ii) 9
898
78987
6789876
567898765
45678987654
3456789876543
234567898765432
12345678987654321
Source Code:
import java.util.*;

class Patterns

public void first_pattern(int rows) //method to print the first pattern.

System.out.println();

int copy=rows; //copies the number of rows to be created.

int copy2=rows;

for(int k=0;k<=copy2;k++) //loop to create the pattern is started.

for(int j=0;j<copy2-copy;j++)

System.out.print(" "); //the required number of spaces are created.

for(int i=0;i<=copy;i++)

System.out.print("# "); //the hashtag is created to create the

triangle pattern. }

copy=copy-1;

System.out.println();

//with each iteration, one more space is printed,and the number of


hashtags start reducing.

System.out.println("The pattern has been printed.");

public void second_pattern(int rows) //method to create the


second pattern. {

for (int z=rows;z>=1;z--) //loop to create the pattern is started.


{

for (int j=1;j<=z*2;j++) //loop to print the respective number of spaces

for each row. {

System.out.print(" ");

for (int j=z;j<=9;j++) //loop to print the first half of

numbers in a row. //in case there is only one number,

then it prints the number.

System.out.print(j+" ");

for (int j=rows-1;j>=z;j--) //loop to print the second half of

numbers in a row. {

System.out.print(j+" ");

System.out.println(); //moves to the next line.

System.out.println();

System.out.println("The pattern has been printed.");

public static void main() //method to call the respective pattern.

int n=0;
Patterns obj=new Patterns();

Scanner sc=new Scanner(System.in);

System.out.println("Enter 1 to print the first pattern.");

System.out.println("Enter 2 to print the second pattern.");

System.out.println();
System.out.print("Input: ");

n=sc.nextInt();

//Statements to define the menu driven program to the

user are given. switch(n) //switch case is started.

case 1: //for the first pattern.

System.out.print("Enter the number of rows: ");

int rows=sc.nextInt();

System.out.println("The first pattern is being printed: ");

System.out.println();

if(rows>0)

obj.first_pattern(rows); //respective method is called.

else

System.out.println("The input has been determined to be invalid,


please run the program again.");

break;

case 2:

System.out.print("Enter the number of rows,not more than 9: ");

//9 is the limit as the input should be a single digit number.

int rows=sc.nextInt();

if((rows<10)&&(rows>0)) //Verifies the user input is valid.


{

System.out.println("The second pattern is being printed: ");

System.out.println();

obj.second_pattern(rows); //respective method is called.

else
{

System.out.println("The input has been determined to be invalid,


please run the program again.");

break;

default: //if the input is other than 1 or 2.

System.out.println("The input has been determined to be invalid,


please run the program again.");

}
First Case:
Enter 1 to print the first
pattern. Enter 2 to print
the second pattern.

Input: 1
Enter the number of rows: 6

Output:
The first pattern is being printed:

#######
######
#####
####
###
##
#
The pattern has been printed.
Second Case:
Enter 1 to print the first pattern.
Enter 2 to print the second pattern.

Input: 2
Enter the number of rows, not more than 9: 9

Output:
The second pattern is being printed:

9
898
78987
6789876
567898765
45678987654
3456789876543
234567898765432
12345678987654321

The pattern has been printed.


VDT
Name Datatype Description

n int Variable to operate the switch case, taking a user inputted value.

rows int Variable to store the number of rows of the pattern to print.

copy int Variable to copy the number of rows in the method to print the first pattern.

copy2 int This is the second variable to copy the number of rows in the method to
print the first pattern.

k int Loop control variable in the process to print the first pattern.

j int Loop control variable in the loop to print the spaces in the first pattern.

i int Loop control variable in the loop to print the hashtags in the first pattern.

z int Loop control variable which stores the value of the number of rows in
the second pattern.
obj Pattern
Object of the class Pattern.

----------------------X----------------------
Acknowledgement

Firstly, I would like to thank God for keeping all of us safe


in these uncertain times.

I would like to thank my teacher, Mrs. Dorothy Flynn, for


assigning this project and for her constant guidance.

I would also like to thank my parents, for constantly reminding


me what to do , and not letting me fall asleep and my brother
for allowing me to go to him for his help and constant support.

Thank You

You might also like