0% found this document useful (0 votes)
25 views

Final Java Programs Organized

Uploaded by

mimiko.girl911
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Final Java Programs Organized

Uploaded by

mimiko.girl911
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 193

Question 1.

Class name : digit


Data members : int n
Functions
void input() : To input max 3 digit number
int check(int y) : Returns 1 if y is positive else it return 0
int length(int u) : Returns length of u
void print( ) : Check that number is of valid length and print in
following format-
Input: 176
Output: positive One Hundred and Seventy Six

Input: -96
Output: negative Ninety Six

Input: 123461
Output: “wrong input only 3 digit number is allowed
!”.
Answer 1.

import java.io.*;
class digit
{
private int n;
public void input()throws IOException
{
BufferedReader kd = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number(max. three digits allowed)");
n = Integer.parseInt(kd.readLine());// storing in variable n
}

public int check(int y)


{
if(y>0)
return 1; //returning 1 if number is positive
else
return 0; //returning 0 if number is negative
}
public int length(int u)
{
int f = 0;
do
{
u = (u/10);
f++; //incrementing f until u does not become zero, hence calculating the number of
digits
}
while(u != 0);
return f;
}

public void print()throws IOException


{
digit ob = new digit();
ob.input();
if(ob.length(ob.n)>3)
{
System.out.println("Wrong input only 3 digit number is allowed !");
// Printing appropriate message if number is more than 3
digts.
}
if(ob.check(ob.n) == 1) // checking wherther number is positive
{
System.out.print("Positive ");
}
else // checking wherther number is positive
{
System.out.print("Negative ");
ob.n = Math.abs(ob.n); // Removing negative sign
}
String af[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"};
String as[] = {"tweenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"};
if(ob.n < 20)
{
System.out.print(af[ob.n]); //Printing the number in words if it is less than twenty
}
else if(ob.n == 20)
{
System.out.print("Twenty "); //Printing the number in words if it is twenty
}
else if(ob.n < 100)
{
int x = (ob.n)%10; // Finding the last digit i.e.ones place
int y = (ob.n)/10; //Finding number at tens place
System.out.print(as[y-1]+" " +af[x]);
}
else if(n == 100)
{
System.out.print("Hundred "); //Printing the number in words if it is Hundred
}
else if(n != 20 || n != 100)
{
int x = (ob.n)%10; // Finding the last digit i.e.ones place
int y = (ob.n)/10;
int z = y%10; //Finding number at tens place
int p = y/10; //Finding number at hundredth place
System.out.print(af[p] + " hundred ");
System.out.print(as[z-1]+ " " +af[x]);
}
}
public void main(String args[])throws IOException
{
digit mn = new digit();
mn.print(); //Calling function print().
}
}
OUTPUT 1.

Enter a number(max. three digits allowed)


234
Positive two hundred thirty four

Algorithm 1.

1. Start.
2. Enter a number, of maximum three digits. (n - Input from user)
3. Calculate the length of ‘n’.
4. If the length is more than three, goto step 5, otherwise goto step 6.
5. Print message “"Wrong input only three digit number allowed". Goto step 27.
6. Check that whether the number is greater or less than zero.
7. If it is greater than zero, print “Positive”, otherwise print “Negative”.
8. Change the number ‘n’ to positive by calculating its absolute value and assigning it
again to ‘n’.
9. Define an array “af” containing twenty words from “zero” to “nineteen”.
10.Define an array “as” containing nine elements with first elements as null character
and rest of the elements as multiples of ten from Twenty to Ninety.
11.Check if the number is less than twenty, if yes goto step 16.
12.Check if number is equal to twenty, if yes goto step 17.
13.Check if number is less than hundred, if yes goto step18
14.Check if number is equal to hundred, if yes goto step 21.
15.Otherwise goto step 22.
16.Print nth index of array “af”. Goto step 27.
17.Print “Twenty”. Goto step 27.
18.Extract last digit of “n” and store it in integer type variable “x”.
19.Divide n by 10 and store it in integer type variable y.
20.Print y-1 th index of as followed by space and x th index if af. Goto step 27.
21.Print “Hundred”. Goto step 27.
22.Extract last digit of n and store it in integer type variable ‘x’.
23.Divide n by 10 and store it in integer type variable ‘y’.
24.Extract last digit of y and store it in variable ‘z’.
25.Divide y by 10 and store it in variable ‘p’.
26.Print p th index of af followed by “hundred” followed by z-1 th index of as followed
by x th index of af. Goto step 27.
27.Stop.
Question 2.

Consider following inheritance path where Student is Base class.


student : Base Class name
name : String type
address : String
type rollno : int
type

commerceStud : Derived Class name


ent
marksEco : int type
marksAcc : int type

scienceStudent : Derived Class name


marksPhy : int type
marksMaths : int type

Above classes are showing datamembers.


Student class has all its data members as protected.
But commerceStudent and scienceStudent have their data members as private

Write constructors for passing various attributes for all the three classes.
And a function Average( ) for the class commerceStudent and scienceStudent
which returns average marks.
Also write display( ) for all the three classes to display the data members and
average too.
Write main( ) for above class.
Answer 2.

import java.io.*;
class inheritingClasses
{
public static void main(String args[])throws IOException
{
BufferedReader inv = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your choice 1- Commerce & 2- Science");
int ch = Integer.parseInt(inv.readLine());
switch(ch)
{
case 1: commerceStudent obj=new commerceStudent(); //creating object for Case
1
obj.display();
break;
case 2: scienceStudent obj1=new scienceStudent(); //creating object for cASE 2
obj1.display();
break;
default: System.out.print("Invalid choice !");
break;
}
}
}

class student
{
protected String name, address;
protected int rollno;
student()throws IOException
{
BufferedReader inv = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter rollno ");
rollno = Integer.parseInt(inv.readLine()); //Storing student roll no in variable
System.out.println("Enter name ");
name = inv.readLine(); //storing student name in
variable
System.out.println("Enter address ");
address = inv.readLine(); //storing student address in variable
}
public void display()
{
System.out.println(name+ " " +address+ " "+rollno); // printing student details
}
}

class commerceStudent extends student


{
private int marksAcc, marksEco;
commerceStudent()throws IOException
{
super(); //calling constructor of base class
BufferedReader inv = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter marks in acc and eco ");
marksAcc = Integer.parseInt(inv.readLine()); //storing student marks in
accounts
marksEco = Integer.parseInt(inv.readLine()); //storing student marks in
economics
}
public double average()
{
double avg = ((marksEco+marksAcc)/2); //calculating average of commerce
//student marks
return avg;
}
public void display()
{
super.display();
System.out.println("Marks in economics " +marksEco); //displaying marks in
economics
System.out.println("Marks in accounts "+marksAcc);
double a = average();
System.out.println("Average marks "+a); //displaying average marks
}
}

class scienceStudent extends student


{
private int marksMaths, marksPhy;
scienceStudent()throws IOException
{
super(); //calling constructor of base class
BufferedReader inv = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter marks in maths and physics ");
marksPhy = Integer.parseInt(inv.readLine()); //Storing marks in physics
marksMaths = Integer.parseInt(inv.readLine()); //Storing marks in maths
}
public double average()
{
double avg = ((marksMaths+marksPhy)/2); //calculating average
science marks
return avg;
}
public void display()
{
super.display(); //calling diplay function of BASE
class
System.out.println("Marks in maths ARE- "+marksMaths); //displaying marks in
maths
System.out.println("Marks in physics ARE- " +marksPhy); //displaying marks in
physics
double a = average();
System.out.println("Average marks " +a); //displaying average science marks
}
}OUTPUT 2.

enter your choice 1-commerce 2-science


2
Enter rollno
16
Enter name
Syed Nabeel Ud-din Ahmed Kirmani
Enter address
124 – Gulshan Enclave, Khurram Nagar, Lucknow, Uttar Pradesh, India.
Enter marks in physics and maths
85
90
Name Syed Nabeel Ud-din Ahmed Kirmani
Roll no 16
Address 124 – Gulshan Enclave, Khurram Nagar, Lucknow, Uttar Pradesh, India.
Marks in maths ARE-90
Marks in physics ARE-85
Average marks 87.0

Algorithm 2.

1. Start
2. Define variables (“name”, “address” , “rollno”, “marksAcc”, “marksEco”, “marksPhy”,
“marksMaths”).
3. Ask user to enter choice 1-Commerce, 2-Science(ch - Input from user)
4. If choice is 1, goto step 9, otherwise proceed
5. Input the details of Science Student.
6. Input the marks of Science Student and store them in marksPhy & marksMaths.
7. Print the details of Science Student along with marks.
8. Calculate average of the two marks and print it.
9. Goto step 14
10.Input the details of Commerce Student.
11.Input the marks of Commerce Student and store them in marksAcc and marksEco.
12.Print the details of commerce Student along with marks.
13.Calculate the average of the two marks and print it.
14.Stop.
Question 3.

Define a class – Recurstring


Data String str
members :
String revst
Functions :
Recurstring ( : constructor
)
void Input( ) : To input any string in str
void rev(int) : To store the reverse of str in revst using
recursion
void check( ) : To check that str is palindrome or not.
Also write main() for above class.
Answer 3. import
java.io.*; class
Recurstring
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private String str;
private String revst;
char ch;
Recurstring()
{
str = " ";
revst = " ";
}
public void main()throws IOException
{
Recurstring ob = new Recurstring();
ob.input();
ob.check();
}
void input()throws IOException
{
System.out.println("Enter String- ");
str = in.readLine(); //Storing string in str
}
void rev(int i)
{
int l = str.length(); //Storing length of str in l
if(i < l)
{
ch = str.charAt(i); //Extracting character from position i of string str
revst = ch + revst; //Storing reverse of string in str
rev(i+1);
}
}
void check()
{
rev(0);
if(str.equals(revst)) //checking if str and revst are the same
{ System.out.println("Palindrome"
);
}
else
{
System.out.println("Not a Palindrome");
}
}
}
OUTPUT 3.

Enter String-
MAMMA
Not a Palindrome

Algorithm 3.

1. Start.
2. Enter a string. (str - Input from user)
3. Calculate length of str and store it in “l”.
4. Define an integer type variable “i” and initialize it as 0.
5. Extract the i th character of str and concatenate it with an empty string revst.
6. If i is less than “l”, increment i by 1 and go back to step 5.
7. Otherwise check if str and revst are equal.
8. If yes then print message “Palindrome”
9. If no, print message “Not a Palindrome”.
10.Stop.
Question 4.

Define a class decimal2Binary


Data members:
int n : Number to be converted to its binary equivalent
int s : To store binary equivalent
int i : To store the incremental power
Functions
decimal2Binary( : Constructor
)
void input( ) : To input number in n.
void convert(int) : To convert any number to its binary equivalent using
recursion.
void display() : To print n and its binary equivalent s.

Also write main( ).


Answer 4.

import java.io.*;
class decimal2Binary
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
protected int n, s, i;
decimal2Binary()
{
n = 0;
s = 0;
i = 1;
}
void input()throws IOException
{
System.out.println("Enter n ");
n = Integer.parseInt(in.readLine()); // Storing number in variable n
}
void convert(int y)
{
if(y > 0)
{
int r = y % 2;
s = s + (r*i); i
= (i*10);
convert(y/2);
}
}
void display()
{ convert(n);
System.out.println("Number = " +n);
System.out.println("Binary equation = " +s);
}
void main(String args[])throws IOException
{ input();
display();
}
}
OUTPUT 4.

Enter n
234
Number = 234
Binary equation = 11101010

Algorithm 4.

1. Start
2. Enter number whose binary equivalent is to be found out.( n - Input from user)
3. Create a copy of “n” and store it in “y”, and define integer type variable “i” with initial
value 1
4. Divide y by 2, multiply the remainder by i. (i.e it is either 0 or 1)
5. Multiply remainder by i and add it to s.
6. Multiply i by 10.
7. If y is greater than 0 , go back to step 3.
8. Print “n” and “s”.
9. Stop.
Question 5.

A Sentence is terminated by either “.” , “!” or “?” followed by a space.


Input a piece of text consisting of sentences.
Assume that there will be a maximum of 10 sentences in block letters.
Class name : Sentence
Data members
String str : To store sentence
Member functions :
void input( ) : To input any string in str
int vowel(char) : To return 1 if character is a vowel else return 0
int words(String s) : To return number of words in string s.
void out_graph () : : To display the output and graph as follows
Input
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF LUCK
Output
SENTENCE NO OF VOWELS NO OF
WORDS
1 2 1
2 5 3
3 8 4
4 3 3
GRAPH
Sentenc No of words/Vowels
e
1 VVVVVV
WWW

2 VVVVVVVVVVVVVVV
WWWWWWWWW

3 VVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWW

4 VVVVVVVVV
WWWWWWWWW

Scale used is 1 : 3
Answer 5.

import java.util.*;
import java.io.*;
class Sentence2
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
String str;
void input()throws IOException
{
System.out.println("Enter a string ");
str = b.readLine(); //inputting string from user
str += " ";
}
public static void main()throws IOException
{
new Sentence2().out_graph();
}
int vowel(char c)
{
if(c == 'a'| c == 'e' | c == 'i' | c == 'o' | c == 'u' | c == 'A' | c == 'E' | c == 'i' | c == 'O' | c == 'U')
//checking whether c is a vowel
return 1;
return 0;
}
int words(String s)
{
StringTokenizer st = new StringTokenizer(s); //tokenizing string s
return st.countTokens(); //returning number of tokens
}
void out_graph()throws IOException
{ input();
int n = 0;
for(int i=0; i<str.length(); i++)
{
char c = str.charAt(i); //extracting one character at at time to count number of
sentences
if(i != (str.length()-1))
if(((c == '.' | c == '!' | c == '?') && str.charAt(i+1)) == ' ')
n++;
}
String s[] = new String[n]; //creating an array to store
int k=0;
for(int i=0; i<(str.length()-1); i++)
{
char c = str.charAt(i);
s[k] = s[k] + c; //storing each sentence in array s
if(((c == '.' | c == '!' | c == '?') && str.charAt(i+1)) == ' ')
{
k++;
i++; //for minimizing number of iterations
}
}
System.out.println("SENTENCE " + " \t " + "NO OF VOWELS " + " \t " + "NO OF WORDS
");
for(int i=1; i<=n; i++)
{
int v = 0;
for(int j=0; j<s[i-1].length(); j++)
{
char c=s[i-1].charAt(j);
if(vowel(c) == 1)
v++;
}
System.out.println(i+" \t\t " +(v-1)+ " \t\t " +words(s[i-1]));
//printing number of words and number of
vowels
}
System.out.println("Sentence \t No. of words/vowels");
for(int i=1; i<=n; i++)
{
int vow = 0;
for(int j=0; j<s[i-1].length(); j++)
{
char c = s[i-1].charAt(j);
if(vowel(c) == 1)
vow++;
} System.out.print(i+"\t\t");
for(int j=1; j<=3*(v-1); j++)
System.out.print("V");
System.out.println();
System.out.print(" \t\t");
for(int j=1; j<=3*words(s[i-1]); j++)
System.out.print("W");
System.out.println("\n");
}
}
}
OUTPUT 5.

Enter a string
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF LUCK.
SENTENCE NO OF VOWELS NO OF WORDS
1 2 1
2 5 3
3 8 4
4 3 3

Sentence No of words/vowels
1 VVVVVV
WWW

2 VVVVVVVVVVVVVVV
WWWWWWWWW

3 VVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWW

4 VVVVVVVVV
WWWWWWWWW

Algorithm 5.

1. Start
2. Define class variables, “str” and “len”, to store string and its length respectively.
3. Input the string .(str - Input from user)
4. Add at blank space at the end of “str”.
5. Store the length of string in variable “len”
6. Count the number of " . ", " ! " or " ? " follows by space in the string and store it in “n”
so as to find number of sentences.
7. Count the number of spaces in each sentence so as to find the number of words in
each sentence.
8. Count the number of vowels in each sentence.
9. Print the no. of words and no. of vowels in each sentence in the given format.
10.Print the graph showing number of words and vowels in each sentence as in
question in ratio 1 : 3.
11.Stop.
Question 6.

A class stringModifications has been defined with the following details


Class name : stringModifications

Data member
Str : stores the string
Len : to store the length of the string

Member function
void read() : to accept the string in Uppercase alphabets
void putin(int, char) : to insert a character at the specified
position in the string and display the
changed string.
void takeout(int) : to remove character from the specified
position in the string and display the
changed string.
void change() : to replace each character in the original
string by the character which is at a
distance of 2 moves ahead. For
example :“ABCD” becomes “CDEF”
“ZYZ” becomes “ZAB”
Specify the class stringModifications giving details of the functions:
void read()
void putin(int, char)
void takeout(int) and
void change().
The main function need not be written.
Answer 6.

import java.io.*;
import java.lang.*;
class stringModifications
{
private String str;
private int len;
void read()throws IOException
{
BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string in Uppercase ");
str = ob.readLine(); //storing the string in varible str
len = str.length(); //calculating the length of the string
}
void putin(int p, char ch)
{
String strc1 = str; //creating copy of the string
String s = " ";
for(int i=0; i<p; i++)
{
s = s + strc1.charAt(i); //extracting one char at a time till required
poaition is found
}
String s1 = strc1.substring(p,len); //extracting a part of string from required
position till the end
s = s + ch + s1; //inserting
System.out.println("The modiied string after insertion is " + s);
}
void takeout(int t)
{
String strc2 = str;
String f = " ";
f = (strc2.substring(0,t) + strc2.substring(t+1,len)); //concatenating both strings
System.out.println("The modiied string after deletion is " + f);
}
void change()
{
System.out.println("Coded string is ");
for(int k=0; k<len; k++)
{
int u = 0;
char c = str.charAt(k);
u = (int)c;
if(u>=65 && u<=88) //ASCII value of A is 65 and X is 88
{
u = u + 34;
}
else
if(u == 89) //for Y
{
u = 65;
}
else
if(u == 90) //for Z
{
u = 66;
}
System.out.print((char)u);
}
}
public void main(String args[])throws IOException
{
stringModifications kd = new stringModifications();
BufferedReader pt = new BufferedReader(new InputStreamReader(System.in));
kd.read();
System.out.println("Enter position ");
int i = Integer.parseInt(pt.readLine()); //Asking user to enter position
//where character is to be inserted
System.out.println("Enter character to be inserted ");
char ch = (char)pt.read();
BufferedReader ak = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter position from where character is to be deleted ");
//Asking user to enter a position
int d = Integer.parseInt(ak.readLine());
kd.putin(i,ch);
kd.takeout(d);
kd.change();
}
}
OUTPUT 6.
Enter the string in Uppercase
DOUGHNUTS
Enter position
2
Enter character to be inserted
E
Enter position from where character is to be deleted
3
The modified string after insertion is DOEUGHNUTS
The modified string after deletion is DOUHNUTS
Coded string is fqwijpwvu

Algorithm 6.

1. Start.
2. Enter a string in Uppercase and store it in variable. (str- Input from user)
3. Enter the position where a character is to be inserted. (i - Input from user)
4. Enter a character to be inserted at position “i”. (ch - Input from user).
5. Enter position from where character is to be deleted. (d - Input from user)
6. Create a copy of the entered string. (strc1-à str)
7. Declare an empty string “s”.
8. Extract character from position “i” by one from “strc1” and concatenate it with “s”.
Increment i by 1.
9. If i is less than the required position , go back to step 7.
10.Define a string “s1” & store a substring of “strc1” in it.
11.concatenate “s” with “ch” and “s1”.
12.Print string ‘s’.
13.Create a copy of “str” and store it in “str2”.
14.Store a substring of “strc2” from initial position to one less than “d” and another
substring from one greater than “d” till the end of “strc2” in a string “f”
15.Print the string f.
16.Extract a character one by one from str.( ‘c’ contains the extracted character)
17.Find its ASCII code by type conversion. (“u” contains the ASCII value of c)
18.If “u” is greater than or equal to 65 and less than or equal to 88, add 34 to u.
19.Other wise if “u’ is 89, re-initialize u to 65.
20.Other wise if “u’ is 90, re-initialize u to 66.
21.Convert u to character type by using type conversion, and print it.
22.Go back to step 16 till end of string is reached.
23.Stop.
Question 7.

You are given a string with English sentences as data. You have to read it and
output after formatting it so that each sentence is on a new line with no leading
blanks. A sentence is recognized by the following pattern: Full stop, followed by a
space, followed by a capital letter. Note that just a full stop by itself does not
indicate a sentence since full stop may be a part of a decimal number.
Class name : format
Data members
str : To store the given string
len To store the length of the string
Format () : Constructor
Void read_string : Reads the string from the input.
int is_end_of_sentence (int i) : Returns 1 if the end of a sentence has
been reached at the character position ‘i’
in the string, 0 otherwise
void format_string () : Using the method is_end_of_sentence()
formats and outputs the given string in
such a manner that each sentence is on a
new line with no leading blanks.
Specify the class format write the main( ) function.
Answer 7.

import java.io.*;
class format
{
private String str;
private int len;
format()
{
str = " ";
len = 0;
}
public void read_string()throws IOException
{
BufferedReader mb = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String ");
str = mb.readLine();
len = str.length();
System.out.println();
}
public int is_end_of_sentence(int i)
{
if(str.charAt(i) == '.' && str.charAt(i+1) == ' ' && (str.charAt(i+2)) >= 'A' && (str.charAt(i+2))
<= 'Z')
return 1;
else
return 0;
}
public void format_string()
{
for(int c=0; c<(len-2); c++)
{
if(is_end_of_sentence(c) == 1)
{
System.out.println( str.substring(0,c) );
str = str.substring(c+2, len);
c = 0;
len = str.length();
}
}
System.out.println( str );
}
public void main(String args[])throws IOException
{
format ob = new format();
ob.read_string();
System.out.println("The formatted string is ");
ob.format_string();
}
}
OUTPUT 7.

Enter String
Hello Daksh. How is Sarah?

The formatted string is


Hello Daksh.
How is Sarah?

Algorithm 7.

1. Start.
2. Enter a string. (str - Input from user)
3. Calculate its length and store it in “len”.
4. Define a variable “c” with initial value 0.
5. Extract the c th character of str.
6. If it is a fullstop and the c+1 th character is a space and if the n+2 th character is
greater than or equal to ‘A’ and less than or equal to ‘Z’ goto step 8.
7. Otherwise goto step 11.
8. Print substring of str from 0 to c.
9. Change shorten str to from c+2 th index till len-1 th index and store new length of
str in len.
10.Re initialize c as zero. Goto step 5.
11.Increment c by one.
12.If c is equal to len-2, goto step 14.
13.If not goto step 5.
14.Print str.
15.Stop.
Question 8.

A college maintains all the list of its students graduating every year. At the end of
the year, the college produces a report that lists following :

Year :_
No. of working Graduates :_
No. of non-working Graduates :_

Details of the topmost Scorer


Name :_
Age :_
Subject :_
Ave Marks :_
First Division :_ %

Write a Program that uses the following inheritance path for the below classes:
Person (Base Class) :(name, age, roll no, percentage marks)
GraduateStudent (Derived Class) :(Subject, employed)

Design classes with functions of your own choice and display the list as shown
above in main(). Input records for 10 Graduate Students and display the list.
Answer 8.

import java.io.*;
class graduate
{
graduateStudent ob[] = new graduateStudent[10];
int w = 0; //To store number of working stdents
char ch = ' ';
public void main(String args[])throws IOException
{
BufferedReader kd=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter year ");
int yr = Integer.parseInt(kd.readLine()); //Storing academic year
System.out.println("Enter number of students ");
int j = Integer.parseInt(kd.readLine()); //Storing no of graduating students
for(int i=0; i<j; i++)
{
ob[i] = new graduateStudent();
}
for(int i=0; i<j; i++)
{
ch = ob[i].employed;
if(ch == 'Y') //checking work status
{
w++;
}
}
int nw = (j-w), pos = 0, f = 0;
double t = 0.0d, big=0.0;
for(int i=0; i<j; i++)
{
double m = ob[i].percent;
if(big < m)
{big = m; //updating the top most score
pos = i; //updating corresponding position in array
}
if(m > 60.0)
{
f++; //counting number of first divisioners
}
t = t + m;
}
t = (t/j);
System.out.println("Year- " +yr); System.out.println("No.
of working graduate- " +w); System.out.println("No. of
non working graduate- " +nw);
System.out.println("Details of Top most scorer- ");
System.out.println(" ");
ob[pos].display(); System.out.println("Avgerage marks "
+t); System.out.println(((100*f)/j)+ "% are first
divisioners ");
}
}

class person
{
protected String name;
protected int age,roll;
double percent;
person()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Name ");
name = br.readLine(); //storing student name
System.out.println("Enter Age ");
age = Integer.parseInt(br.readLine()); //storing student age
System.out.println("Enter Roll No. ");
roll = Integer.parseInt(br.readLine()); //storing student rol number
System.out.println("Enter Percent ");
percent = Double.parseDouble(br.readLine()); //storing student percentage
}
void display()
{
System.out.println("Name- " +name);
System.out.println("Age- " +age); //Displaying details of top scorer
System.out.println("Roll.No.- " +roll);
System.out.println("Percent- " +percent);
}}
class graduateStudent extends person
{
String subject; char employed;
graduateStudent()throws IOException
{
super();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Subject ");
subject = br.readLine(); //Storing student subject
System.out.println("Enter Y if employed and N if unemployed");
employed = (char)br.read(); //storing working status
}
void display()
{ super.display();
System.out.println("Subject- " +subject);
}
} //end of class
OUTPUT 8.

Enter year
2009
Enter number of students
3

Enter Name
Nabeel
Enter Age
17
Enter Roll No.
16
Enter Percent
84
Enter Subject
Science
Enter Y if employed and N if unemployed
Y

Enter Name
Harsh
Enter Age
17
Enter Roll No.
17
Enter Percent
80
Enter Subject
Science
Enter Y if employed and N if unemployed
N

Enter Name
Dixy
Enter Age
17
Enter Roll No.
10
Enter Percent
88
Enter Subject
Science
Enter Y if employed and N if unemployed
N

Year-2009
No. of working graduate-1
No. of non working graduate-2
Details of Top most scorer-
Name-Dixy
Age-17
Roll.No.-16
Percent-88.0
Subject-Science

Avgerage marks 84.6


100% are first divisioners

Algorithm 8.

1. Start
2. Enter the year.(yr -Input academic year)
3. Enter number of graduating students.(y -Input from user)
4. Define variable “i” with initial value 0.
5. Define a variable “w” for storing number of employed students.
6. Define a variable “nw” for storing number of unemployed students.
7. Enter name, age , roll number, percentage and work status.(name, age, roll,
percent -Input from user).
8. If work status is employed then, increment w by 1.
9. If work status is unemployed then, increment nw by 1.
10.Increement i by 1.
11.If i is less than y, then go back to step 5.
12.Display the year, .
13.Display number of working candidates by printing w.
14.Display number of nonworking candidates by printing nw.
15.Find the maximum entered marks.
16.Display the corresponding details of the candidate.
17.Calculate the average marks of all the students by using formula ∑marks/y .
18.Also calculate percentage of first divisioners by using formula (((no. of students
scoring 60% and above)/y)* 100) .
19.Display average marks and percentage of first divisioners.
20.Stop.
Question 9.
A class frequencyCalculation is defined, for finding out the mode and the
modefrequency.
Mode : The most frequently occurring mark in the class. If
two or more marks occur equally frequently then the
highest of these marks is the mode
modefrequency : Frequency at mode

You can make following assumptions:


The class has 10 students, the maximum marks anyone can get are 100 and
minimum is 0, all the student marks are whole numbers.
Important- You are not allowed to sort the marks.

Some of the member functions/methods of frequencyCalculation are given below:


Class name : FrequencyCalculation

Data members
marks[ ] : An int array to store the marks of 10 students
mode : To store the mode
freqatmode : To store the frequency at node

Member functions
frequencyCalculation() : Constructor
Void readmarks() : For reading the marks into the array
int getmode() : For finding and returning the mode
int getfreqatmode() : For returning the frequency at mode
void : A single function that calculates both mode and
calcmodeandfrequency() frequency at mode.
Write all the functions and write main() also.
Answer 9.

import java.io.*;
class frequencyCalculation
{
private int marks[] = new int[10];
int mode;
int freqatmode;
frequencyCalculation()
{
mode = 0;
freqatmode = 0;
for (int i=0; i<10; i++)
marks[i] = 0;
}
void readmarks()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Marks");
for(int i=0; i<10; i++)
{
marks[i] = Integer.parseInt(br.readLine());
//Storing marks of ten students
// in array marks[]
}
calcmodeandfrequency() //Calculating mode and mode frequency
}
void calcmodeandfrequency()
{
mode=getmode(); // Storing mode in "mode" by invoking
//function getmode()
freqatmode=getfreqatmode();//Storing mode frequency in
//"freqatmode" by invoking function getfreqatmode().
System.out.println("Mode = "+mode);//Printin mode
System.out.println("Frequency = "+freqatmode);//Printing freqatmode
}
int getmode()
{
int m = 0; //Variable for storing mode
int f = 0; //Variable for storing mode frequency
for(int i=0; i<=100; i++)
{
int s = 0;
for(int j=0; j<10; j++)
{
if(marks[j] == i)
{
s++;
}}
if(s >= f)
{
f = s; //Storing current mode frequency
m=i; //Storing current mode.
}}
return m; // returning mode
}
int getfreqatmode()
{
int f = 0; // variable for storing mode frequency
for(int i=0; i <= 100; i++)
{
int s = 0;
for(int j=0; j<10; j++)
{
if(marks[j] == i)
{
s++; // calculating frequency of current i
}}
if(s >= f)
{
f = s; // if current i is > than currrent mode freq., storing freq. if i in f
}}
return f; //returning mode frequency
}
public static void main()throws IOException
{
frequencyCalculation ob = new frequencyCalculation();
ob.readmarks();
}
}
OUTPUT 9.

Enter Marks
55
34
67
55
54
67
89
55
67
77
Mode = 67
Frequency = 3

Algorithm 9.

1. Start.
2. Enter the marks of ten students. (marks[] contains marks of ten students)
3. Define a variable “mode” for storing mode. Initialize it as zero.
4. Define a variable “freqatmode” for storing mode frequency. Initialize it as zero.
5. Define a variable “i” for finding mode.
6. Define a variable “s” for storing mode frequency.
7. Check all elements of marks[] if they are equal to i.
8. Increements by 1. Goto step 10.
9. If s is greater than mode frequency, assigns to freqatmode, and i to mode. Goto
step 10.
10.Increment i by 1.
11.If i is less than or equal to 100, goto step 7.
12.If not , then print “mode” and “freqatmode”.
13.Stop.
Question 10.

Declare a class “point” which contains following-

Data members -
a double dimensional array,
row size,
col size,
row index,
col index and
other data members as
required.
Member functions
(a) void : To input a double dimensional array in the form of matrix of
get_array() given rows and columns.
(b) void : To print the entered matrix.
display_mat()
(c) void : To find and print the saddle point from the entered matrix (a
check_saddle() saddle point from any matrix exists in all the rows if and only
if the smallest element from each row should be greatest in
the corresponding column).
Also write main()

Consider the following example


Input matrix
3574
1649
2475

The output –
saddle point is 3 (row=0 and column =0)
Answer 10.

import java.io.*;
class point
{
private int r;
private int c;
private int a[][];
public void get_array()throws IOException
{
BufferedReader inv = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter rows");
r = Integer.parseInt(inv.readLine()); //storing number of rows
System.out.println("Enter columns");
c = Integer.parseInt(inv.readLine()); //storing number of columns
a = new int[r][c]; //making a 2D array of r rows and c colmns
for(int i=0;i<r;i++)
{
System.out.println(" Enter the elements in the row " +(i+1));
for(int j=0; j<c; j++)
{
a[i][j] = Integer.parseInt(inv.readLine()); // entering elements row-wise.
}
}
}
public void check_saddle()
{
int b;
if(r < c)
{
b = r;
}
else
{
b = c;
}
int s[] = new int[r]; //creating an array to store smallest element in each row
for(int i=0; i<r; i++)
{
s[i] = a[i][0];
for(int j=0; j<c; j++)
{
if(a[i][j] < s[i])
s[i] = a[i][j]; //updating the smallent in row i if a smaller
element is found
}
}
int l[] = new int[c]; //creating an array to store largest element in column
for(int i=0; i<c; i++)
{
l[i] = a[0][i];
for(int j=0; j<r; j++)
{
if(a[j][i] > l[i])
{
l[i] = a[j][i]; //updating the largest element if a larger element is found
}
}
}
int sp = 0;
for(int k=0; k<b; k++)
{
if(l[k] == s[k]) //checking if smallest element of row k is largest in corresponding
column
{
System.out.println("Sadlle point is "+ l[k]);
sp = l[k];
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
if(a[i][j] == sp)
{
System.out.print("row= " +i+ " , " +"column= "+j); //printing position of saddle point
break;
}}
break;
}}}}
public void display_mat()throws IOException
{ get_array();
System.out.println("INPUT");
System.out.println();
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println(" ");
}
}
public static void main(String args[])throws IOException
{
point obj = new point();
obj.display_mat();
System.out.println();
obj.check_saddle();
}
}}
OUTPUT 10.

Enter rows
3
Enter columns
4
Enter the elements in the row 1
3
5
7
4
Enter the elements in the row 2
1
6
4
9
Enter the elements in the row 3
2
4
7
5

INPUT
3574
1649
2475

Saddle point is 3
row= 0 ,column= 0

Algorithm 10.

1. Start.
2. Declare variables (a[ ][ ], row, size, col, rowindex, colindex).
3. Input the double dimensional array and store it in a[ ][ ].
4. Print the double dimensional array as 2 – D matrix.
5. Find the smallest element of each row and store them in an array.
6. Find the greatest element of the corresponding column and store them in an array.
7. If the ith element of both arrays are same then print it and also print its row and
column in array “a[][]”.
8. Increment i by 1 and go back to step 7.
9. Stop.
Question 11.

Define a class w_square


A wondrous square is N X N(N >3) grid which fulfills the following conditions
1 ) it contains integers from 1 to N 2 where each integer appears only once .
2 ) the sum of integers in any row or column is same .
eq N=5

17 24 1 8 15
23 5 7 14 16
15 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Data member
int a[ ][ ] : 2-d array
int N : size

Member functions
Void input ( ) : to input size and create 2-d array of size N
Void generate() : to generate wondrous square matrix of size N
Void print( ) : to print matrix

Also write main().


Answer 11.

import java.io.*;
class w_square //beginning of class
{
private int n;
private int a[][];
public void input() throws IOException
{
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter square side");
n= Integer.parseInt(in.readLine());// storing side of square
a= new int[n][n];//defining an array of n rows and n columns
}
void generate() //Method to generate the wonder square
{
int digit=1,r=0,c=(n/2);
a[r][c]=digit;
do
{ digit+
+; r--;
c++;
if((digit%n)==1)
{ r+=2;
if(r>n-1)
{
r=0;
}
c--;
if(c<0)
{
c=n-1;
}
}
if(r<0)
{
r=n-1;
}
if(c>(n-1))
{
c=0;
}
if(a[r][c]==0)
{
a[r][c]=digit;
}
}while(digit<=(n*n));
}
void print() //Method to print the array
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
System.out.print(a[i][j]+" "+'\t'); //printing the array
System.out.println();
}
}
public static void main(String args[]) throws IOException
{
w_square obj= new w_square(); //Creating object to call oher functions
obj.input();
obj.generate();
obj.print();
}
}

UTPUT 11.

Enter square side


5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Algorithm 11.

1. Input size of wonder square in n.


2. Create a 2d array “a” of dimensions n x n.
3. Initialize digit ← 1 r←0,c←(n/2).
4. Assign a[r][c]=digit.
5. Increment digit and “c” by 1 each and decrement “r” by 1.
6. If (digit modulus n) is not equal to 1 go to step 10
7. Increment “r” by 2
8. If “r” greater than n-1 Let “r” ← 0
9. Decrement “c” by 1 and if “c” less than 0 Let “c” ← n-1
10. If “r” less than 0 Let “r”← n-1
11. If “c” greater than n-1 Let “c”← 0
12. If a[r][c] is equal to 0 Let a[r][c]←digit
13. If digit less than or equal to (n*n) go to step 5
14. Display array a[][]
15. Stop
Question 12.

India Institute of Technology's resource manager has decided to network the


computer resources like printer, storage media etc, so that minimum resources and
maximum sharing could be availed.
Accordingly printers are linked to a centralized system and the printing jobs are
done on a ‘first come first served’ basis only.
This is like the first person’s printing job will get done first and the next person’s
job will be done as the next job in the list and so on.
In order to avoid collision, the restriction is that no more than 20 printing jobs can
be added.

Define the class printJob with the following details:


Class name : printJob

Data members/instance variables


job[ ] : Array of integers to hold the printing jobs.
Newjob : To add a new printing job into the array.
Capacity : The maximum capacity of the integer array.
Front : To point to the index of the front.
Rear : To point to the index of the last.

Member Functions:
printjob ( ) : Constructor to initialize the data member
Capacity = 20, Front = Rear = -1 and to call the function
createJob ( ).
void createjob ( ) : To create an array to hold the printing jobs.
void addjob ( ) : Adds the new printing job to the end of the last printing job,
if possible, otherwise displays the message “printJob is full,
cannot add any more”
void removejob ( ) : Removes the printing job from the front if the printing job is
not empty, otherwise displays the message “printJob is
empty”

Also write the main() function for above class.


Answer 12.

import java.io.*;
class inheritingClasses
{
public static void main()throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
printJob ob = new printJob();
ob.createjob(); //Calling function from class printJob
int choice;
do
{
System.out.println("1. Add element" );
System.out.println("2. Remove element");
System.out.println("3. Print");
System.out.println("4. Exit");
System.out.println("Enter choice");
choice = Integer.parseInt(in.readLine()); //Entering user choice
switch(choice)
{
case 1:
ob.addjob(); //calling function addjob
System.out.println();
break;
case 2:
ob.removejob(); //calling function removejob()
System.out.println();
break;
case 3:
ob.print(); //calling function print
System.out.println();
break;
case 4:
break;
}
}
while(choice != 4);
}
}
class printJob
{
protected int job[];
protected int newjob;
protected int capacity, front, rear;
printJob()
{
capacity = 20;
front = -1;
rear = -1;
createjob();
}
void createjob()
{
job = new int[20]; //Creating Queue
}
void addjob()throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
if(rear >= (capacity-1)) //Checking wherther queue is full or not
System.out.println("overflow");
else
{
rear++;
newjob = Integer.parseInt(in.readLine());
job[rear] = newjob; //Inserting newjob at rear
if(front == -1)
front++;
}
}
void removejob()
{
if((front == -1)&&(rear == -1)||(front > rear))
{ //If queue is empty then printing underflow condition
System.out.println("underflow");
}
else
front++; //Deleting element
}
void print()
{
for(int i = front; i <= rear; i++)
{
System.out.println( job[i] ); //Printing all jobs one by one
}
}
}
OUTPUT 12.

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
1

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
1

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
3

2
3

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
2

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
3

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
3

2
3

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
2

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
3

1. Add element
2. Remove element
3. Print
4. Exit
Enter Choice
4
Algorithm 12.

1. Start.
2. Create an array of 20 integers (int job←new int [20]).
3. Declare a variable ‘choice’ for entering choice.
4. Print messages “1.Add element 2. Remove element 3. Print 4. Exit”
5. Enter choice (choice ← Input from user).
6. If choice is 1
7. Check whether rear is greater than or equal to (capacity-1) (rear points the number
of printing jobs and capacity is equal to maximum number of printing jobs).
8. If above condition is satisfied print”Print Job is full, cannot add any more”.
9. If the above condition is not satisfied then increment rear by one and add a new job,
by taking input from user ,at rearth index of array. Also if front is equal to
-1,increment it by 1.
10.If choice is 2
11.Check whether (front←-1 0 && (rear←-1) || (front >rear) (front is a variable which
points the 1st inputted print job).
12.If above condition is satisfied print “Print Job is empty”.
13.Otherwise increment front by 1.
14.If choice is 3
15.Print all the elements of job[] from ‘front to rear’.
16.If the choice is 4,print “ Exit ”.
17.Go to step 3 until choice is not 4.
18.Stop.
Question 13.

A class D2point defines the coordinate of appoint in the plane while another class
D3 point defines the coordinates of a point in space. The details of both the classes
are given below.

Class Name : D2point


Data members : double x,y [to store the x and y coordinates]

Functions
D2point() : Constructor to assign 0 to x,y
D2point(double : Constructor to assign 0 to x,y
nx,double,ny)
double : To return the distance between the point a and the
distance2d(D2point b) current point in the plane

Class name :D3point


Data members : double z[tc store the z coordinate]

Functions
D3point() : Constructor to assign 0 to z
D2point(double nz) : Constructor to assign nz to z
double distance3d(D2point b) : To return the distance between the point b and
the current point in a space
If x1,y1,z1,x2,y2,z2 be the coordinate of the 2 points,then the distance between the
points in a plane if given by the formula-((x2+x1)2 + (y2+y1)2)^(0.5)
and th distance between the point in the space is given by the formula-
((x2+x1)2 + (y2-y1)2 +(z2-z1)2)^(0.5)

Specify the class D2point giving the details of the two constructors and function
double distance2d(D2point b) using concept of inheritance specify the class
D3point giving the details of the two constructors and function double distance3d
(d3point b).
Write the main() Function.
Answer 13.

import java.io.*;
class D2point
{
protected double x,y;
D2point()
{
x = 0.0;
y = 0.0;
}

D2point(double nx,double ny)


{
x = nx;
y = ny;
}
double distance2d(D2point b)
{
double d = ((x-b.x)*(x-b.x)) + ((y-b.y)*(y-b.y)); //calculating square of distance
between 2d points
d = Math.sqrt(d); // calculating distance between two 2d points.
return d;
}
public void main(String args[])throws IOException
{
BufferedReader ob = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter x and y positions for first 2d point");
double x1 = Double.parseDouble(ob.readLine());
double y1 = Double.parseDouble(ob.readLine());
D2point d21 = new D2point(x1,y1);
System.out.println("Enter x and y positions for second 2d point");
double x2 = Double.parseDouble(ob.readLine());
double y2 = Double.parseDouble(ob.readLine());
D2point d22 = new D2point(x2,y2);
System.out.print("Distance between the entered two dimensional points is ");
System.out.println(d22.distance2d(d21));
System.out.println("Enter x,y and z positions for a 3d point in space");
double x3 = Double.parseDouble(ob.readLine());
double y3 = Double.parseDouble(ob.readLine());
double z3 = Double.parseDouble(ob.readLine());
D3point d3 = new D3point(x3,y3,z3);
System.out.println("Enter x,y and z positions for a 3d point in space");
double x32 = Double.parseDouble(ob.readLine());
double y32 = Double.parseDouble(ob.readLine());
double z32 = Double.parseDouble(ob.readLine());
D3point d32 = new D3point(x32,y32,z32);
System.out.println("Distance between entered three dimensional points is ");
System.out.print(d3.distance3d(d32));
}
}
class D3point extends D2point
{
protected double z;
D3point()
{ super(
); z =
0.0;
}
D3point(double x1,double y1,double nz)
{ super(x1,y1
); z = nz;
}
double distance3d(D3point b)
{
double d = ((b.x-x)*(b.x-x)) + ((b.y-y)*(b.y-y)) + ((b.z-z)*(b.z-z));
//calculating square of distance between 3d
points
d = Math.sqrt(d); //calculating distance between 3d points
return d;
}
}
OUTPUT 13.

Enter x and y positions for first 2d point


2
3
Enter x and y positions for second 2d point
4
5
Distance between the entered two dimensional points is 2.8284271247461903
Enter x,y and z positions for a 3d point in space
1
2
3
Enter x,y and z positions for a 3d point in space
4
5
6
Distance between entered three dimensional points is
5.196152422706632

Algorithm 13.

1. Start.
2. Input x,y co-ordinates of a point in “x1” , “y1”.
3. Input x,y co-ordinates of another point in “x2” , “y2”.
4. Calculate and display distance between above inputted points using formula √ {(x1-
x2)^2 + (y1-y2)^2}
5. Input x,y,z co-ordinates of a point in “x1”, “y1” , “z1”.
6. Input x,y,z co-ordinates of another point in “x2” , “y2” , “z2”.
7. Calculate and print distance between above inputted points by using formula √
{(x2)^2 + (y1-y2)^2+(z1-z2)^2}.
8. Stop.
Question 14.

A set is a collection in which there is no duplication of elements.


A multiset is a collection in which elements can be duplicate. For example
S = {1,2,3,4} is a set with integer elements
While
mS = {1,2,3,1,3} is a multiset with integer elements
following are some member functions of class multiset (which defines multiset with
integer elements)

Class name – Set


Data members /instance variables
int arr[] : integers array of size n
int n : (size)
Members
functions/methods
Set( ) : Constructor to assign 0 to n.
Set(int nn) : Constructor to assign n=nn
Void readlist() : To input integers
int isset() : Which is 1(one) if the multiset object is a set and
0(zero) other wise
Set intersection(Set s1 : Returns intersection elements of s1,s2.
,Set s2)
Void displaylist() : To display the intersection elements if both are sets.
Else display “multiset”.
Aslo write main().
Answer 14.

import java.io.*;
class Set
{
int arr[]; //declaring array
int n;

Set()
{
n = 0;
}
Set(int nn)
{
n = nn;
arr = new int[n]; //defining array of size n
}

public static void main(String args[])throws IOException


{
Set ob = new Set(); //making object of Set
ob.displaylist();
}

void readList()throws IOException


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter set");
for(int i=0; i<n; i++)
{ //inputting elements in array
arr[i] = Integer.parseInt(br.readLine());
}
}
int isset()
{
int flag=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(arr[i] == arr[j] && i != j) //condition for same elements in array i.e. it is not a set
{
flag = 1;
}
}
}
return flag;
}
Set intersection(Set s1,Set s2) //passing objects through constructor
{
int c = 0;
Set s3 = new Set(s1.n);
for(int i=0; i<s1.n; i++)
{
for(int j=0; j<s2.n; j++)
{
if(s1.arr[i] == s2.arr[j])
{
s3.arr[c] = s1.arr[i]; //taking intersection of the two sets
c++;
}
}
}
s3.n = c;
return s3; //returning object
}
void displaylist()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of elements in array 1");
int n1 = Integer.parseInt(br.readLine()); //storing size in a variale
System.out.println("Enter number of elements in array 2");
int n2 = Integer.parseInt(br.readLine());

Set ob1 = new Set(n1); //defining objects


Set ob2 = new Set(n2);
Set ob = new Set();
ob1.readList();
ob2.readList();
int o1 = ob1.isset();
int o2 = ob2.isset();
if(o1 == 0 && o2 == 0) // condition of both arrays being sets
{
ob = intersection(ob1,ob2);
System.out.println("Intersection of sets is");
for(int i=0; i<ob.n; i++)
{
System.out.println(ob.arr[i] + " "); //printing the intersection of sets
}
}
else
{
System.out.println("There is multiset");
} //message for case of any one or both arrays not beign a
set
}
}
OUTPUT 14.

Enter number of elements in array 1


4
Enter number of elements in array 2
4
Enter set
1
2
3
4
Enter set
1
3
4
5
Intersection of sets is
1
3
4

Algorithm 14.

1. Input two sets in arrays and get their lengths.


2. Initialize “flag” as 0.
3. Initialize “i” as 0.
4. Let j = i+1
5. If jth element of array is equal to ith element of array then display that it is not a set
and stop
6. Increment j by 1 and if j is less than length of array then goto step 5.
7. Increment i by 1 and if i is less than length of array then goto step 4.
8. Check if other array is a set or not by going to step 3 again.
9. Let “i”←0
10. Let “j”←0
11.If jth element of first array is equal to ith element of second array then display that
that element.
12.Increment j by 1 and if j is less than length of first array then go to step 11.
13.Increment i by 1 and if i is less than length of second array then go to step 10.
14.Stop.
Question 15.

Define a class Spiral to Generate a spiral matrix of max size N.(N>=3)


If N = 5 then spiral matrix
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

Data members:
int a[ ][ ] : 2-d array
int N : size

Member :
functions:
Void input ( ) : To input size and create 2-d array of size N
Void generate( ) : To generate spiral matrix of size N
Void print( ) : To print spiral matrix
Also write main().
Answer 15.

import java.io.*;
class Spiral
{
private int a[][];
private int N;
public void input()throws IOException
{
System.out.println("Enter size of array(n)");
BufferedReader at = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(at.readLine());
a = new int[N][N];
}
public void generate()
{
int i = -1, r = -1, u = -1, d=-1;
int m = 0;
int n = 0;
for(int j=1; j<N; j++)
{
a[m][n] = j;
n++;
}
a[m][n] = N;
for(int i=N+1; i<=(N*N); i++)
{
i =-1; r=-1; u=-1; d=-1;
if(n+1<N && n+1>=0 && a[m][n+1]==0)
{
r = 0;
}

if(m+1<N && m+1>=0 && a[m+1][n]==0)


{
d = 0;
}
if(m-1<N && m-1>=0 && a[m-1][n]==0)
{
u = 0;
}
if(n-1<N && n-1>=0 && a[m][n-1]==0)
{
i = 0;
}
if(r==0 && d==0 || (r==0 && i+d+u==-3))
{ n++; a[m]
[n] = i;
}
else if(d==0 && i==0 || (d==0 && i+r+u==-3))
{
m++;
a[m][n] = i;
}
else if(i==0 && u==0 || (i==0 && d+r+u==-3))
{
n--;
a[m][n]=i;
}
else if(u==0 && r==0 || (u==0 && i+r+d==-3))
{
m--;
a[m][n]=i;
}
}
}
public void print()
{
for(int j=0; j<N; j++)
{
for(int i=0; i<N; i++)
{
System.out.print(a[j][i]+" ");
}
System.out.println(" ");
}
}
public static void main(String args[])throws IOException
{
Spiral ob = new Spiral();
ob.input();
ob.generate();
ob.print();
}
}
OUTPUT 15.

Enter size of array(n)


5
12345
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

Algorithm 15.

1. Input size of array in N and declare a N x N matrix a[][].


2. Initialize “i”as -1, “r” as -1, “u”as -1, “d”as -1, “m”as 0, “ n”as 0 and “j”as 0
3. Let a[m][n]<j
4. Increment n and j by 1 each.
5. If j<N then go to step 4.
6. Let a[m][n] ←N
7. Let i←N+1.
8. Initialize “i”=-1, “r”= -1, “u”=-1, “d”=-1
9. If n+1<N and n+1 greater than or equal to 0 and a[m][n+1] is equal to 0 then let r←0
10.If m+1<N and m+1 greater than or equal to 0 and a[m+1][n] is equal to 0 then let
d=0
11.If m-1<N and m-1 greater than or equal to 0 and a[m-1][n] is equal to 0 then let u=0
12.If n-1<N and n-1 greater than or equal to 0 and a[m][n-1] is equal to 0 then let i=0
13.If r is equal to 0 and d is equal to 0 or r is equal to 0 and i+d+u is equal to -3 then
increment n by one and let a[m][n] ←i
14.If d is equal to 0 and l is equal to 0 or d is equal to 0 and i+r+u is equal to -3 then
increment m by one and let a[m][n] ←i
15.If l is equal to 0 and u is equal to 0 or l is equal to 0 and r+d+u is equal to -3 t then
decrement n by one and let a[m][n] ←i
16.If u is equal to 0 and r is equal to 0 or u is equal to 0 and l+r+d is equal to -3 then
decrement m by one and let a[m][n] ←i
17.Increment i by 1 and if i is less than or equal to N*N then go to step 8 else display
array.
18.Stop
Question 16.

A principal of a school needs to find the highest and lowest marks scored by the
student and also merit list on marks from highest to lowest in a class of 50
students. The classes student and meritlist are declared for above activities with
following details where student is base class and meritlist is derived class
Class name : student
Data members/instance
variables:
Tot[ ] : (floating) an array to store total marks of 50
students out of 500 each
stud[50] : string array to store name of 5 students of a
class

Member functions/methods:
void readdetails( ) : to input names and marks of 5 students. Marks
are given out of 500 each.
void printresult ( ) : to print students scoring highest and lowest marks in
the class along with names of students.
Class name : meritlist
Data members/instance None
variables
Member function /
methods:
Void generatemerit ( ) : to generate merit list of 5students on the basis of
total marks along with name of students.
void printmerit ( ) : to print merit list of 5 students in two columns in the
following

Format:
NAME MARKS SCORED
XXXX XXXXXX
XXXX XXXXXX
XXXX XXXXXX
Answer 16.

import java.io.*;
class student
{
float tot[] = new float[5];
String stud[] = new String[5];
void readdetails()throws IOException
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
for(int i=0; i<5; i++)
{
System.out.println("Enter name:");
stud[i] = b.readLine(); // Storing name of students in array
System.out.println("Enter marks:");
tot[i] = Float.parseFloat(b.readLine()); //Storing total marks of corresponding student
}
}
void printresult()
{
float h = tot[0];
String nh = stud[0];
float l = tot[0];
String nl = stud[0];
for(int i=1; i<5; i++)
{
if(tot[i]>h)
{ //If any array element is > than current highest
h = tot[i]; //marks, then updating the highest marks, and
nh = stud[i]; // and the corresponding students name.
}
if(tot[i] < l) //If any array element is > than current highest
{ //marks, then updating the highest marks, and
l = tot[i]; // and the corresponding students name
nl = stud[i];
}
}
System.out.println("Student scoring highest marks: "+nh);
System.out.println("Highest marks = "+h); //printing name and marks of student
System.out.println();
System.out.println("Student scoring lowest marks: "+nl);
System.out.println("Lowest marks = "+l); //printing name and marks of student
}
class meritlist extends student
{
void generatemerit()throws IOException
{ super.readdetails(
); for(int i=0;i<5;i++)
{ //Sorting array usiing bubble sort
for(int j=0;j<4-i;j++)
{
if(tot[j]<tot[j+1])
{
float t=tot[j];
tot[j]=tot[j+1];
tot[j+1]=t;
String s=stud[j];
stud[j]=stud[j+1];
stud[j+1]=s;
}
}
}
}
void printmerit()
{
System.out.println("NAME"+"\t"+"MARKS SCORED");
for(int i=0;i<5;i++)
{
System.out.println(stud[i]+"\t"+tot[i]); //printing meritlist
}
System.out.println();
super.printresult();
}
}
public void main()throws IOException
{
meritlist o = new meritlist();
o.generatemerit();
o.printmerit();
}
}
OUTPUT 16.

Enter name:
Nabeel
Enter marks:
500
Enter name:
Harsh
Enter marks:
444
Enter name:
Daksh
Enter marks:
400
Enter name:
Ritwik
Enter marks:
423
Enter name:
Peyush
Enter marks:
411
NAME MARKS SCORED
Nabeel 500.0
Harsh 444.0
Ritwik 423.0
Peyush 411.0
Daksh 400.0

Student scoring highest marks: Nabeel


Highest marks = 500.0

Student scoring lowest marks: Daksh


Lowest marks = 400.0
Algorithm 16 .

1. Start.
2. Enter names of five students. (stud[] - Input from user).
3. Enter marks of 5 students. ( tot[] - Input from user)
4. Define a floating variable “h” to store the highest marks with initial value as tot[0].
5. Define a floating variable “l” to store the lowest marks with initial value as tot[0].
6. Define a string variable “nh” to store name of student with highest marks, and
initialize it as stud[0].
7. Define a string variable “nl” to store name of student with lowest marks, and
initialize it as stud[0].
8. Compare h with each element in tot[]
9. If any of it is higher than h, interchange it with h and corresponding name with nh.
10.Go back to step 8 five times until h has the highest marks in tot[] and nh has the
corresponding name.
11.Compare l with each element in tot[]
12.If any of it is lower than l, interchange it with l and corresponding name with nl.
13.Go back to step 11 five times until l has the lowest marks in tot[] and nl has the
corresponding name.
14.Print the highest marks “h” and student’s name nh.
15.Print the lowest marks “l” and student’s name nl.
16.Define a variable i with initial value 0.
17.Compare i th element of tot with each element of tot[].
18.If i th element is lower than any of the tot[] elements, inter change them and also
interchange the i th element of stud[] with the corresponding element of stud.
19.Increment i by 1.
20.If i is less than 5 , go back toh step 17.
21.Otherwise define a variable j with initial value 0.
22.Print j th element of stud[] followed by space, followed by j th element of tot[].
23.Increment j by 1 .
24.If j is less than 5, then go back to step 22.
25.Stop.
Question 17.

Define a class recursion


Data String str
members
: int cv
int sp
int w

Functions:
recursion( ) Constructor
void accept( ) To input any string
void countvowels(int ) To count vowels in str & store in data member cv using
recursion
int spaces(String s,int To count and return number of spaces in string s using
p) recursion
void display( ) To print number of vowels and spaces and words in str

Also write main( ).


Answer 17.

import java.io.*;
class rockOn
{
public static void main()throws IOException
{
recursion ob = new recursion();
ob.input();
ob.display();
}
}
class recursion
{
private String str; //Defining class variables
private int cv, sp, w;
recursion()
{
str = " ";
cv = 0;
sp = 0;
}
void input()throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string ");
str = in.readLine(); //Storing string in str
}
void countvowels(int i)
{
String st = " ";
if(i > 0) //Stopping criteria
{
st = st + str.charAt(i-1);
char q = str.charAt(i-1); //Extracting character from (i-1) th position
if(q == 'a' || q == 'e' || q == 'i' || q == 'o' || q == 'u')
//Calulating number of vowels
{
cv++;
}
countvowels(i - 1); //Calling function by using recursion
}}
int spaces(String s,int p)
{
if(p > 0)
{
char t = s.charAt(p-1);
if(t == ' ')
{
sp++; //Calculating number of spaces and storing it in
sp
}
spaces(sp - 1); //Recursive call
}
return(sp);
}
void display()
{
int p = str.length();
countvowels(p);
spaces(str,p);
System.out.println("The number of vowels in " +str+ " is " +cv); //Printing number of
vowels
System.out.println("The number of spaces in "+str+" is "+sp); //Printing number of
spaces
}}

OUTPUT 17.

Enter the string


Rock on! Hai ye waqt ka ishara.
The number of vowels in Rock on! Hai ye waqt ka ishara. is 10
The number of spaces in Rock on! Hai ye waqt ka ishara. is 6

Algorithm 17.

1. Start
2. Define variables str,cv,sp and w
3. Initialize str as “”, cv as 0, sp as 0, w as 0
4. Input from user the String in variable str
5. Calculate the length of the string entered
6. Use recursion to extract each character of the string and store it in ch
7. If ch is a space, goto step 8
8. Increment sp by 1.
9. Use recursion to extract each character of the string and store it in ch
10.If ch is a vowel then goto step 11
11.Increment cv by 1
12.Display number of vowels
13.Display number of spaces
14.Stop
import java.io.*;
class employ //the base class starts here
{
private String empname;
private String pfno;
void inputdata(String a, String b)
{
empname = a;
pfno = b;
}
public void outputdata()
{
System.out.println("--------");
System.out.println("Name of the Employee : " +empname);
System.out.println("PF Number : " +pfno);
}
}

//The first derived class starts here


class derivedemp extends employ
{
float salary, grosspay, da, hra, pf, netpay;
derived emp(float value)
{
salary = value;
}

void calculateda()
{
da = (0.5f)*(salary);
System.out.println("Daily Allowance : " +da);
}

void calculatehra()
{
hra = (0.1f)*(salary);
System.out.println("H R Allowance : " +hra);
}

void calculategross()
{
grosspay = salary + hra da;
System.out.println("Gross Salary of the Employee : " +grosspay);
}

void pfdeduction()
{
pf = (0.12f)*(salary);
System.out.println("Provident Fund Deduction : " +pf);
}
void calculatenetpay()
{
netpay = grosspay - pf;
System.out.println("Net Pay of the Employee : " +netpay);
}
}

class derivedsecond extends employ //The Second derived class starts here
{
private float bankbalance;
derivedsecond(float value)
{
bankbalance = value;
}

void calculatebalance()
{
System.out.println("Bank balance of the Employee : " +bankbalance);
}
}
Question 18.

Write a program to input limit and print rhombus till n.


*
**
* *
**
*
Answer18.

import java.io.*;
class Rhombus
{

public static void main(String arg[])throws IOException


{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
if(n%2==0)
{
System.out.println("NO.SHOULD BE ODD ");
System.exit(0);
}
int s=(n+1)/2,b=-1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=s;j++)
System.out.print(" ");
if(i==1 || i==n)
System.out.print("*");
else
{
System.out.print("*");
for(int k=1;k<=b;k++)
System.out.print(" ");
System.out.print("*");
}
if(i<=n/2)
{
s=s-1;
b=b+2;
}
else
{
s=s+1;
b=b-2;
}
System.out.println(" ");
}
}
}

OUTPUT 18.

ENTER NO 12
NO.SHOULD BE ODD
ENTER NO 17
*
**
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
**
*

ALGORITHM 18.

i. Input the limit.


ii. Execute a loop from 1-n for printing lines.
iii. Execute another loop from 1-n and print blank space.
iv. If i=1 or n, then print *.
v. Else execute a loop and print blank and *.
vi. If it is in first half of rhombus then decrease value of s by 1 and increase value of b
by 2 and vice verse for second half.
vii. Change the line.
Question 19.

Write a program to input a string and two nos. and replace each character of that
two words by the character which is next in the alphabetical order in circular
fashion.

Answer 19.

import java.util.*;
import java.io.*;
class Change
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int a,b;
String str;
System.out.print("ENTER STRING ");
str=br.readLine();
System.out.print("ENTER PLACES OF WORDS TO BE CHANGED
");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
StringTokenizer st=new StringTokenizer(str," ");
int c=st.countTokens();
String w[]=new String[c];
for(int i=0;i<c;i++)
w[i]=st.nextToken();
for(int i=0;i<c;i++)
{
String wor="";
if(i==a-1 || i==b-1)
{
for(int j=0;j<w[i].length();j++)
{
char ch=w[i].charAt(j);
if(ch=='z' || ch=='Z')
wor=wor+(char)(((int)ch)-25);
else wor=wor+(char)(((int)ch)
+1);
}
w[i]=wor;
}
}
for(int i=0;i<c;i++)
System.out.println(w[i]);
}
}
OUTPUT 19.

ENTER STRING Time and tide waits for none


ENTER PLACES OF WORDS TO BE CHANGED 3
3
Time
and
ujef
waits
for
none

ALGORITHM 19.

i. Input a string and two nos.


ii. Count the no. of words and create an array of its size.
iii. Store each word in the array.
iv. Execute a loop till no. of words.
v. If loop becomes equal to nos. then extract each character of that word, and shift if
one place.
vi. If the character is ‘z’, then reaplace it with ‘a’ .
vii. Store the new word in the array.
viii. Print.
Question 20.

Write a program to input a no. less than 100 and covert it into roman no.

Answer 20.

import java.io.*;
class Roman
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
String r="";
String a[]={"","I","II","III","IV","V","VI","VII","VIII","IX","X"};
if(n<=50)
{
if(n<=39)
{
for(int i=0;i<n/10;i++)
r=r+"X";
r=r+a[n%10];
}
else
r=r+a[50-n]+"L";
}
else if(n>50 && n<=100)
{
if(n<=89)
{
int b=n-50;
r=r+"L";
for(int i=0;i<b/10;i++)
r=r+"X";
r=r+a[b%10];
}
else
r=r+a[100-n]+"C";
}
System.out.print("ROMAN NO. = "+r);
}
}
OUTPUT 20.

ENTER NO 12
ROMAN NO. = XII

ENTER NO 100
ROMAN NO. = C

ENTER NO 49
ROMAN NO. = IL

ENTER NO 1
ROMAN NO. = I

ENTER NO 99
ROMAN NO. = IC

ALGORITHM 20.

i. Input a no.
ii. Create an array and store 1-10 in roman form.
iii. Check that no. is less than 50 or not.
iv. If no. is less than 50 and 39, then execute a for loop and print X andthen remainder
from array.
v. If no. is less than 50 and more than 39, then print remainder from array and then L.
vi. If no. is more than 50 and less than 89, then print L and execute a for loop and print
X and then remainder from array.
vii. If no. is more than 50 and 89, then print 100-n from array and then C.
Question 21.

Write a program to input a no. and print the pattern till n.


ABCDEDCBA
ABCD DCBA
ABC CBA
AB BA
A A
AB BA
ABC CBA
ABCD DCBA
ABCDEDCBA

Answer 21.

import java.io.*;
class Pattern
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
if(n%2==0)
{
System.out.print("NO SHOULD BE ODD ");
System.exit(0);
}
int m=65+n/2,b=-1,j;
for(int i=1;i<=n;i++)
{ for(j=65;j<=m;j++)
System.out.print((char)j);
if(i==1 || i==n)
j=j-2;
else
j=j-1;
for(int k=1;k<=b;k++)
System.out.print(" ");
for(int l=j;l>=65;l--)
System.out.print((char)l);
if(i<=n/2)
{ b=b+2;
m=m-1;
}
else
{ b=b-2;
m=m+1;
}
System.out.println();
}}}
OUTPUT 21.

ENTER NO 12
NO SHOULD BE ODD
ENTER NO 19
ABCDEFGHIJIHGFEDCBA
ABCDEFGHI IHGFEDCBA
ABCDEFGH HGFEDCBA
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
AB BA
ABC CBA
ABCD DCBA
ABCDE EDCBA
ABCDEF FEDCBA
ABCDEFG GFEDCBA
ABCDEFGH HGFEDCBA
ABCDEFGHI IHGFEDCBA
ABCDEFGHIJIHGFEDCBA

ALGORITHM 21.

i. Input the limit.


ii. Execute a loop from 1-n for printing lines.
iii. Execute another loop from 65-65+n/2 and print character.
iv. If i=1 or n, then decrease value of j by 2 else by 1.
v. Execute a loop and print blank spaces.
vi. Now print again characters.
vii. If it’s upper half or lower half of loop, then increase value and decrease value of
counter for blank spaces respectively.
viii. Change the line.
Question 22.

Write a program to input two matrices and multiply them.

Answer 22.

import java.io.*;
class MultiOfMatrices
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
int r1,r2,c1,c2;
System.out.print("ENTER ROW & COLUMN OF FIRST MATRIX");
r1=Integer.parseInt(br.readLine());
c1=Integer.parseInt(br.readLine());
System.out.print("ENTER ROW & COLUMN OF SECOND
MATRIX");
r2=Integer.parseInt(br.readLine());
c2=Integer.parseInt(br.readLine());
if(c1!=r2)
{
System.out.print("MATRX CANNOT BE MULTIPLIED");
System.exit(0);
}
int a[][]=new int[r1][c1];
int b[][]=new int[r2][c2];
int c[][]=new int[r1][c2];
System.out.println("\n MATRIX 1");
for(int i=0;i<r1;i++)
{ for(int j=0;j<c1;j++)
{
System.out.print((i+1)+"."+(j+1)+" ENTER NO");
a[i][j]=Integer.parseInt(br.readLine());
}}
System.out.println("\n MATRIX 2");
for(int i=0;i<r2;i++)
{ for(int j=0;j<c2;j++)
{
System.out.print((i+1)+"."+(j+1)+" ENTER NO ");
b[i][j]=Integer.parseInt(br.readLine());
}}
System.out.println("\n MATRIX 1");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println("\n MATRIX 2");
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
System.out.print(b[i][j]+" ");
System.out.println();
}
System.out.println("\n MATRIX AFTER MULTIPLICATION");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
c[i][j]=0;
for(int k=0;k<c1;k++) c[i][j]=c[i]
[j]+(a[i][k]*b[k][j]);
System.out.print(c[i][j]+" ");
}
System.out.println();
}}}

OUTPUT 22.

ENTER ROW & COLUMN OF FIRST MATRIX 3


3
ENTER ROW & COLUMN OF SECOND MATRIX 3
4
MATRIX 1
1.1 ENTER NO 0
1.2 ENTER NO 1
1.3 ENTER NO 6
2.1 ENTER NO 4
2.2 ENTER NO 0
2.3 ENTER NO 1
3.1 ENTER NO 7
3.2 ENTER NO 5
3.3 ENTER NO 0

MATRIX 2
1.1 ENTER NO 0
1.2 ENTER NO 0
1.3 ENTER NO 9
1.4 ENTER NO 0
2.1 ENTER NO 2
2.2 ENTER NO 8
2.3 ENTER NO 2
2.4 ENTER NO 3
3.1 ENTER NO 5
3.2 ENTER NO 0
3.3 ENTER NO 4
3.4 ENTER NO 3

MATRIX 1
0 1 6
4 0 1
7 5 0
MATRIX 2
0 0 9 0
2 8 2 3
5 0 4 3
MATRIX AFTER MULTIPLICATION
32 8 26 21
5 0 40 3
10 40 73 15

ALGORITHM 22.

i. Input sizes of matrices.


ii. Check that column of first should be equal to row of second.
iii. If condition is false then exit from program.
iv. Input values in both matrices.
v. Create another matrix of size [r1][c2].
vi. Execute a loop from 0-r1.
vii. Execute another loop from 0-c2.
viii. Initialize element of matrix as 0.
ix. Execute a loop and multiply rows of matrix 1 with columns.
x. Print the matrix.
Question 23 .

Write a program to input a no. and print the consecutive nos. who adds to give that
number.

Answer 23.

import java.io.*;
class SumOfNos
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
for(int i=1;i<=n/2;i++)
{ int sum=0;
for(int j=i;j<=n/2+1;j++)
{ sum=sum+j;
if(sum==n)
{ for(int k=i;k<=j;k++)
System.out.print(k+" ");
System.out.println();
break;
}
else if(sum>n)
break;
}}}}
OUTPUT 23 .

ENTER NO 15
1 2 3 4 5
4 5 6
7
ENTER NO 75
3 4 5 6 7 8 9 10 11 12
10 11 12 13 14 15
13 14 15 16 17
24 25 26
37 38

ALGORITHM 23.

Enter the no.


i. Execute a loop from 1-n/2.
ii. Execute another loop from i-n/2.
iii. Add value of j and check with no.
iv. If sum is equal to no. then print nos. from i-j.
If sum has become greater than no. then exit from loop.
Question 24.

Write a program to input a string and display the word which has highest no. of
vowels. If two words has equal no. of vowels, then display largest word. if length is
also same, then which ever is alphabetically superior.

Answer 24.

import java.io.*;
class Word
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
String str,w="",w1="";
int v=0,p=0,c=0;
System.out.print("ENTER STRING ");
str=br.readLine();
for(int i=0;i<str.length();i++)
{
if((str.charAt(i)!=' ') && ((i==str.length()-1)||
(str.charAt(i+1)==' ')))
{
w1=str.substring(p,i+1);
if(i==1)
w=w1;
else
{
c=0;
for(int j=0;j<w1.length();j++)
{
char ch=w1.charAt(j);
if(ch=='A' || ch=='E' ||
ch=='I' || ch=='O' || ch=='U' ||ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' )
c++;
}
if(c>v)
{
v=c;
w=w1;
}
else if(c==v)
{
int a=w.length();
int b=w1.length();
if(b>a)
w=w1;
else if(a==b)
{

if(w.compareTo(w1)>0)
w=w1;
}
}
}
}
else if((str.charAt(i)!=' ')&&((i==0)||(str.charAt(i-1)==' ')))
p=i;
} System.out.println("\
n"+w);
}
}

OUTPUT 24.

ENTER STRING
Java is purely object oriented programming language
language
ENTER STRING India is my country
India
ENTER STRING fortune favours the brave
favours

ALGORITHM 24.

i. Input a string.
ii. Execute a loop from 0-length of string.
iii. Extract a word.
iv. Count no. of vowels.
v. Compare no. of vowels of words and store word which has highest no. of vowels.
vi. If two words have equal vowels, then compare their length.
vii. If length is also equal, then compare alphabetically.
viii. Print the word.
Question 25.

Write a program to input nos in double dimention array and check that it ts symetric
or not. A symetric matrix is one which is equal to its transpose.

Answer 25.

import java.io.*;
class Transpose
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int m,n;
System.out.print("ENTER ROWS ");
m=Integer.parseInt(br.readLine());
System.out.print("ENTER COLUMNS ");
n=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
if(m==n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print((i+1)+"."+(j+1)+"ENTER NO
");
a[i][j]=Integer.parseInt(br.readLine());
}
}
}
else
{
System.out.println("NOT SYMETRIC ");
System.exit(0);
}
int f=1;
loop1:
for(int i=0;i<m;i++)
{
loop2:
for(int j=0;j<m;j++)
{
if(a[i][j]!=a[j][i])
{
f=0;
break loop1;
}
}
}
System.out.println();
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println(); if(f==1)
System.out.println("SYMETRIC ");
else
System.out.println("NOT SYMETRIC ");
}
}

OUTPUT 25.

ENTER ROWS 4
ENTER COLUMNS 4
1.1 ENTER NO 18
1.2 ENTER NO 47
1.3 ENTER NO 13
1.4 ENTER NO 31
2.1 ENTER NO 47
2.2 ENTER NO 22
2.3 ENTER NO 42
2.4 ENTER NO 67
3.1 ENTER NO 13
3.2 ENTER NO 42
3.3 ENTER NO 98
3.4 ENTER NO 15
4.1 ENTER NO 31
4.2 ENTER NO 67
4.3 ENTER NO 15
4.4 ENTER NO 96
18 47 13 31
47 22 42 67
13 42 98 15
31 67 15 96
SYMETRIC

ALGORITHM 25.

i. Input rows and columns.


ii. Check that rows and column are equal.
iii. Create an array of size rows and columns.
iv. Input nos. in array.
v. Check that a[r][c]=a[c][r].
vi. If condition is true then it is a symmetric matrix.
vii. Print the matrix.
Q1.)Write a program to input a number and print 1 to n square in the form of
spiral.

import java.io.*;
class Spiral
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
if(n>12)
{
System.out.print("NO. SHOULD BE LESS THAN
12 ");
System.exit(0);
}
int arr[][]=new int[n][n];
int m=(int)Math.pow(n,2.0);
int c=n,r=n-1,b=n-1;
while(m>=1)
{
for(int i=0;i<b+1;i++)
arr[r][--c]=m--;
for(int i=0;i<b;i++)
arr[--r][c]=m--;
for(int i=0;i<b;i++)
arr[r][++c]=m--;for(int i=0;i<b-1;i++)
arr[++r][c]=m--;
b=b-2;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(arr[i][j]+" ");
System.out.println(" ");
}
}
}

OUTPUT :
ENTER NO 6
26 25 24 23 22 21
27 10 9 8 7 20
28 11 2 1 6 19
29 12 3 4 5 18
30 13 14 15 16 17
31 32 33 34 35 36

ALGORITHM:

ix. Input a no. and check that it is less than 12.


x. Create an array of [n][n].
xi. Store square of n in m.
xii. Execute a while loop till m>=1.
xiii. Execute a for loop for printing bottom row.
xiv. Execute a for loop for printing left column.
xv. Execute a for loop for printing above row.
xvi. Execute a for loop for printing right column.

Q2.)Write a program to input two date of births and find difference


between them.
import java.io.*;
class DateDifference
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int d1,d2,d,m1,m2,m,y1,y2,y;
int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
System.out.println("ENTER DATE OF BIRTH OF FIRST
PERSON ");
System.out.print("ENTER DATE ");
d1=Integer.parseInt(br.readLine());
System.out.print("ENTER MONTH ");
m1=Integer.parseInt(br.readLine());
System.out.print("ENTER YEAR ");
y1=Integer.parseInt(br.readLine());
System.out.println("\nENTER DATE OF BIRTH OF
SECOND
PERSON ");
System.out.print("ENTER DATE ");
d2=Integer.parseInt(br.readLine());
System.out.print("ENTER MONTH ");
m2=Integer.parseInt(br.readLine());
System.out.print("ENTER YEAR ");
y2=Integer.parseInt(br.readLine());
if(y1%100==0)
{
if(y1%400==0)
a[2]=29;
}
else
{
if(y1%4==0)
a[2]=29;
}
if(d1>=d2)
d=d1-d2;
else
{
d=d1+a[m1]-d2;
m1--;
}
if(m1>=m2)
m=m1-m2;
else
{
m=m1+12-m2;
y1--;
}
if(y1>=y2)
y=y1-y2;
else
y=y2-y1;
System.out.println("\nDIFFERENCE IN DATE OF BIRTH
");
System.out.println("DAYS= "+d);
System.out.println("MONTHS= "+m);
System.out.println("YEARS= "+y);
}
}

OUTPUT:

ENTER DATE OF BIRTH OF FIRST PERSON


ENTER DATE 1
ENTER MONTH 1
ENTER YEAR 2009
DIFFERENCE IN DATE OF BIRTH
DAYS= 1
MONTHS= 0
YEARS= 0
ALGORITHM:

9. Input two date of births.


10. Store days of month in an array.
11. If year is leap year then store days of feburary 29.
12. If date1 is greater than date2, then subtract d1-d2.
13. If date2 is greater than date1, then add days of month1 and subtract
d1-d2.
14. If month1 is greater than month2, then subtract m1-m2.
15. If month2 is greater than month1, then add 12 and subtract m1-m2.
16.If year1 is greater than year2, then subtract y1-y2 and vice versa.

Q3.)Write a program to input a security codein string format using


following format.
16. string length should not exceed 6 characters.
17. all letters should be in uppercase.
18. there should be no repetition of letters.
19. only alternate uppercase letter is allowed.

import java.io.*;
class SecurityCode
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int f=1;
String code;
System.out.print("ENTER SECURITY CODE ");
code=br.readLine();
int l=code.length();
if(l>6)
f=0;
for(int i=0;i<l;i++)
{
char ch=code.charAt(i);
if(Character.isLowerCase(ch))
{
f=0;
break;
}
}
for(int i=65;i<=90;i++)
{
int c=0;
for(int j=0;j<l;j++)
{
char ch=code.charAt(j);
if(ch==(char)i)
c++;
}
if(c>=2)
{
f=0;
break;
}
}
for(int j=0;j<l;j++)
{
char ch=code.charAt(j);
if(j!=l-1 )
{
char ch1=code.charAt(j+1);
if((int)ch1-(int)ch==1)
{
f=0;
break;
}
}
}
if(f==1)
System.out.println("VALID CODE");
else
System.out.println("INVALID CODE");
}
}

OUTPUT:

ENTER SECURITY CODE abcc


INVALID CODE
ENTER SECURITY CODE ABEGK
INVALID CODE

ALGORITHM:

21.Input a string.
22.Take a counter which changes its value if condition is false.
23.Check the length of string that it is less than 6.
24.Check that all letters are of uppercase.
25.Check that there is no repetition of letters.
26.Check that there is no consecutive letters
27.If condition is not satisfied then value of flag changes.
28.Check the value of flag and print the appropriate message.

Q4.)Write a program to input limit and find lucky nos. between them.
consider the series:
1 2 3 4 5 6 7 8 9 10 11 12…..
cancelling each second no.
1 3 5 7 9 11 13 15 17 15…...
cancelling each third no.
1 3 7 9 13 15 19 21…..
nos. remaining are lucky no.

import java.io.*;
class LuckyNo
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int n;
System.out.print("ENTER LIMIT ");
n=Integer.parseInt(br.readLine());
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=i+1;
for(int j=0;j<n;j++)
System.out.print(a[j]+" ");

System.out.println(" ");
for(int i=0;i<n;i++)
{
int c=i+1;
if(c<n)
{
int d=c;
while(d<n)
{
a[d]=-1;
d=d+i+2;
}
for(int j=0;j<n;j++)
{
if(a[j]==-1)
{
for(int k=j;k<n-1;k++)
a[k]=a[k+1];
n--;
}
}
for(int j=0;j<n;j++)

{
if(a[j]!=-1)
System.out.print(a[j]+" ");

}
System.out.println(" ");

if(a[c]==-1)
System.exit(0);
}
}
}
}

OUTPUT:
ENTER LIMIT- 10
1 2 3 4 5 6 7 8 9 10
1 3 5 7 9
1 3 7 9
1 3 7

ALGORITHM:

xi. Input the limit.


xii. Store nos. in array from 1-n.
xiii. Take a variable c for storing the no. of times whose no. has to be
cancelled.
xiv. Execute a while loop and store -1 in the place of no. which has to be
cancelled.
xv. Shift nos. to left and decrease size of array by 1.
xvi. Print the array.
xvii. If c is greater than size of array then exit.

Q5.)Write a program to declare a sq matrix and find a saddle pt. a


saddle pt is element of array such that it is minimum for row and
maximum for the column to which it belongs.also sort the diagonal.

import java.io.*;
class Matrix
{
int m[][]=new int[50][50];
int n;
public Matrix()
{
n=0;
for(int i=0;i<50;i++)
{
for(int j=0;j<50;j++)
m[i][j]=0;
}
}
public void input()throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("ENTER SIZE ");
n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print((i+1)+"."+(j+1)+"
ENTER NO");
m[i][j]=Integer.parseInt(br.readLine());
}
}
}
public void saddle()
{
int f=0;
for(int i=0;i<n;i++)
{
int min=m[i][0];
int a=0;
for(int j=0;j<n;j++)
{
if(m[i][j]<min)
{
min=m[i][j];
a=j;
}
}
int max=m[i][a];
for(int j=0;j<n;j++)
{
if(m[j][a]>max)
max=m[j][a];
}
if(min==max)
{
System.out.println("\n SADDLE POINT
FOUND AT "+i+" "+a);
f=1;
break;
}
}
if(f==0)
System.out.println("NO SADDLE POINT ");
}
public void sort()
{
for(int i=1;i<n;i++)
{
int j=i-1,a=m[i][i];
while(j>=0 && a<m[j][j])
{
m[j+1][j+1]=m[j][j];
j--;
}
m[j+1][j+1]=a;
}
}
public void display()
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(m[i][j]+" ");
System.out.println();
}
}
public static void main(String arg[])throws IOException
{
Matrix obj=new Matrix();
obj.input();
obj.saddle();
System.out.println("\n BEFORE SORTING");
obj.display();
obj.sort();
System.out.println("\n AFTER SORTING");
obj.display();
}
}

OUTPUT:

ENTER SIZE 3
1.1 ENTER NO 4
1.2 ENTER NO 16
1.3 ENTER NO 12
2.1 ENTER NO 2
2.2 ENTER NO 8
2.3 ENTER NO 14
3.1 ENTER NO 1
3.2 ENTER NO 3
3.3 ENTER NO 6

SADDLE POINT FOUND AT 0 0

BEFORE SORTING
4 16 12
2 8 14
1 3 6

AFTER SORTING
4 16 12
2 6 14
1 3 8

ALGORITHM:

24. Input the size of array.


25. Store nos. in array .
26. Take a flag which shows presence of saddle pt
27. Find minimum no. in a row and store index no. of it.
28. Find maximum no. with that index no.
29. If max no. is equal to minimum no. then it is saddle pt.
30. After finding saddle pt change value of flag.
31. If value of flag is same then there is no saddle pt.
Q6.)Write a program to input a word and print all possible
anagram.

import java.io.*;
class Anagram
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.print("ENTER ANY WORD ");
str=br.readLine();
int c=0,l=str.length();
int a[]=new int[l];
for(int i=0;i<l;i++)
a[i]=0;
while(a[l-1]!=l)
{
int f=1;
outer:
for(int i=0;i<l;i++)
{
inner:
for(int j=i+1;j<l;j++)
{
if(a[i]==a[j])
{
f=0;
break outer;
}
}
}
if(f==1)
{
for(int k=0;k<l;k++)
System.out.print(str.charAt(a[k]));
System.out.println();
c++;
}
a[0]=a[0]+1;
for(int i=0;i<l-1;i++)
{
if(a[i]==l)
{
a[i]=0;
a[i+1]=a[i+1]+1;
}
}
}
System.out.println("TOTAL ANAGRAMS= "+c);
}
}

OUTPUT:

ENTER ANY WORD word


drow
rdow
dorw
odrw
rodw
ordw
drwo
rdwo
dwro
wdro
rwdo
wrdo
dowr
odwr
dwor
wdor
owdr
wodr
rowd
orwd
rwod
wrod
owrd
word
TOTAL ANAGRAMS= 24

ALGORITHM:

11. Input a word.


12. Create an array according to words size.
13. Execute a while loop till last index no. has value equal to length of
word.
14. Execute two for loops and check that no two values in array are same.
15. If values are same then change the value of flag and break.
16. If value of flag is not changed then, print the letters of word according
to the value stored in array.
17. Increase the value of array one by one.

Q7.)Write a program to input nos. in binary tree and


tranverse it by preorder, inorder, postorder.

import java.io.*;
class Note
{
int info;
Note right,left;
public Note()
{
right=null;
left=null;
} } import
java.io.*; class
BinaryTree
{
public void create(Note r,int v)
{
if(v>r.info)
{
if(r.right==null)
{
r.right=new Note();
r.right.info=v;
}
else
create(r.right,v);
}
else
{
if(r.left==null)
{
r.left=new Note();
r.left.info=v;
}
else
create(r.left,v);
}
}
public void inorder(Note r)
{
if(r!=null)
{
inorder(r.left);
System.out.print(r.info+" ");
inorder(r.right);
}
}
public void preorder(Note r)
{
if(r!=null)
{
System.out.print(r.info+" ");
preorder(r.left);
preorder(r.right);
}
}
public void postorder(Note r)
{
if(r!=null)
{
postorder(r.left);
postorder(r.right);
System.out.print(r.info+" ");
}
}
public void input(Note r,int v)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int ch;
do
{
System.out.print("ENTER VALUE ");
v=Integer.parseInt(br.readLine());
create(r,v);
System.out.print("WISH TO CONTINUE ");
ch=Integer.parseInt(br.readLine());
}
while(ch!=0);
}
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
BinaryTree o=new BinaryTree();
int val,ch;
Note root=new Note();
System.out.print("ENTER VALUE ");
val=Integer.parseInt(br.readLine());
root.info=val;
do
{
System.out.println();
System.out.println("1. CREATE");
System.out.println("2. INORDER");
System.out.println("3. PREORDER");
System.out.println("4. POSTORDER");
System.out.println("5. EXIT");
System.out.print("ENTER CHOICE ");
ch=Integer.parseInt(br.readLine());
System.out.println();
switch(ch)
{
case 1:o.input(root,val);
break;
case 2:o.inorder(root);
break;
case 3:o.preorder(root);
break;
case 4:o.postorder(root);
break;
}
}
while(ch!=5);
}
}

OUTPUT:

ENTER VALUE 60
1. CREATE
2. INORDER
3. PREORDER
4. POSTORDER
5. EXIT
ENTER CHOICE 1

ENTER VALUE 40
WISH TO CONTINUE 1
ENTER VALUE 70
WISH TO CONTINUE 1
ENTER VALUE 20
WISH TO CONTINUE 1
ENTER VALUE 45
WISH TO CONTINUE 1
ENTER VALUE 10
WISH TO CONTINUE 1
ENTER VALUE 25
WISH TO CONTINUE 1
ENTER VALUE 41
WISH TO CONTINUE 1
ENTER VALUE 50
WISH TO CONTINUE 1
ENTER VALUE 75
WISH TO CONTINUE 1
ENTER VALUE 85
WISH TO CONTINUE 1
ENTER VALUE 80
WISH TO CONTINUE 0

1. CREATE
2. INORDER
3. PREORDER
4. POSTORDER
5. EXIT
ENTER CHOICE 2

10 20 25 40 41 45 50 60 70 75 80
1. CREATE
2. INORDER
3. PREORDER
4. POSTORDER
5. EXIT
ENTER CHOICE 3

60 40 20 10 25 45 41 50 70 75 85
1. CREATE
2. INORDER
3. PREORDER
4. POSTORDER
5. EXIT
ENTER CHOICE 4

10 25 20 41 50 45 40 80 85 75 70
1. CREATE
2. INORDER
3. PREORDER
4. POSTORDER
5. EXIT
ENTER CHOICE 5

ALGORITHM:
14. Create a menu driven program to create and print binary tree.
15. For creation store the first no. in first node and then compare other
nos. and store address of node according.
16. If no. is small then store address in left else in right.
17. If user gives preorder, then first print root, then left and then right.
18. If user gives inorder, then first print left, then root and then right.
19. If user gives postorder then first print left, then right and then left.

Q8.)Write a program to input a string along with special


characters and sort string without shifting special characters

import java.io.*;
class PunSort
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.print("ENTER STRING ");
str=br.readLine();
int l=str.length();
char a[]=new char[l];
for(int i=0;i<l;i++)
a[i]=str.charAt(i);
for(int i=0;i<l-1;i++)
{
int p=i;
for(int j=i;j<l;j++)
{
if(a[j]>=(char)65 && a[j]<=(char)90)
{
if(a[p]>a[j])
p=j;
}
}
char t=a[i];
a[i]=a[p];
a[p]=t;
}
for(int i=0;i<l;i++)
System.out.print(a[i]);
}
}

OUTPUT:
ENTER STRING C OM+P&U T E*&R E!@DU%CA TI&ON
A CC+D&E E I*&M N!@OO%PR TT&UU
ENTER STRING VYA($KH?YA" K@#ATI(&YAR
AAA($AH?IK" K@#RTV(&YYY

ALGORITHM:

10. Input a string.


11. Create an array of size of string.
12. Store characters of string in array.
13. Sort using selection sort technique.
14. While sorting check that if it is alphabet then only sort it.
15. Print the array.
Q9.)Write a program to input a no. with more than5 digits else re-enter
date. last 4 digits represent year and rest days and convert into date.year
should be between 1900-3000, else re-enter date.

import java.io.*;
class DaysDate
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int n,y;
do
{
System.out.print("ENTER DATE - ");
n=Integer.parseInt(br.readLine());
y=n%10000;
}
while(n<=9999 || (!(y>=1900 && y<=3000)));
int m[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if((y%100==0 && y%400==0)||(y%4==0))
m[2]=29;
n=n/10000;
int c=0,a=1,b=1,f=0;
String mon[]={" "," JAN "," FEB "," MARCH "," APRIL ","
MAY "," JUNE "," JULY "," AUG "," SEP "," OCT "," NOV "," DEC "};
int d=(int)Math.ceil(n/365);
y=d+y;
for(int k=0;k<d+1;k++)
{
for(int i=1;i<=12;i++)
{
for(int j=1;j<=m[i];j++)
{
c++;
if(c==n)
{
a=i;
b=j;
f=1;
break;
}
}
if(f==1)
break;
}
}
System.out.print(b+mon[a]+y);
}
}

OUTPUT:

ENTER DATE 120000


ENTER DATE 121800
ENTER DATE 000
ENTER DATE 1232008
2 MAY 2008
ENTER DATE 4001998
4 FEB 1999

ALGORITHM:
v. Execute a do while loop till user do not give correct integer.
vi. Integer should have mininum5 digits.
vii. Last 4 digits should be between 1900-3000.
viii. Create an array and store days of month in it.
ix. Create an array and store name of months in it.
x. Extract year and check that it is leap year or not.
xi. Execute a loop for month
xii. Execute another loop for days of month.
xiii. Increase the counter and check with days.
xiv. When counter matches then exit from loop and value of i is month and j
is date.
xv. Print date.

Q10.)Write a program to input a sentence and find occurance of each


word and print occurance of highest word.

import java.io.*;
class EachWord
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
String s,w="";
int c=0,a=0,max=0,p=0;
System.out.println("ENTER TEXT --> ");
s=br.readLine();
System.out.println();
int m=s.length();
for(int i=0;i<m;i++)
{
if(s.charAt(i)!=' ' && (i==m-1 || s.charAt(i+1)==' '))
c++;
}
String str[]=new String[c];
for(int i=0;i<m;i++)
{
if(s.charAt(i)!=' ' && (i==m-1 || s.charAt(i+1)==' '))
{
str[a]=s.substring(p,i+1);
a++;
}
if(s.charAt(i)!=' ' && (i==0|| s.charAt(i-1)==' '))
p=i;
}
for(int i=0;i<c;i++)
{
int d=0,f=0;
for(int j=0;j<c;j++)
{
if(str[i].equalsIgnoreCase(str[j]))
d++;
if(str[i].equalsIgnoreCase(str[j]) && i>j)
f++;
}
if(d>max)
{
max=d;
w=str[i];
}
if(f==0)
System.out.println(str[i]+" = "+d);
}
System.out.println("\nHIGHEST OCCURING WORD
"+w);
}
}

OUTPUT:

ENTER TEXT -->


Tanu is good girl she is nice girl she is mannered girl than any other girl
Tanu = 1
is = 3
good = 1
girl = 4
she = 2
nice = 1
mannered = 1
than = 1
any = 1
other = 1
HIGHEST OCCURING WORD girl

ALGORITHM:

28. Input a sentence.


29. Count no. of words.
30. Store each word in an array.
31. Compare a word with all other words, and if found same increase
the counter.
32. Check that it has already occurred or not, if not then print the
occurrence.
33. Check occurrence of each word with max value, if it exceeds max
value, then that word has max occurred.
34. Print the max occurring word.

Q11.)Write a program to input amount and output the no. of currency


notes.

import java.io.*;
class Money
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int amt;
System.out.print("ENTER AMOUNT ");
amt=Integer.parseInt(br.readLine());
int an=amt;
int a[]=new int[8];
int b[]={500,100,50,20,10,5,2,1};
for(int i=0;i<8;i++)
{
a[i]=an/b[i];
an=an-(b[i]*a[i]);
}
for(int i=0;i<8;i++)
{
if(a[i]!=0)
System.out.println(" NOTES OF "+b[i]+" = "+a[i]);
}}}
OUTPUT:
ENTER AMOUNT= 28768
NOTES OF 500 = 57
NOTES OF 100 = 2
NOTES OF 50 = 1
NOTES OF 10 = 1
NOTES OF 5 = 1
NOTES OF 2 = 1
NOTES OF 1 = 1

ALGORITHM:
Create an array b[] and stored all possible notes.
15. Create another a[] array to store no. of each notes.
16. Execute a loop till 8.
17. Divide money by notes and store in the array
18. Subtract the money calculated.
19. Print both the arrays.

Q12.)Write a program to input limit and print rhombus till n.


*
**
* *
**
*

import java.io.*;
class Rhombus
{

public static void main(String arg[])throws IOException


{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
if(n%2==0)
{
System.out.println("NO.SHOULD BE ODD ");
System.exit(0);
}
int s=(n+1)/2,b=-1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=s;j++)
System.out.print(" ");
if(i==1 || i==n)
System.out.print("*");
else
{
System.out.print("*");
for(int k=1;k<=b;k++)
System.out.print(" ");
System.out.print("*");
}
if(i<=n/2)
{
s=s-1;
b=b+2;
}
else
{
s=s+1;
b=b-2;
}
System.out.println(" ");
}
}
}

OUTPUT:

ENTER NO 12
NO.SHOULD BE ODD
ENTER NO 17
*
**
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
**
*

ALGORITHM:
15. Input the limit.
16. Execute a loop from 1-n for printing lines.
17. Execute another loop from 1-n and print blank space.
18. If i=1 or n, then print *.
19. Else execute a loop and print blank and *.
20. If it is in first half of rhombus then decrease value of s by 1 and
increase value of b by 2 and vice verse for second half.
21. Change the line.

Q13.)Write a program to input a string and two nos. and replace each
character of that two words by the character which is next in the
alphabetical order in circular fashion.

import java.util.*;
import java.io.*;
class Change
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int a,b;
String str;
System.out.print("ENTER STRING ");
str=br.readLine();
System.out.print("ENTER PLACES OF WORDS TO BE
CHANGED ");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
StringTokenizer st=new StringTokenizer(str," ");
int c=st.countTokens();
String w[]=new String[c];
for(int i=0;i<c;i++)
w[i]=st.nextToken();
for(int i=0;i<c;i++)
{
String wor="";
if(i==a-1 || i==b-1)
{
for(int j=0;j<w[i].length();j++)
{
char ch=w[i].charAt(j);
if(ch=='z' || ch=='Z')
wor=wor+(char)(((int)ch)-25);
else wor=wor+(char)(((int)ch)
+1);
}
w[i]=wor;
}
}
for(int i=0;i<c;i++)
System.out.println(w[i]);
}
}

OUTPUT:
ENTER STRING Time and tide waits for none
ENTER PLACES OF WORDS TO BE CHANGED 3
3
Time
and
ujef
waits
for
none

ALGORITHM:
12. Input a string and two nos.
13. Count the no. of words and create an array of its size.
14. Store each word in the array.
15. Execute a loop till no. of words.
16. If loop becomes equal to nos. then extract each character of that
word, and shift if one place.
17. If the character is ‘z’, then reaplace it with ‘a’ .
18. Store the new word in the array.
19.Print.
Q14.)Write a program to input a no. less than 100 and covert it into
roman no.

import java.io.*;
class Roman
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
String r="";
String a[]={"","I","II","III","IV","V","VI","VII","VIII","IX","X"};
if(n<=50)
{
if(n<=39)
{
for(int i=0;i<n/10;i++)
r=r+"X";
r=r+a[n%10];
}
else
r=r+a[50-n]+"L";
}
else if(n>50 && n<=100)
{
if(n<=89)
{
int b=n-50;
r=r+"L";
for(int i=0;i<b/10;i++)
r=r+"X";
r=r+a[b%10];
}
else
r=r+a[100-n]+"C";
}
System.out.print("ROMAN NO. = "+r);
}
}

OUTPUT:

ENTER NO 12
ROMAN NO. = XII

ENTER NO 100
ROMAN NO. = C

ENTER NO 49
ROMAN NO. = IL

ENTER NO 1
ROMAN NO. = I

ENTER NO 99
ROMAN NO. = IC

ALGORITHM:

viii. Input a no.


ix. Create an array and store 1-10 in roman form.
x. Check that no. is less than 50 or not.
xi. If no. is less than 50 and 39, then execute a for loop and print X
andthen remainder from array.
xii. If no. is less than 50 and more than 39, then print remainder from array
and then L.
xiii. If no. is more than 50 and less than 89, then print L and execute a for
loop and print X and then remainder from array.
xiv. If no. is more than 50 and 89, then print 100-n from array and then C.

Q15.)Write a program to input a no. and print the pattern till n.


ABCDEDCBA
ABCD DCBA
ABC CBA
AB BA
A A
AB BA
ABC CBA
ABCD DCBA
ABCDEDCBA

import java.io.*;
class Pattern
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
if(n%2==0)
{
System.out.print("NO SHOULD BE ODD ");
System.exit(0);
}
int m=65+n/2,b=-1,j;
for(int i=1;i<=n;i++)
{
for(j=65;j<=m;j++)
System.out.print((char)j);
if(i==1 || i==n)
j=j-2;
else
j=j-1;
for(int k=1;k<=b;k++)
System.out.print(" ");
for(int l=j;l>=65;l--)
System.out.print((char)l);
if(i<=n/2)
{
b=b+2;
m=m-1;
}
else
{
b=b-2;
m=m+1;
}
System.out.println();
}
}
}
OUTPUT:
ENTER NO 12
NO SHOULD BE ODD
ENTER NO 19
ABCDEFGHIJIHGFEDCBA
ABCDEFGHI IHGFEDCBA
ABCDEFGH HGFEDCBA
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
AB BA
ABC CBA
ABCD DCBA
ABCDE EDCBA
ABCDEF FEDCBA
ABCDEFG GFEDCBA
ABCDEFGH HGFEDCBA
ABCDEFGHI IHGFEDCBA
ABCDEFGHIJIHGFEDCBA

ALGORITHM:
ix. Input the limit.
x. Execute a loop from 1-n for printing lines.
xi. Execute another loop from 65-65+n/2 and print character.
xii. If i=1 or n, then decrease value of j by 2 else by 1.
xiii. Execute a loop and print blank spaces.
xiv. Now print again characters.
xv. If it’s upper half or lower half of loop, then increase value and decrease
value of counter for blank spaces respectively.
xvi. Change the line.
Q16.)Write a program to input two matrices and multiply them.

import java.io.*;
class MultiOfMatrices
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int r1,r2,c1,c2;
System.out.print("ENTER ROW & COLUMN OF FIRST
MATRIX");
r1=Integer.parseInt(br.readLine());
c1=Integer.parseInt(br.readLine());
System.out.print("ENTER ROW & COLUMN OF SECOND
MATRIX");
r2=Integer.parseInt(br.readLine());
c2=Integer.parseInt(br.readLine());
if(c1!=r2)
{
System.out.print("MATRX CANNOT BE MULTIPLIED");
System.exit(0);
}
int a[][]=new int[r1][c1];
int b[][]=new int[r2][c2];
int c[][]=new int[r1][c2];
System.out.println("\n MATRIX 1");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
System.out.print((i+1)+"."+(j+1)+" ENTER NO");
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\n MATRIX 2");
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
{
System.out.print((i+1)+"."+(j+1)+" ENTER NO ");
b[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\n MATRIX 1");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println("\n MATRIX 2");
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
System.out.print(b[i][j]+" ");
System.out.println();
}
System.out.println("\n MATRIX AFTER
MULTIPLICATION");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
c[i][j]=0;
for(int k=0;k<c1;k++) c[i][j]=c[i]
[j]+(a[i][k]*b[k][j]);
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}

OUTPUT:
ENTER ROW & COLUMN OF FIRST MATRIX 3
3
ENTER ROW & COLUMN OF SECOND MATRIX 3
4
MATRIX 1
1.1 ENTER NO 0
1.2 ENTER NO 1
1.3 ENTER NO 6
2.1 ENTER NO 4
2.2 ENTER NO 0
2.3 ENTER NO 1
3.1 ENTER NO 7
3.2 ENTER NO 5
3.3 ENTER NO 0

MATRIX 2
1.1 ENTER NO 0
1.2 ENTER NO 0
1.3 ENTER NO 9
1.4 ENTER NO 0
2.1 ENTER NO 2
2.2 ENTER NO 8
2.3 ENTER NO 2
2.4 ENTER NO 3
3.1 ENTER NO 5
3.2 ENTER NO 0
3.3 ENTER NO 4
3.4 ENTER NO 3

MATRIX 1
0 1 6
4 0 1
7 5 0
MATRIX 2
0 0 9 0
2 8 2 3
5 0 4 3
MATRIX AFTER MULTIPLICATION
32 8 26 21
5 0 40 3
10 40 73 15

ALGORITHM:

10. Input sizes of matrices.


11. Check that column of first should be equal to row of second.
12. If condition is false then exit from program.
13. Input values in both matrices.
14. Create another matrix of size [r1][c2].
15. Execute a loop from 0-r1.
16. Execute another loop from 0-c2.
17. Initialize element of matrix as 0.
18. Execute a loop and multiply rows of matrix 1 with columns.
19. Print the matrix.

Q17.)Write a program to input a no. and print the consecutive nos. who adds
to give that number.

import java.io.*;
class SumOfNos
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int n;
System.out.print("ENTER NO ");
n=Integer.parseInt(br.readLine());
for(int i=1;i<=n/2;i++)
{
int sum=0;
for(int j=i;j<=n/2+1;j++)
{
sum=sum+j;
if(sum==n)
{
for(int k=i;k<=j;k++)
System.out.print(k+" ");
System.out.println();
break;
}
else if(sum>n)
break;
}
}
}
}
OUTPUT
ENTER NO 15
1 2 3 4 5
4 5 6
7
ENTER NO 75
3 4 5 6 7 8 9 10 11 12
10 11 12 13 14 15
13 14 15 16 17
24 25 26
37 38
ALGORITHM:
Enter the no.
viii. Execute a loop from 1-n/2.
ix. Execute another loop from i-n/2.
x. Add value of j and check with no.
xi. If sum is equal to no. then print nos. from i-j.
If sum has become greater than no. then exit from loop.
Q18.)Write a program to input a string and display the word which has
highest no. of vowels. If two words has equal no. of vowels, then
display largest word. if length is also same, then which ever is
alphabetically superior.

import java.io.*;
class Word
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
String str,w="",w1="";
int v=0,p=0,c=0;
System.out.print("ENTER STRING ");
str=br.readLine();
for(int i=0;i<str.length();i++)
{
if((str.charAt(i)!=' ') && ((i==str.length()-1)||
(str.charAt(i+1)==' ')))
{
w1=str.substring(p,i+1);
if(i==1)
w=w1;
else
{
c=0;
for(int j=0;j<w1.length();j++)
{
char ch=w1.charAt(j);
if(ch=='A' || ch=='E' ||
ch=='I' || ch=='O' || ch=='U' ||ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' )
c++;
}
if(c>v)
{
v=c;
w=w1;
}
else if(c==v)
{
int a=w.length();
int b=w1.length();
if(b>a)
w=w1;
else if(a==b)
{
if(w.compareTo(w1)>0)
w=w1;
}
}
}
}
else if((str.charAt(i)!=' ')&&((i==0)||(str.charAt(i-1)==' ')))
p=i;
} System.out.println("\
n"+w);
}
}

OUTPUT:

ENTER STRING
Java is purely object oriented programming language
language
ENTER STRING India is my country
India
ENTER STRING fortune favours the brave
favours

ALGORITHM:

19. Input a string.


20. Execute a loop from 0-length of string.
21. Extract a word.
22. Count no. of vowels.
23. Compare no. of vowels of words and store word which has highest
no. of vowels.
24. If two words have equal vowels, then compare their length.
25. If length is also equal, then compare alphabetically.
26. Print the word.
Q19.)Write a program to input nos in double dimention array and check
that it ts symetric or not. A symetric matrix is one which is equal to its
transpose.

import java.io.*;
class Transpose
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
int m,n;
System.out.print("ENTER ROWS ");
m=Integer.parseInt(br.readLine());
System.out.print("ENTER COLUMNS ");
n=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
if(m==n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{ System.out.print((i+1)+"."+
(j+1)+"ENTER
NO ");
a[i][j]=Integer.parseInt(br.readLine());
}
}
}
else
{
System.out.println("NOT SYMETRIC ");
System.exit(0);
}
int f=1;
loop1:
for(int i=0;i<m;i++)
{
loop2:
for(int j=0;j<m;j++)
{
if(a[i][j]!=a[j][i])
{
f=0;
break loop1;
}
}
}
System.out.println();
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println(); if(f==1)
System.out.println("SYMETRIC ");
else
System.out.println("NOT SYMETRIC ");
}
}

OUTPUT:
ENTER ROWS 4
ENTER COLUMNS 4
1.1 ENTER NO 18
1.2 ENTER NO 47
1.3 ENTER NO 13
1.4 ENTER NO 31
2.1 ENTER NO 47
2.2 ENTER NO 22
2.3 ENTER NO 42
2.4 ENTER NO 67
3.1 ENTER NO 13
3.2 ENTER NO 42
3.3 ENTER NO 98
3.4 ENTER NO 15
4.1 ENTER NO 31
4.2 ENTER NO 67
4.3 ENTER NO 15
4.4 ENTER NO 96
18 47 13 31
47 22 42 67
13 42 98 15
31 67 15 96
SYMETRIC
ALGORITHM:
viii. Input rows and columns.
ix. Check that rows and column are equal.
x. Create an array of size rows and columns.
xi. Input nos. in array.
xii. Check that a[r][c]=a[c][r].
xiii. If condition is true then it is a symmetric matrix.
xiv. Print the matrix.
Q20.)Write a program to create file and read, write, search, edit and
delete record.

import java.util.*;
import java.io.*;
class FileHandling
{
static int count=0;
static FileWriter fw;
static BufferedWriter bw;
static PrintWriter pw;
static FileReader fr;
static BufferedReader br1=new BufferedReader(new
InputStreamReader(System.in));
static BufferedReader br2;
String empname;
int empno,basic;
public void addRecord()throws IOException
{
fw=new FileWriter("Employee.dat",true);
bw=new BufferedWriter(fw);
pw=new PrintWriter(bw);
int ch;
do
{
empno=count; System.out.println("CODE IS
"+empno); System.out.print("ENTER NAME -->
"); empname=br1.readLine();
System.out.print("ENTER BASIC --> ");
basic=Integer.parseInt(br1.readLine());
pw.println(empno+" "+empname+" "+basic);
count++;
System.out.print("ADD MORE (0/1) ");
ch=Integer.parseInt(br1.readLine());
}
while(ch!=0);
pw.close();
bw.close();
fw.close();
}
public static void generate()throws IOException
{
fr=new FileReader("Employee.dat");
br2=new BufferedReader(fr);
String rec,last=null;
while((rec=br2.readLine())!=null)
last=rec;
if(last==null)
count=100;
else
{
StringTokenizer st=new StringTokenizer(last);
count=Integer.parseInt(st.nextToken())+1;
}
br2.close();
fr.close();
}
public void read()throws IOException
{
fr=new FileReader("Employee.dat");
br2=new BufferedReader(fr);
while(readFromFile()!= -1);
br2.close();
fr.close();
}
public int readFromFile()throws IOException
{
String s=br2.readLine();
if(s==null)
return -1;
StringTokenizer st=new StringTokenizer(s);
empno=Integer.parseInt(st.nextToken());
empname=st.nextToken();
basic=Integer.parseInt(st.nextToken());
System.out.println(empno+" "+empname+" "+basic);
return 1;
}
public void searchRecord()throws IOException
{
fr=new FileReader("Employee.dat");
br2=new BufferedReader(fr);
String rec;
int key,f=0;
System.out.print("ENTER CODE TO BE SEARCHED ");
key=Integer.parseInt(br1.readLine());
while((rec=br2.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(rec," ");
empno=Integer.parseInt(st.nextToken());
empname=st.nextToken();
basic=Integer.parseInt(st.nextToken());
if(empno==key)
{
f=1;
break;
}
}
System.out.println("" );
if(f==1)
System.out.println(empno+" "+empname+" "+basic);
else
System.out.println("RECORD NOT FOUND");
br2.close();
fr.close();
}
public void edit()throws IOException
{
fr=new FileReader("Employee.dat");
br2=new BufferedReader(fr);
fw=new FileWriter("NewFile.dat",true);
bw=new BufferedWriter(fw);
pw=new PrintWriter(bw);
int key;
System.out.print("ENTER CODE TO BE EDITED ");
key=Integer.parseInt(br1.readLine());
String rec;
while((rec=br2.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(rec," ");
empno=Integer.parseInt(st.nextToken());
empname=st.nextToken();
basic=Integer.parseInt(st.nextToken());
if(empno==key)
{
System.out.print("ENTER NAME ");
empname=br1.readLine();
System.out.print("ENTER BASIC ");
basic=Integer.parseInt(br1.readLine());
}
pw.println(empno+" "+empname+" "+basic);
}
pw.close();
bw.close();
fw.close();
br2.close();
fr.close();
File f1=new File("Employee.dat");
File f2=new File("NewFile.dat");
f1.delete();
f2.renameTo(f1);
}
public void deleteRecord()throws IOException
{
fr=new FileReader("Employee.dat");
br2=new BufferedReader(fr);
fw=new FileWriter("NewFile.dat",true);
bw=new BufferedWriter(fw);
pw=new PrintWriter(bw);
int key;
System.out.print("ENTER CODE TO BE DELETED ");
key=Integer.parseInt(br1.readLine());
String rec;
while((rec=br2.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(rec," ");
empno=Integer.parseInt(st.nextToken());
empname=st.nextToken();
basic=Integer.parseInt(st.nextToken());
if(empno!=key)
pw.println(empno+" "+empname+" "+basic);
}
pw.close();
bw.close();
fw.close();
br2.close();
fr.close();
File f1=new File("Employee.dat");
File f2=new File("NewFile.dat");
f1.delete();
f2.renameTo(f1);
}
public static void main(String arg[])throws IOException
{
BufferedReader br3=new BufferedReader(new
InputStreamReader(System.in));
FileHandling obj=new FileHandling();
int ch;
do
{
System.out.println(" " );
System.out.println("1. READ" );
System.out.println("2. WRITE" );
System.out.println("3. SEARCH" );
System.out.println("4. EDIT" );
System.out.println("5. DELETE" );
System.out.println("6. EXIT" );
System.out.print("ENTER CHOICE ");
ch=Integer.parseInt(br3.readLine());
generate();
System.out.println("" );
switch(ch)
{
case 1:
obj.read();
break;
case 2:
obj.addRecord();
break; case 3:
obj.searchRecord();
break;
case 4:
obj.edit();
break;
case 5:
obj.deleteRecord();
break;
}
}
while(ch!=6);
}
}

OUTPUT:
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 2
CODE IS 100
ENTER NAME --> palak
ENTER BASIC --> 45000
ADD MORE (0/1) 1
CODE IS 101
ENTER NAME --> parul
ENTER BASIC --> 44000
ADD MORE (0/1) 1
CODE IS 102
ENTER NAME --> neha
ENTER BASIC --> 60000
ADD MORE (0/1) 1
CODE IS 103
ENTER NAME --> antika
ENTER BASIC --> 55000
ADD MORE (0/1) 0

1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 1
100 palak 45000
101 parul 44000
102 neha 60000
103 antika 55000
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 3
ENTER CODE TO BE SEARCHED 102
102 neha 60000
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 4
ENTER CODE TO BE EDITED 101
ENTER NAME parul
ENTER BASIC 50000
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 5
ENTER CODE TO BE DELETED 102
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 1
100 palak 45000
101 parul 50000
103 antika 55000
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 2
CODE IS 104
ENTER NAME --> sushantika
ENTER BASIC --> 66000
ADD MORE (0/1) 0
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
1. READ
2. WRITE
3. SEARCH
4. EDIT
5. DELETE
6. EXIT
ENTER CHOICE 6

ALGORITHM:
ix. Make a menu driven program for performing reading, writing, searching,
editing, deleting the records.
x. If user gives reading, then open file in reading mode and read records
till null point comes.
xi. If user gives writing, then open file in writing mode and input name and
salary.
xii. If user gives searching, then open file in reading mode and search for
the given empno.till null point comes, and print appropriate message.

Q21.)Write a program to input a string and a word.Now display each


word of the string in reverse order without changing its position and
also take care that if second inputted word exist in the string then it
should remain unreversed on its position.

import java.io.*;
class Strword
{
public static void main(String[] args)throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
int i,j,p;
String na=new String();
String s=new String();
String b=new String();
String a=new String();
a="";
System.out.println("ENTER A STRING ");
na=d.readLine();
na=na+" ";
s="";
System.out.println("ENTER A WORD ");
b=d.readLine();
for(i=0;i<na.length();i++)
{ if(na.charAt(i
)!=' ') a=a +
na.charAt(i);
else
{
if(a.compareToIgnoreCase(b)==0)
s=s+a;
else
{
for(j=i-1;j>=i-a.length();j--)
s=s + na.charAt(j);
}
s=s+" ";
a="";
}
}
System.out.println("THE OUTPUT IS :'" +s+"'");
}
}

OUTPUT:

ENTER A STRING
HELLO HOW ARE YOU
ENTER A WORD
ARE
THE OUTPUT IS :'OLLEH WOH ARE UOY '
ENTER A STRING
reverse the entire string
ENTER A WORD
remain
THE OUTPUT IS :' esrever eht eritne gnirts '

ALGORITHM:

Step1: In main( )function, initialize all required variables- int


i,j,p and string-na,a,b,s.
Step2: Store blank space in a.
Step3: Accept the string in na from user and add blank space to it.
Step4: Accept the string in b from user.
Step5: Run a loop from 0 to na’s length and excute the given steps in it.
Step6: Add characters of string till a blank space is found in a.
Step7: Check if a is equal to b.
Step8: If the condition is true, add it to s .
Step9: Otherwise add the reverse of string a in s and initialize a with blank
space.
Step10:Print the output string and end the process.

Q22.)Define a class with following specifications:


Class Name :Equation
Data Member :double a
:double b
:double c
Members Functions :
Equation() :default constructor
Equation(double a,double b,double c) :parametrised constructor
Point Solve(Equation e) :to find out values of
x and y

import java.io.*;
class Equation
{
double x,y;
private double a,b,c;
public Equation()
{
a=0;
b=0;
c=0;
}
public Equation(double na,double nb,double nc)
{
a=na;
b=nb;
c=nc;
}
public Equationt Solve(Equation e)
{
Equation p=new Equation ( );
p.x=(b*e.c-e.b*c)/(a*e.b-b*e.a);
p.y=(e.a*c-a*e.c)/(a*e.b-b*e.a);
return p;
}
public static void main(String args[])throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
int a1,a2,b1,b2,c1,c2;
System.out.println("Enter the values of a,b,c for Equation
1");
a1=Integer.parseInt(d.readLine());
b1=Integer.parseInt(d.readLine());
c1=Integer.parseInt(d.readLine());
System.out.println("Enter the values of a,b,c for Equation
2");
a2=Integer.parseInt(d.readLine());
b2=Integer.parseInt(d.readLine());
c2=Integer.parseInt(d.readLine());
Equation a=new Equation(a1,b1,c1);
Equation b=new Equation(a2,b2,c2);
Equation p=a.Solve(b);
System.out.println("x ="+p.x+" y ="+p.y);
}
}

OUTPUT:
Enter the values of a,b,c for Equation 1
1
1
1
Enter the values of a,b,c for Equation 2
1
2
3
x =1.0 y =-2.0

ALGORITHM:
Step1: In main( )function, initialize all required variables- int
a1,a2,b1,b2,c1,c2.
Step2: Accept the values of these variables from user.
Step3: Make two objects for two equations and pass these parameters in
each of them.
Step4: Make a new object and call Solve(Equation v) function.
Step5: In Solve(Equation e)function, make an object.
Step6: In a variable x store the calculated value.
Step7: In a variable y store the calculated value.
Step8: Return the object p which contains them.
Step9: Receive the object in main( ) and print the values of x and y.
Step10:End the process.

Q23.) Define a class with following specifications:


Class Name : Legender
Data member:
p : to store constant of p1
Member functions:
Legender(double np)
double nthterm(int n) : to return nth polynomial
double sum(int n) : to store sum upto nth polynomial

import java.io.*;
class Legender
{
double p;
public Legender (double np)
{
p=np;
}
public double nthterm(int n)
{
if(n==0)
return 0;
if(n==1)
return p;
else
return ((2.0*n-1)/(2.0*n)*nthterm(n-1))+(((double)n-1)/n*nthterm(n2));
}
public double sum(int n)
{
double s=0,k;
for(int i=0;i<=n;i++)
{
k=nthterm(i);
System.out.println("p"+i+" : "+k);
s+=k;
}
return s;
}

public static void main (String[]args) throws Exception


{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
double x;
int nx;
System.out.println("enter the no of terms");
nx=Integer.parseInt(d.readLine());
Legender l=new Legender(nx);
x=l.sum(nx);
System.out.println("the sum of legender polynomial series
upto
"+nx+" is : "+x);
}
}

OUTPUT:
enter the no of terms
3
p0 : 0.0
p1 : 2.0
p2 : 1.5
p3 : 2.583333333333333
the sum of legender polynomial series upto 3 is : 6.083333333333333

ALGORITHM:
Step1: In main( )function, initialize all required variables- double x
and int nx and accept the no. of terms from user(nx).
Step2: Make an object and pass no in it.
Step3: Call sum( )function and store the sum of series in a variable.
Step4: Print the sum of series.
Step5: In nthterm(int n))function, check and return the nth term of series.
Step6: In sum(int n) function, initialize all required variables- double s
and k.
Step7: Run a loop from 0 to n and execute the given steps.
Step8: Store the nth term in k.
Step9: Add the value of k in s and return the sum.
Step10:End the process.

Q24.)Define a class PerfectSq with following specifications:


Class Name :PerfectSq
Data Members:
long n :to store number
MEMBER FUNCTIONS:
PerfectSq(long mn)
int isPrime(long nx) :returns 1,if nx is prime,0 otherwise
int nextPrimeTo(long nx) :return next prime no. immediate after nx
long isPerfectSq() :returns perfect square root of n if possible,0
otherwise.
import java.io.*;
class Perfectsq
{
long n;
public Perfectsq(long mn)
{
n=mn;
}
public int isprime(long nx)
{
int i,c=0;
long z=nx;
for(i=2;i<nx && nx%i!=0;i++);
if(i==nx)
return 1;
else
return 0;
}
public long nextPrimeTo(long nx)
{
long i;
int m=0;
for(i=nx+1;m!=1;i++)
{
if(isprime(i)==1)
m++;
}
return (i-1);
}
public long isperfectsquare()
{
long s=1;
long num=n,x=2;
while(num>1)
{
while(num%x==0)
{
s*=x;
num/=x;;
if(num%x!=0)
return 0;

num/=x;
}
x=nextPrimeTo(x);
}
return s;
}
public static void main(String args[])throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
long no;
long c;
System.out.println("ENTER ANY NUMBER");
no=Integer.parseInt(d.readLine());
Perfectsq p=new Perfectsq(no);
c=p.isperfectsquare();
System.out.println("PERFECT SQUARE ROOT : "+c);
}
}

OUTPUT :
ENTER ANY NUMBER
25
PERFECT SQUARE ROOT : 5
ENTER ANY NUMBER
34
PERFECT SQUARE ROOT : 0

ALGORITHM:
Step1: In main( )function, initialize all required variables- (long) no and
c and accept the value of no from user.
Step2: Make an object and pass no in it.
Step3: Call isperfectsquare()function and store the result in c.
Step4: Print the perfect square of given value.
Step5: In isprime(long nx)function, check if the value is prime and
return 0 or 1 accordingly.
Step6: In isperfectsquare() function,use a while loop to check if the no.
is a perfect square or not.
Step7: Call nextPrimeTo(long nx) function that returns the next prime no..
Step8: Store the next prime no.in a variable.
Step9: Return the perfect square’s root.
Step10:End the process.
Q25.)Find the LCM AND HCF of two fractions (You may make your own
class and functions).

import java.io.*;
class Fraction
{
int num,den;
public Fraction(int n,int d)
{
num=n;
den=d;
}
public int lcm(int a,int b)
{
int n=a,m=b;
while(a!=b)
{
if(a<b)
a=a+n;
else
b=b+m;
}
return a;
}
public int hcf(int a,int b)
{
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}
public static void main(String args[])throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));

int n,den;
System.out.println("ENTER THE NUM AND DEN");
n=Integer.parseInt(d.readLine());
den=Integer.parseInt(d.readLine());
Fraction f=new Fraction(n,den);
int c=f.hcf(n,den);
System.out.println("HCF IS"+c);
System.out.println("ENTER THE NUMBERS TO FIND
LCM");
int z,e;
z=Integer.parseInt(d.readLine());
e=Integer.parseInt(d.readLine());
int g=f.lcm(z,e);
System.out.println("LCM IS"+g);
}
}

OUTPUT:
ENTER THE NUM AND DEN
2
3
HCF IS 1
ENTER THE NUMBERS TO FIND LCM
12
20
LCM IS 60

ALGORITHM:
Step1: Declare the required variable (int) num and den and initialize them
with values passed in constructor.
Step2: In function lcm(int a,int b) store these values in nand m.
Step3: Run a while loop that has a condition that a is not equal to b.
Step4: If a is less than b add n to .
Step5: If b is less than a add m to b.
Step6: When the loop terminates ,return a.
Step7: In hcf(int a,int b) function run a while loop that has a condition that a
is not equal to b.
Step8: If a is greater than b store (a-b) in a.
Step9: If b is greater than a store (b-a) in b.
Step10: When the loop terminates ,return a and end the process.

Q26.)Define a class with following specifications:


Class Name :Mean
Data Members:
n : size of array
data[ ] : integer type array
llimit : to store lowest limit
Hlimit : to store highest limit
Members Functions:
void readData( )
int getfrequency(int start,int end)
double getMean()
void showTable()

import java.io.*;
class mean
{
int n,data[];
int size,llimit,hlimit;
public void readData()throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
int i;
System.out.println("Enter Llimit & Hlimit & size");
llimit=Integer.parseInt(d.readLine());
hlimit=Integer.parseInt(d.readLine());
size=Integer.parseInt(d.readLine());
if((hlimit-llimit)%size==0)
{
System.out.println("enter size of array then no.");
n=Integer.parseInt(d.readLine());
data=new int[n]; for(i=0;i<n;i++)
data[i]=Integer.parseInt(d.readLine());
}
}
public int getfrequency(int start,int end)
{
int f=0,i;
for(i=0;i<n;i++)
if(data[i]>=start && data[i]<end)
f++;
return f;
}
public double getMean()
{
int i;
double sf=0,sfx=0,x,f;
for(i=llimit;i<hlimit;i+=size)
{
f=getfrequency(i,size+i);
x=(i+size+i)/2;
sfx+=f*x;
sf+=f;
}
return sfx/sf;
}
public void showTable()
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
System.out.println("Class Size Mid Value(m)
Frequency(f)fm");
double r;
int c=0,e=size,x,fsum=0,fmsum=0,f;
x=(hlimit+llimit)/size;
while(x!=0)
{
System.out.print(c+"-"+e+" ");
r=(c+e)/2.0;
System.out.print(r+" ");
f=getfrequency(c,e);
System.out.print(f+" "+(r*f));
fmsum+=f;
c=e;
e+=size;
x--;
System.out.println();
}
System.out.println();
System.out.print("Mean is "+getMean());
}
public static void main(String args[])throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
{
Mean m=new Mean();
m.readData();
m.showTable();
}
}

OUTPUT:
Enter Llimit & Hlimit & size
0
50
5
enter size of array then no.
10
1
2
3
4
5
6
7
8
9
10
Class Size Mid Value(m) Frequency(f) fm
0-5 2.5 4 10.0
5-10 7.5 5 37.5
10-15 12.5 1 12.5
15-20 17.5 0 0.0
20-25 22.5 0 0.0
25-30 27.5 0 0.0
30-35 32.5 0 0.0
35-40 37.5 0 0.0
40-45 42.5 0 0.0
45-50 47.5 0 0.0
Mean is 5.5

ALGORITHM:
Step1: Declare the required variable (int) n and array data[] and
size, llimit and hlimit.
Step2: In the main( )function,create an object.
Step3: Call functions readData( ) and showTable( ) from object.
Step4: In function readData( ) accept the values of size, llimit and hlimit.
Step5: Enter the size of array and then its values.
Step6: In function getfrequency(int start,int end) run a loop and return the
frequency.
Step7: In getMean() function run a loop from llimit to hlimit.
Step8: Call getFrequency( ) and return the mean after calculating it.
Step9: In showTable() function print the messages appropriately
before showing the table and mean.
Step10:Use a while loop and print the table and mean.
Step11:End the process.
Q27.)Cryptograph is a method of hiding actual meaning of any
message.There are different ways to perform.
Crytograph, one of them is explained below.
Cryptic No. : 7
Message : Life is a camera
Now replace each character by (7 + length of the word)th next character
(in cyclic order)

import java.io.*;
class Cryptic
{
public static void main(String[] args)throws Exception
{
BufferedReader d=new BufferedReader(new
InputStreamReader(System.in));
int i,j,n,c,p;
char a;
String na=new String();
String s=new String();
s="";
String k=new String();
k="";
System.out.println("ENTER ANY STRING");
na=d.readLine()+" ";
System.out.println("ENTER ANY NUMBER");
n=Integer.parseInt(d.readLine());
for(i=0;i<na.length();i++)
{
if(na.charAt(i)!=' ')
s=s+na.charAt(i);
else
{
for(j=0;j<s.length();j++)
{
c=(int)s.charAt(j);
p=c + n + s.length();
if((p>=65 && p<=90) || (p>=97
&p<=122))
a=(char)p;
else
{
p=p-26;
a=(char)p;
}
k=k+a;
}
System.out.print(k+" ");
k="";
s="";
}
}
}
}

OUTPUT:
ENTER ANY STRING
HELLO HOW are you
ENTER ANY NUMBER
4
QNUUX OVD hyl fvb

ALGORITHM:
Step1: Declare the required variable String na and initialize it with
string accepted from user in main( )function.
Step2: Initialise two more strings s and k with blank space.
Step3: Declare the required variable n(int) and initialize it with
value accepted from user.
Step4: Run a loop from 0 to (length of string na-1) and execute steps given
below.
Step5: Take out characters from the string and store them in string s if
they are not blankspaces.
Step6: Otherwise run a loop till the length of s.
Step7: Take out characters of the string and add n and s’length in their
ASCII code.
Step8: Store the characters obtained in another string.
Step9: After the operation is over print the new coded string.
Step10:End the process.
Q28.)Define a class Encode to encode string with following rules.
inplaceof="prtmnoqxyabcdhgfeikjuvwzsl"
above set of character represent the set of character in place of
"abc...xyz"
Class name : Encode
Data Member/instance variables
txt : to store text to be coded
Member functions/methods:
Encode(text) : constructor to initialize txt = text
char inplaceof(char ch) : to return output code

import java.io.*;
class Encode
{
String txt = new String();
public Encode(String text)
{
txt=text;
}
public char inplaceof(char ch)
{
String s ="prtmnoqxyabcdhgfeikjuvwzsl";
int pos = 0,i; char na=' ';
for(i=0;i<s.length()&&pos<1;i++)
{
if(s.charAt(i)==ch)
{
pos = (int)ch-97;
na = s.charAt(pos);
}
}
return na;
}
public void showcodedText()
{
String a = new String();
int i,j;
String p = new String();
p="";
for(i=0;i<txt.length();i++)
{
if(txt.charAt(i)!=' ')
p = p + txt.charAt(i);
else
{
for(j=0;j<p.length();j++)
a=a+inplaceof(p.charAt(j));
a+=" ";
p="";
}
}
System.out.print(a);
}
public static void main(String args[])throws Exception
{
BufferedReader d=new BufferedReader(new
InputStreamReader(System.in));
int i;
String na;
System.out.println("Enter the text");
na=d.readLine()+" ";
Encode e=new Encode(na);
e.showcodedText();
}
}

OUTPUT:
Enter the text
soumya
kgudsp
Enter the text
table not cable
jprcn hgj tprcn
ALGORITHM:
Step1: Declare the required variable String txt and initialize it with
parameter passed in constructor of class.
Step2: In the main( ) function, accept the text and then pass it
in the object.
Step3: Call the showcodedText()function to show the required code.
Step4: In the inplaceof(char ch) function store the given string of characters
of code.
Step5: In the same function, run a loop and return the position of
new character.
Step6: In the showcodedText() function initialize two strings.
Step7: In the same function, run a loop from 0 to (txt-1)and execute the
given steps.
Step8: Store the characters of a word in the string p.
Step9: When a blank space occurs, run aloop till the length of p and call
inplaceof(char ch) function and store the coded string in a.
Step10:Print the new string and end the process.
Q29.)Write a program to input a string then output the same by
increasing numbers present in the string by 50% ,
For example:
Input String : "I have bought 10 apples in Rs. 20."
Output String : "I have bought 15 apples in Rs. 30."

import java.io.*;
class Fifty
{
public static void main(String[] args)throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
String s=new String();
String z=new String();
String na=new String();
int i,j,k,c=0,n=0;
double num;
System.out.println("Enter any string");
na=d.readLine();
len=na.length();
if(na.charAt(na.length()-1)=='.')
len--;
for(i=0;i<len;i++)
z=z+na.charAt(i);
z=z+" ";
for(i=0;i<z.length();i++)
{
if(z.charAt(i)!=' ')
s=s+z.charAt(i);
else
{
for(j=0;j<s.length();j++)
if(s.charAt(j)>='0' && s.charAt(j)<='9')
c++;
if(c==s.length())
{
for(k=0;k<s.length();k++)
n=n*10+(s.charAt(k)-
48);
System.out.println(n);
num=n+(.5*n);
System.out.print(num+" ");
}
else
System.out.print(s+" ");
n=0;
s="";
c=0;
}
}
}
}

OUTPUT:
Enter any string
I bought 10 apples for Rs. 20.
I bought 15.0 apples for Rs. 30.0

ALGORITHM:
Step1: Declare the required variable String na and initialize it with
string accepted from user in main( )function.
Step2: Initialise two more strings s and k with blank space.
Step3: Store the length of na in len.
Step4: Store the characters of na in z and a blank space in end.
Step5: Take out characters from the string and store them in string s if
they are not blankspaces.
Step6: Otherwise run a loop till the length of s and count the no. of digits.
Step7: Take out characters of the string and increase the no. by 50%.
Step8: Store the value in num.
Step9: After the operation is over print the new string.
Step10:End the process.
Q30.)Convert an infix expression into postfix expression (You may
make your own class and functions).

import java.io.*;
class Postfix
{
public static int pre(char c)
{
String s[]={"(",")","+ -","* % /","^"};
int i;
for(i=0;s[i].indexOf(c)==-1;i++);
return i;
}
public static boolean operator(char c)
{
return("* - + % / () ^".indexOf(c)!=-1)?true:false;
}
public static void main(String[]args)throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in));
System.out.print("enter an infix exp");
String s = d.readLine();
String s1=new String ("");
String s2=new String ("");
char ch;
int i;
for(i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(operator(ch))
{
while(ch!='('&&s1.length()>0&&pre(s1.charAt(s1.length()-
1))>=pre(ch))
{
s2+=s1.charAt(s1.length()-1);
s1=s1.substring(0,s1.length()-
1);
}
if(ch==')')
s1=s1.substring(0,s1.length()-
1);
else
s2+=ch;
}
for(i=s1.length()-1;i>=0;i--)
s2+=s1.charAt(i);
System.out.print("Postfix Expression="+s2);
}
}
}

OUTPUT:
enter an infix exp
(a+b)/(d-i)
Postfix Expression=ab+di-/

ALGORITHM:
Step1: In pre(char c)function, declare an array of string s that contains all
operators.
Step2: In same function return the position of operator matched.
Step3: In operator(char c)function, return true or false according to
condition.
Step4: In the main( )function, accept an infix expression from user.
Step5: Declare two more null strings.
Step6: Run a loop from 0 to( s’length-1).
Step7: Call operator( )function to check if character extracted is an operator.
Step8: Then transpose the operators accordingly.
Step9: Print the expression.
Step10:End the process.

Q31.)Define a class number with following specification


Class name :Number
Data Members :
num :an integer to store number
Member functions :
number(int n) :constructor to initialize num by n
int frequencyOf(int i) :to return the frequency of i in the current
object
int sumOf(int n) :to return the sum of digits of n
int isMagical() :returns 1 if the current object is magical ,
0 otherwise
void showAll() :display the frequency of each digit in number
and also display the message
whether number is
magical or not.(frequency of each
digit must be
printed once only)
Specify the class number giving details of constructor
and functions int frequencyOf(int n), int isMagical() and void showAll().
You may assume other functions are designed for you.

import java.io.*;
class Number
{
int num;
public Number(int n)
{
num=n;
}
public int frequencyOf(int i)
{
int s=num,c=0,f;
while(s!=0)
{
f=s%10;
if(i==f)
c=c+1;
s=s/10;
}
return c;
}
public int sumOf(int n)
{
int p=n,d=0,a;
while(p!=0)
{
a=p%10;
d=d+a;
p=p/10;
}
return d;
}
public int isMagical()
{
int a=0,b=num;
while(b>9)
b=b%10 + b/10;
if(b==1)
return 1;
else
return 0;
}
public void showAll()
{
int b=num,nu,i=0,a,c,d;
nu=num; for(i=0;i<9;i+
+)
{
a=frequencyOf(i);
if(a>0)
System.out.println(" The frequency of "+ i + " is "
+ a);
}
d=isMagical();
if(d==1)
System.out.print("THIS IS MAGICAL");
else
System.out.print("THIS IS NOT MAGICAL");
}

public static void main(String []args)throws Exception


{
BufferedReader d=new BufferedReader(new
InputStreamReader(System.in));
int n;
System.out.println(" ENTER THE NUMBER ");
n=Integer.parseInt(d.readLine());
Number n1=new Number(n);
n1.showAll();
}}
OUTPUT:
ENTER THE NUMBER
6542366
The frequency of 2 is 1
The frequency of 3 is 1
The frequency of 4 is 1
The frequency of 5 is 1
The frequency of 6 is 3
THIS IS NOT MAGICAL

ALGORITHM:
Step1: Declare the required variable num(int) and initialize it with
parameter passed in constructor of class.
Step2: In the main( ) function, accept the number and then pass it
in the object.
Step3: Call the showAll( ) function to show the required information.
Step4: Call frequencyOf(int i)function initialize the required variables.
Step5: In the same function, run a loop and count the frequency of the
digit in ‘i’ and return it.
Step6: In the sumOf(int n) function add all the digits of num and return it.
Step7: In the isMagical( ) function, check if the no. is magical or not by
dividing by 10 and adding quotient and remainder.
Step8: If the no. is magical return 1 or 0.
Step9: In the showAll()function call the frequencyOf(int i)function by
running a loop from 0-9 and print each no.’ frequency.
Step10:Then, call function isMagical( int i) and check if returned value is 0
or 1.
Step11:Print the message accordingly and end the process.

Q32.)Write a program to input n integers in an array. Now arrange these


integer these integers in such a way so that all positive numbers should
appear in the left side of the array and negative numbers in the right
side.
Input : 2 -4 -6 8 9 -11 12
output: 2 8 9 12 -4 -6 -11

import java.io.*;
class Negpos
{
public static void main(String[] args)throws Exception
{
BufferedReader d=new BufferedReader(new
Input StreamReader(System.in)); int
arr[],i,j,temp,n;
System.out.println("Enter the length");
n=Integer.parseInt(d.readLine());
arr=new int[n];
System.out.println("Enter the numbers");
for(i=0;i<n;i++)
arr[i]=Integer.parseInt(d.readLine());
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]<arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n && arr[i]>=0 && arr[j]>=0;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("THE SERIES IS AS FOLLOWS");
for(i=0;i<n;i++)
System.out.print (arr[i]);
}
}

OUTPUT:
Enter the length
7
Enter the numbers
2
-4
-6
8
9
-11
12
THE SERIES IS AS FOLLOWS:2 8 9 12 -4 -6 -11

ALGORITHM:
Step1: In main( )function, initialize all required variables- (int)
array- arr[],i,j,temp and n.
Step2: Accept the length of array from user in n.
Step3: Initialise the array with size n.
Step4: Accept the values from user by running a loop.
Step5: Run a loop from (i=0) to (n-1) that executes given steps.
Step6: Run another loop from (i+1) to n.
Step7: Arange the array in ascending order by bubble sort method .
Step8: Then again run a loop and check for negative values.
Step9: Transpose the values accordingly and print them by running a loop.
Step10:End the process.

Q33.)Class ChaArray contains an array of n characters. You may


assume that array contains only letter of the English alphabet. Some of
member functions/methods ChaArray are given below:
Class name : ChaArray
Data member/instance variables:
char ch[] : an array of character
int size : the size of array of character
Member functions/methods:
ChaArray() : Constructor to
initialize instance variable
ChaArray(char c[]) : Constructor to assign character
array c to
instance variable
void displayArray() : to diplay the list of n character
void move() : to move all upper case
character the right
side of the array and the
lower case
character
to the left side of the array
Input:tDsfXvd
Output:tdfsvXD
Define a class with the above defined data members and member
functions.

import java.io.*;
class ChaArray
{
char ch[];
int size;
public ChaArray()
{
size=0;
ch=new char[0];
}
public ChaArray(char c[])
{
ch=new char[c.length];
for(int i=0;i<c.length;i++)
ch[i]=c[i];
}
public void displayArray()
{
for(int i=0;i<ch.length;i++)
System.out.print(ch[i]);
System.out.println();
}
public void move()
{
char temp;
int i,j,m=0,len,l=0;
len=ch.length;
for(i=ch.length-1;i>l;i--)
{
for(j=0;j<len && m!=1;j++)
{
if(ch[i]>=97 && ch[i]<=122 && ch[j]>=65 && ch[j]<=90)
{
temp=ch[i];
ch[i]=ch[j];
ch[j]=temp;
m=1;
len--;
}
}
m=0;
}
}
public static void main(String args[])throws Exception
{
BufferedReader d=new BufferedReader(new
InputStreamReader(System.in));
int i,n;
char c[];
System.out.println("Enter length and then string");
String s=new String();
n=Integer.parseInt(d.readLine());
c=new char[n];
s=d.readLine();
for(i=0;i<s.length();i++)
c[i]=s.charAt(i);
ChaArray p=new ChaArray(c);
p.move();
System.out.println("The output is ");
p.displayArray();
}
}

OUTPUT:
Enter length and then string
7
tDfsXvd
The output is
tdfsvXD
ALGORITHM:
Step1: Declare the required variable size(int) and array ch[] and
initialize them with parameters passed in constructor of class.
Step2: In the main( ) function, accept the length of array and then the string
of characters.
Step3: Store the characters of string in array ch[].
Step4: Call move( )function by object and then print the transposed string
by calling display( )function.
Step5: In the constructor initialize ch[] with the passed parameter.
Step6: In the move( )function initialize variables required.
Step7: In the same function, run a loop from (length of array-1) to more
than 1 and execute steps 8 and 9.
Step8: In the loop, take out characters of the array in another loop and check
if previous character is smallcase and next uppercase.
Step9: Also check if m=0 and transpose the characters.
Step10:Initialise m with 0 and end the process.

Q34.)Define a class Conversion with following specifications :


Class Name : Conversion
Data Member/Instance Variables:
num : a string to store number
base : an integer to store base
Member functions/Methods:
Conversion(String n,int b) : constructor to initialize num
by n and base by b
int isValid() : returns 1 if the number is
valid for the given base(where
base<=16),0 otherwise
int toDecimal() : to return decimal equivalent of the
number.
You have to check the validity of the number before its
conversion,function should return 0 for invalid number.

import java.io.*;
class conversion
{
String num=new String();
int base;
public static void main(String[] args)throws Exception
{
BufferedReader d=new BufferedReader(new
InputStreamReader(System.in));
{
int a,b,z;
String n;
System.out.println("INPUT THE BASE AND
THEN
THE VALUE ");
b=Integer.parseInt(d.readLine());
num=d.readLine();
Conversion c=new Conversion(n,b);
if(c.isValid( )==1)
System.out.println("THIS IS VALID");
else
System.out.println("THIS IS INVALID ");
z=c.ToDecimal();
System.out.println("THE NUMBER IN THE
ENTERED
BASE IS : "+z);

}
}

public Conversion (String s,int b)


{
num=s;
base=b;
}
public int isValid()
{
String s1="0123456789ABCDEF";
int i,c=0;
for(i=0;i<num.length();i++)
{
if(base<=s1.indexOf(num.charAt(i)))
c=0;
else
c=1;
}
return c;
}
public int ToDecimal()
{
String s="0123456789ABCDEF";
int i,p,n=0,l=num.length();
if(isValid()==1)
{
for(i=0;i<num.length();i++)
{
p=s.indexOf(num.charAt(i));
n+=p*(int)Math.pow(base,l-1-i);
}
}
return n;
}
}

OUTPUT:
INPUT THE BASE AND THEN THE VALUE
2
1101
THIS IS VALID
THE NUMBER IN THE ENTERED BASE IS : 13
INPUT THE BASE AND THEN THE VALUE
8
909
THIS IS INVALID
THE NUMBER IN THE ENTERED BASE IS : 0

ALGORITHM:
Step1: Declare the required variable num(String) and base(int) and initialize
them with parameters passed in constructor of class.
Step2: In the main( ) function, accept a string and base from user and pass
them in the object of class.
Step3: In the if...condition call isValid( )function.
Step4: If the condition is true, print that it is valid or otherwise. Step5: In
a variable z store the returned decimal value and print it. Step6: In the
constructor initialize the variables with passed parameters.
Step7: In the function isValid(), run a loop from 0 to (length of string-1) to
execute steps 8 and 9.
Step8: In the loop, take out characters of the string and check that if they
match with any of the base stored in string s1.
Step9: Return the value stored in c.
Step10:In ToDecimal( )function convert the string value in decimal using
for(..)loop.
Step11:Return the decimal value and then end the process.

Q35.)Write a program to input a number and arrange its digits in


ascending order leaving first, last and zero(0) digits unchanged.
For example,
input: 320512
output:310252

import java.io.*;
class Arrange
{
public static void main(String[] args)throws Exception
{
BufferedReader d=new BufferedReader(new
InputStreamReader(System.in));
String num=new String( );
int i,j,len,k,temp;
int a[];
System.out.println("Enter the no.");
num=d.readLine();
len=num.length();
a=new int[len];
for(i=0;i<len;i++)
{
a[i]=num.charAt(i)-48;
}
for(j=1;j<len-2;j++)
{
for(k=j+1;k<len-1;k++)
{
if(a[j]>a[k] &&a[j]!=0 &&a[k]!=0)
{
temp=a[j];
a[j]=a[k];
a[k]=temp;
}
}
}
System.out.println("The number in desired form is");
for(i=0;i<a.length;i++)
System.out.print(a[i]);
System.out.println( );
}
}

OUTPUT:
Enter the no.
320512
The number in desired form is
310252

ALGORITHM:
Step1: Declare the required variable num(String),I,j,len,temp and array a[]
in the main( ) function.
Step2: Accept the the number from user and initialize num with it.
Step3: Initialize len with the string num’s length.
Step4: Initialise the array with len size.
Step5: Then, run a loop from 0 to (len-1) and store each number of the
string in them.
Step6: Run a loop from (j=1)to (len-2) and execute steps 7,8 and 9 in it.
Step7: Run a loop from (j+1) to (len-1) and execute the given steps.
Step8: Using if condition, check if last digit is greater than the present
and neither of them is 0.
Step9: If the condition is true exchange the values.
Step10:End the process.

Q36.)Define a static function int maxpos (int arr[ ],int endIndex) to find
and return index of the maximum number from beginning till the
endIndex.Define another static function void SelectionSort(int arr[ ])to
arrange the array arr[ ] in ascending order using function maxpos( ).

import java.io.*;
class Exsel
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); int
arr[],n,t,i; System.out.println("Enter
the limit");
n=Integer.parseInt(d.readLine());
arr=new int[n];
System.out.println("Enter the elements :");
for(i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
selectionSort(arr);
System.out.println("Series in sorted order is");
for(i=0;i<n;i++)
System.out.println(arr[i]);
}
public static int maxpos(int arr[],int endIndex)
{
int i,m=arr[0],pos=0;
for(i=1;i<endIndex;i++)
{
if(m<arr[i])
{
m=arr[i];
pos=i;
}
}
return pos;

}
public static void selectionSort(int arr[])
{
int i,pos,temp;
for(i=arr.length-1;i>0;i--)
{
pos=Maxpos(arr,i);
temp=arr[pos];
arr[pos]=arr[i-1];
arr[i-1]=temp;
}
}
}

OUTPUT:
Enter the limit
6
Enter the elements :
12
11
67
23
44
19
Series in sorted order is
11
12
19
23
44
67

ALGORITHM:
Step1: Declare the required variable n,t,I and array arr[] in the main( )
function.
Step2: Accept the limit of array from user and initialize the array with it.
Step3: Accept the values to be stored in array from user by running a loop.
Step4: Call the function selectionSort(int arr ) and pass the array in it
Step5: Then, run a loop from 0 to (n-1) in order to print the sorted list.
Step6: In the maxpos(int arr[],int endIndex) function , calculate the position
of maximum value using if condition.
Step7: Return the index no. of maximum value in the same function.
Step8: In the selectionSort(int arr[]) function run a loop from (array’s length
-1) till 0 and execute the step9.
Step9: Call the maxpos(int arr[],int endIndex) function and then transpose
value at index pos to (i-1).
Step10:End the process.

Q37.)class name: Stringfun


Member variables:
String s;
Member functions:
public Stringfun(String ss)
public String reverse(int x)
public void checkpalin( )
public void count( )
Make a program and use these functions to reverse a string by
recursive technique to check for palindrome and show the no. of vowels
and consonants in it .

import java.io.*;
class Stringfun
{
String s;
public Stringfun(String ss)
{
s=ss;
}
public String reverse(int x)
{
String str="";
if(x==(s.length()-1))
return s.charAt(x);
else
str=str+reverse(x+1);
return str;
}
public void checkpalin( )throws IOException
{
String str=reverse(0);
if(s==str)
System.out.println("STRING IS PALINDROME");
else
System.out.println("STRING IS NOT PALINDROME");
}
public void count( )throws IOException
{
int vv=0,cc=0;
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
switch(ch)
{
case 'a':
case 'A':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':vv=vv+1;
break;
default :cc=cc+1;
}
System.out.println("NUMBER OF CONSONANTS IN THE WORD="+cc);
System.out.println("NUMBER OF VOWELS IN THE WORD="+vv);
}
public static void main(String arg[])throws IOException
{
BufferedReader br=new
BufferedReader(newInputStreamReader(System.in));
System.out.println("ENTER A STRING");
String h=br.readLine();
Stringfun obj=new Stringfun(h);
obj.count();
obj.checkpalin();
}
}

OUTPUT:
ENTER A STRING-
FOREMOST

NUMBER OF CONSONANTS IN THE WORD=5


NUMBER OF VOWELS IN THE WORD=3

ALGORITHM:
Step1: Declare the required variable s and initialize it with parameter
passed in constructor of class.
Step2: In the recursive function-reverse(int x), initialize a new string the
reversed string.
Step3: Reverse the string s using recursive technique and then return it.
Step4: In the checkpalin( ) function, receive the reversed string in ‘str’.
Step5: In the same function check if both strings are equal and print the
appropriate message.
Step6: In the count( ) function,initialize variables vv and cc to store the no.
of vowels and consonants in it.
Step7: In the same function, run a loop from 0 to (length of string-1) to
execute steps 8 and 9.
Step8: In the loop, take out characters of the string and check them through
switch( ) case.
Step9: If the character matches with vowels increase vv by 1 or otherwise,
cc by 1.
Step10:In the main( ) function, accept a string from user and pass it in the
object of class.
Step11:Call functions through object and then end the process.
Q38.)class name: Que
Member variables:
int q[ ],n,front,rear;
Member functions:
public Que (int x)
public void push( )
public void pop( )
public void display()
Make a program and use these functions to maintain a queue.

import java.io.*;
class Que
{
int front,rear;
int q[],n;
public Que(int x)
{
n=x;
q=new int[n];
front=-1;
rear=-1;
for(int i=0;i<n;i++)
q[i]=0;
}
public void push( )throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(rear==n-1)
System.out.println("Queue overflow");
else
{
System.out.println("Enter a value"); q[+
+rear]=Integer.parseInt(br.readLine());
if(rear==0)
front=0;
}
}
public void pop( )throws IOException
{ if(front==rear)
System.out.println("Queue underflow");
else
front++;
}
public void display()
{
for(int i=front;i<=rear;i++)
System.out.println(q[i]);
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter queue size:”);
int x=Integer.parseInt(br.readLine());
int ch;
Que ob=new Que(x);
do
{ System.out.println("1.Push\n2.Pop\n3.Display\
n4.Exit"); System.out.println("Enter choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:ob.push();
break;
case 2:ob.pop();
break;
case 3:ob.display();
break;
case 4:return;
}
}while(ch!=4);
}
}

OUTPUT:
Enter queue size:10
1.Push
2.Pop
3.Display
4.Exit
Enter choice
1
Enter a value
257
1.Push
2.Pop
3.Display
4.Exit
Enter choice
1
Enter a value
49
1.Push
2.Pop
3.Display
4.Exit
Enter choice
1
Enter a value
888
1.Push
2.Pop
3.Display
4.Exit
Enter choice
3
257
49
888
1.Push
2.Pop
3.Display
4.Exit
Enter choice
4

ALGORITHM:
Step1: Declare the required variables n,front,rear and array q[].
Step2: Initialize n with parameter passed in constructor of class and
front and rear with -1 and initialize array with size ‘n’.
Step3: In the push( )function check if queue is full and print ‘Overflow’.
Step4: If the queue is not full,accept a value from user and store it in the
array at index no.’rear+1’.
Step5: In the pop( )function check if queue is empty and print ‘Underflow’.
Step6: If the queue is not empty, increase front by 1.
Step7: In the dispay( ) function, run a loop from front to rear to print the
values stored in queue.
Step8: In the main( ) function, initialize variables ch and x to store choice of
user and size of stack.
Step9: Make an object of the class and pass the size in it.
Step10:Accept the size of queue from the user and print the choices inside
do…while loop.
Step11:According to user’s choice, call the required function and end the
process when user enters 4 as choice.
Q39.)class name: Stack
Member variables:
int arr[ ],n,top;
Member functions:
public Stack(int x)
public void push( )
public void pop( )
public void display()
Make a program and use these functions to maintain a stack.

import java.io.*;
class Stack
{
int arr[];
int n,top;
public Stack(int x)
{ n=x;
top=-1;
arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=0;
}
public void push( )throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(top==n-1)
System.out.println("Overflow");
else
{
System.out.println("Enter a value");
arr[++top]=Integer.parseInt(br.readLine());
}
}
public void pop()throws IOException
{
if(top==-1)
System.out.println("Underflow");
else
top--;
}
public void display()throws IOException
{
for(int i=0;i<=top;i++)
System.out.println(arr[i]);
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int ch,s;
System.out.print("Enter size:");
s=Integer.parseInt(br.readLine());
Stack ob =new Stack(s);
do
{
System.out.println("1.Push\n2.Pop\n3.Display\n4.Exit\n Enter choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:ob.push();
break;
case 2:ob.pop();
break;
case 3:ob.display();
break;
case 4:return;
}
}while(ch!=4);
}
}

OUTPUT:
Enter size:10
1.Push
2.Pop
3.Display
4.Exit
Enter choice
1
Enter a value
34
1.Push
2.Pop
3.Display
4.Exit
Enter choice
1
Enter a value
456
1.Push
2.Pop
3.Display
4.Exit
Enter choice
1
Enter a value
89
1.Push
2.Pop
3.Display
4.Exit
Enter choice
2
1.Push
2.Pop
3.Display
4.Exit
Enter choice
3
34
456
1.Push
2.Pop
3.Display
4.Exit
Enter choice
4
ALGORITHM:
Step1: Declare the required variables x,y and array arr[ ].
Step2: Initialize n with parameter passed in constructor of class and
top with -1 and initialize the array with size ‘n’.
Step3: In the push( )function check if stack is full and print ‘Overflow’.
Step4: If the stack is not full,accept a value from user and store it in the
array at index no.’top+1’.
Step5: In the pop( )function check if stack is empty and print ‘Underflow’.
Step6: If the stack is not empty, reduce top by 1.
Step7: In the dispay( ) function, run a loop from 0 to top to print the values
stored in stack.
Step8: In the main( ) function, initialize variables ch and s to store choice of
user and size of stack.
Step9: Make an object of the class and pass the size in it.
Step10:Accept the size of stack from the user and print the choices inside
do…while loop.
Step11:According to user’s choice, call the required function and end the
process when user enters 4 as choice.
Q40.)class name: D2point
Member variables:
double x,y;
Member functions:
public D2point( )
public D2point(dounle xx,double yy)
public double distance2d(D2point b)
class name: D3point
Member variables:
double z;
Member functions:
public D3point( )
public D3point(dounle xx,double yy,double zz)
public double distance3d(D2point b)
Make a program and use these classes and functions to calculate
distance between two points in space and plane using the concept of
inheritance.

import java.io.*;
class D2point
{
double x,y;
public D2point()
{
x=0.0;
y=0.0;
}
public D2point(dounle xx,double yy)
{
x=xx;
y=yy;
}
public double distance2d(D2point b)
{
double d=Math.sqrt(Math.pow((x-b.x),2.0)+Math.pow((y-b.y).2.0));
return d;
}
}

class D3point extends D2point


{
double z;
public D3point()
{
super();
z=0.0;
}
public D3point(double n1,double n2,double zz)
{
super(n1,n2);
z=zz;
}
public double distance3d(D3point b)
{
double d=Math.sqrt(Math.pow((x-b.x),2.0)+Math.pow((y-
b.y).2.0)+Math.pow((z-b.z).2.0));
return d;
}
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter x, y and z coordinates of first point");
int x1=Integer.parseInt(br.readLine());
int y1=Integer.parseInt(br.readLine());
int z1=Integer.parseInt(br.readLine());
System.out.println("Enter x, y and z coordinates of second point");
int x2=Integer.parseInt(br.readLine());
int y2=Integer.parseInt(br.readLine());
int z2=Integer.parseInt(br.readLine());
D3point obj1=new D3point(x1,y1,z1);
D3point obj2=new D3point(x2,y2,z2);
double d1=obj1.distance2d(obj2);
double d2=obj1.distance3d(obj2);
System.out.println("DISTANCE BETWEEN THE POINTS IN
PLANE="+d1);
System.out.println("DISTANCE BETWEEN THE POINTS IN
SPACE="+d2);
}
}
OUTPUT:
Enter x, y and z coordinates of first point
2
3
1
Enter x, y and z coordinates of second point
3
4
2
DISTANCE BETWEEN THE POINTS IN PLANE=1.414
DISTANCE BETWEEN THE POINTS IN SPACE=1.732

ALGORITHM:
Step1: Declare the required variables x and y to store the coordinates of
point in class ‘D2point’.
Step2: Initialize the variables with parameters passed in constructor of class.
Step3: In the distance2d(D2point b) function calculate the value of distance
between the points in plane and return this value.
Step4: Declare the required variable z to store the third coordinate in class
‘D3point’ that extends ‘D2point’ class.
Step5: Call the superclass’ constructor,passing values in it and initialize
required variable z with parameter passed in constructor of class.
Step6: In the distance3d(D3point b) function calculate the value of distance
between the points in space and return this value.
Step7: Create the main( ) function.
Step8: In the main( ) function, accept the values of coordinates of two
points from the user.
Step9: Declare two objects of the class and pass the coordinates in them.
Step10:Now store the output by calling the functions in two variables.
Step11:Print the distance between two points in plane and space and end the
process.
Q41.) class name: Account
Member variables:
protected int accno;
protected double pri;
Member functions:
public Account(int a,double p)
public void display( )
class name: Simple
Member variables:
protected double rate,time,si;
Member functions:
public void display( )
class name: Compound
Member variables:
protected double rate,time,si;
Member functions:
public void display( )
Make a class ‘Bank’ and use these classes and functions to calculate
simple interest or compound interest using the concept of inheritance.

import java.io.*;
class Account
{
protected int accno;
protected double pri;
public Account(int a,double p)
{
accno=a;
pri=p;
}
public void display()throws IOException
{
System.out.println("ACCOUNT NO.="+accno);
System.out.println("PRINCIPLE=Rs."+pri);
}
}
class Simple extends Account
{
protected double rate,time,si;
public Simple(int a1,double p1,double r,double t)
{
super(a1,p1);
rate=r;
time=t;
si=0.0;
}
public void display()throws IOException
{
si=(pri*rate*time)/100.0; super.display();
System.out.println("RATE="+rate);
System.out.println("TIME="+time+”years”);
System.out.println("SIMPLE INTEREST=Rs."+si);
}
}
class Compound extends Account
{
protected double rate,time,ci;
public Compound(int a1,double p1,double r,double t)
{
super(a1,p1);
rate=r;
time=t;
ci=0.0;
}
public void display( )throws IOException
{
double x=Math.pow((1+rate/100),t);
ci=(pri*x)-pri; super.display();
System.out.println("RATE="+rate);
System.out.println("TIME="+time+”years”);
System.out.println("COMPOUND INTEREST=Rs."+ci);
}
}
class Bank
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int ch,a;
double p,r,t;
do
{
System.out.println("Enter account no.");
a=Integer.parseInt(br.readLine());
System.out.println("Enter principle");
p=Double.parseDouble(br.readLine());
System.out.println("Enter rate");
r=Double.parseDouble(br.readLine());
System.out.println("Enter time");
t=Double.parseDouble(br.readLine());
System.out.println("Enter choice:\n1.Simple
interest\n2.Compound\n3.Exit");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:Simple obj=new Simple(a,p,r,t);
obj.display();
break;
case 2:Compound obj1=new Compound(a,p,r,t);
obj1.display();
break;
default:System.out.println("INVALID CHOICE");
}
System.out.println("WISH TO ADD MORE");
ch=Integer.parseInt(br.readLine());
}while(ch!=3);
}
}

OUTPUT:
Enter account no.
230
Enter principle
2000
Enter rate
2
Enter time
3
Enter choice:
1.Simple interest
2.Compound
3.Exit");
1
ACCOUNT NO=230
PRINCIPLE=Rs.2000.0
RATE=2
TIME=3years
SIMPLE INTEREST=Rs.120
WISH TO ADD MORE
3

ALGORITHM:
Step1:Declare and initialize required variables accno, pri and initialize them
with parameters passed in constructor of class ‘Account’.
Step2:In the display( ) function show the values of the variables.
Step3:In the class ‘Simple’ that extends ‘Account’ initialize the required
variables rate, time and si .
Step4:Initialize the variables with parameters passed in constructor.
Step5:In the display( ) function calculate the value of simple interest and
call superclass’ display( ) and show the values of the variables.
Step6:In the class ‘Compound’ that extends ‘Account’ initialize the required
variables rate, time and ci .
Step7:Initialize the variables with parameters passed in constructor.
Step8:In the display( ) function calculate the value of compound interest and
call superclass’ display( ) and show the values of the variables.
Step9:In the class ‘Bank’ declare variables to store account no.,principle,
rate,time and for choice.
Step10:Start a do…while loop that terminates if choice of the user is 3.
Step11:In the loop, accept the values of variables from user and choice.
Step12:Match the value of choice in switch( ) case and make object of
required class to call its function.
Step13:End the process according to user’s choice.

You might also like