Kaprekar Number
Kaprekar Number
Question: 1
Kaprekar number: When a number having ‘d’ digits is squared and the sum of the two
halves, left and right (in such a way that the left part has ‘d’ digits and the right part has ‘d’
or ‘d-1’ digits) in the square is equal to the number itself, it is called a Kaprekar number.
Example: 9, as 9x9=81 and 8+1=9.
Aim:
To accept a number and check whether the number is a kaprekar number or not.
Program:
import java.util.*;
class kaprekarNumber
String s = Integer.toString(n);
if(s.length()>=2){
String f = s.substring(0,mid);
String t = s.substring(mid);
if (num == n1)
return true;
else
return false;
else
return false;
int n = in.nextInt();
if(check(n,(n*n)))
System.out.println("Kaperkar number!");
else
Output:
Lucky Number
Question: 2
Lucky number: In a sequence of natural numbers, if every second number is removed, and
then from the remaining numbers every third number is removed, and so on, some
numbers remain indefinitely in the list. Such numbers are called lucky numbers.
Example: 1,2,3,4,5,6,7,8,9,10.
After removing each second number, 1,3,5,7,9
After removing each third number, 1,3,7 => These are lucky numbers within range 10
Aim:
To accept a number and check whether the number is a Lucky number or not.
Program:
import java.util.*;
public class Lucky
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of elements: “);
int n=sc.nextInt();
int arr[]=new int[n];
int elements=n;
for(int i=0;i<n;i++)
{
arr[i]=i+1;
}
int del=1;
while(del<n)
{
for(int i=del; i<n; i+=del)
{
for(int j=i; j<n-1; j++)
{
arr[j]=arr[j+1];
}
n--;
}
del++;
}
System.out.print(“Hence, the Lucky Numbers Less than “+elements+” are: “);
for(int i=0; i<n; i++)
{
System.out.print(arr[i]+” “);
}
}
}
Output:
Prime Adam
Question: 3
Aim:
To accept a number and check whether the number is a PrimeAdam number or not.
Program:
import java.util.Scanner;
class PrimeAdam
int rev = 0;
while (num != 0)
{
int d = num % 10;
rev = rev * 10 + d;
return rev;
int c = 0;
if (num % I == 0)
c++;
}
}
return c == 2;
int n = in.nextInt();
if(isAdam(n)&& isPrime(n))
else
Output:
Mobius Function
Question: 4
Mobius function: The MOBIUS function M(N) for a natural number N is defined as follows:
1. M(N) = 1 if N = 1
2. M(N) = 0 if any prime factor of N is contained in N more than once
3. M(N) = (-1)p if N is a product of ‘p’ distinct prime factors Example :
M(78) = -1 ( for 78 = 2 * 3 * 13 M(78) = ( -1)3 = -1 )
M(34) = 1 ( for 34 = 2 * 17 M(34) = ( -1)2 = 1 )
Aim:
To accept a number and check whether the number is a Lucky number or not.
Program:
import java.util.*;
class Mobius
{
static boolean isPrime(int n)
{
int n1,i,k = 0;
n1 = n/2;
if(n==0||n==1)
return false;
else
{
for(i = 2; i <= n1; i++)
if(n%i == 0)
k++;
if(k==0)
return false;
else
return true;
}
}
static int mobiusf(int n)
{
if(n==1)
return(1);
int p=0;
for (int i=1;i<=n;i++)
{
if (n%i==0 && isPrime(i))
{
if (n % (i * i) == 0)
return 0;
else
p++;
}
}
return (p%2==0) ? 1 : -1;
}
Aim:
To accept a number and check weither the number is goldbash number or not.
Program:
import java.util.*;
class Goldbach
int num=sc.nextInt();
if(num!>9&&num!<50)
else{
k=num;
if(num%2!=0)
else
for(i=1;i<=num;i++)
for(j=1;j<=i;j++)
if(i%j==0)
c++;
if((c==2)&&(i%2!=0))
arr1[b]=i;
arr2[b]=i;
b++;
c=0;
for(j=i;j<b;j++)
sum=arr1[i]+arr2[j];
if(sum==k)
System.out.print(arr1[i]+” , “+arr2[j]);
System.out.println();
Output:
Date Calculate
Question: 6
Design a program to accept a day number (between 1 and 366), year (int digits) from the
user to generate and display the corresponding date. Also, accept ‘N’ (1 <= N <= 100) from
the user to compute and display the future date corresponding to ‘N’ days after the
generated ate.Display an error message if the value of the day number, year and N are not
within the limit or not according to the condition specified
Aim:
To accept a number and year and compute the date of the following number.
Program:
import java.util.Scanner;
class DateCalculator
if (y % 400 == 0) {
ret = true;
else if (y % 100 == 0) {
ret = false;
else if (y % 4 == 0) {
ret = true;
else {
ret = false;
return ret;
int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(leap) {
monthDays[1] = 29;
int daySum = 0;
daySum += monthDays[i];
break;
}
Sb.append(date);
Sb.append(“TH “);
Sb.append(monthNames[i]);
Sb.append(“, “);
Sb.append(year);
return Sb.toString();
System.out.print(“YEAR: “);
int n = in.nextInt();
return;
nYear = nYear + 1;
nYear = nYear + 1;
System.out.println();
System.out.println(“DATE: “ + dateStr);
System.out.println(“DATE AFTER “ + n
+ “ DAYS: “ + nDateStr);
Output:
Mirror Matrix
Question: 7
Aim:
To accept a element in double dimensional array and display the orginal matrix and mirror
matrix
Program:
import java.util.*;
class HelloWorld {
int m = in.nextInt();
int n = in.nextInt();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
mat[i][j]= in.nextInt();
}
System.out.println(“Original Matrix:”);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.print(mat[i][j]+ “\t”);
System.out.println();
System.out.println();
System.out.println(“Mirror matrix:”);
for(int i=0;i<m;i++){
for(int j=(n-1);j>-1;j--)
System.out.print(mat[i][j]+ “\t”);
System.out.println();
}
Output:
Saddle Point
Question: 8
Saddle point: Saddle point of a matrix is the lowest element in row, which is also the
maximum element in the column. WAP to get in out for a matrix of order mxn and print the
saddle point of it.
Aim:
To accept a order of matrix mxn and get the input for elements, then find and print the saddle
point of the matrix.
Program:
import java.util.*;
class HelloWorld {
int m = in.nextInt();
System.out.println("Enter no. of columns");
int n = in.nextInt();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
mat[i][j]= in.nextInt();
System.out.println("Original Matrix:");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.print(mat[i][j]+ "\t");
System.out.println();
System.out.println();
Output:
Magic Square
Question: 9
Magic square: A square matrix is said to be a magic square if the sum of each row, each
column and each diagonal is the same. WAP to accept the order of matrix ‘n’ and create a
magic square and finally display it.
Aim:
To accept a order of matrix n and create a magic square and finally display it.
Program:
public class MagicSquare
{
public void makeSquare(int s)
{
int magicSqr[][] = new int[s][s];
int r = s / 2;
int c = s – 1;
for (int no = 1; no <= s * s;)
{
if (r == -1 && c == s)
{
c = s – 2;
r = 0;
}
else
{
if (c == s)
{
c = 0;
}
if (r < 0)
{
r = s – 1;
}
}
if (magicSqr[r][c] != 0)
{
c = c – 2;
r = r + 1;
continue;
}
else
{
magicSqr[r][c] = no;
no = no + 1;
}
c = c + 1;
r = r – 1;
}
System.out.println(“The Magic Square for “ + s + “: \n”);
System.out.println(“Sum of each column or row “ + s * (s * s + 1) / 2 + “: \n”);
for (r = 0; r < s; r++)
{
for (c = 0; c < s; c++)
{
System.out.print(magicSqr[r][c] + “ “);
}
System.out.println();
}
}
Aim:
To accept a order of matrix n and get the input for elements and arrage it in a circular manner.
Program:
import java.util.*;
class circu {
Aim:
To accept a order of matrix n and get the input for elements and find the transpose of the
matrix
Program:
import java.util.*;
class HelloWorld {
int m = in.nextInt();
int n = in.nextInt();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
mat[i][j]= in.nextInt();
System.out.println(“Original Matrix:”);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.print(mat[i][j]+ “\t”);
System.out.println();
System.out.println();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.print(mat[j][i]+ “\t”);
System.out.println();
}
Output:
Symmetric Matrix
Question: 12
Write a program to declare a square matrix A[][] of order MxM where ‘M’ is the number of
rows and the number of coloumns, such that Must be greater than 2 and less than 10.
Accept the value of M as user input. Display an appropriate message for invalid input.
Allow the user to input integers into this matrix. Perform the following tasks:
A) Display the original matrix.
B) Check if the given matrix is Symmetric or not. A square matrix is said to be
Symmetric, if the element of the ith row and the jth column is equal to the element
of jth row and the ith column.
C) Find the sum of the elements of left diagonal and the sum of the elements if right
diagonal of the matrix and display them. Example :
Aim:
To accept a order of matrix n and get the input for elements and check if the matrix is
symmetric or not and find sum of its diagonals
Program:
import java.io.*;
class Symm
{
int left=0,right=0,m,I,j, arr[][];
boolean bool=false;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeValues() throws Exception
{
System.out.println(“Enter the value of ‘m’;”);
m=Integer.parseInt(br.readLine());
if(m>=10)
{
System.out.println(“Matrix size is out of range”);
return;
}
arr=new int[m][m];
for(i=0;i<m; i++)
{
for(j=0;j<m;j++)
{
System.out.println(“value:”);
arr[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println(“Original Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(“ “+arr[i][j]);
}
System.out.println();
}
for(i=0;I < m ; i++)
{
for(j=0;j<m; j++)
{
if(arr[i][j]!=arr[j][i])
{
bool=true;
break;
}
}
if(bool==true)
break;
}
if(bool)
System.out.println(“The given matrix is not symmetric”);
else
System.out.println(“The given matrix is symmetric”);
for(i=0;i<m ; i++)
{
for(j=0;j<m; j++)
{
if(i==j)
left=left+arr[i][j];
if(i+j==m-1)
right=right+arr[i][j];
}
}
System.out.println(“Sum of the left diagonal=”+left);
System.out.println(“Sum of the right diagonal=”+right);
}
WAP in Java to get two matrices of order mxn and pxq, and check for multiplication
compatibility. If they are compatible, multiply both and display the product matrix. Else,
display an appropriate message that the matrices are non-compatible.
Aim:
To input two different matrices and check for the multiplication compatibility and if they
are compatible then want to multiply both and display the product matrix
Program:
Import java.util.*;
public class MatrixMultiplicationExample {
Aim:
To accept 10 names and store in a text file in names.txt and sort the name alphabetically and
store it in another text file orde.txt
Program:
import java.io.*;
class Txt_Sort {
public static void main(String[] args)
{
Scanner in = new Scanner(“System.in);
System.out.println(“Enter no. of entries”);
int n = in.nextInt();
String names[] = new names[n];
System.out.println(“Enter the names”);
for(int i=0;i<n;i++)
names = in.next;
String temp;
for (int i = 0; i < n; i++) {
for (int j = I + 1; j < n; j++) {
if (names[i].compareTo(names[j]) > 0) {
Temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.println( “The names in alphabetical order are: “);
for (int i = 0; i < n; i++) {
System.out.println(names[i]);
}
}
}
Product Code
Question: 15
A binary file named "ABC.DAT" contains the product code, unit price and quantity for
number of items. Write a method to accept a product code 'p' and check the availability of
the product and display with an appropriate message. The method declaration is as
follows. void findpro(int p)
Aim:
To accept number items and store their product code, uint price and quantity and then check
the availability of the product and want to display appropriate message
Program:
import jaava.util.*;
import java.io.*;
class product
int pc,q,up;
Scanner sc=newScanner(System.in);
input();
findpro(int p);
pc=sc.nextint();
q=sc.nextint();
up=sc.nextint();
try
BufferedReader br=BufferedReader(fr);
do
pc = be.readline();
while(pc==””)
System.out.println(on);
System.out.printin(q);
System.out.printin(up);
Catch(Exception e)
System.out.println(e);
Caesar Cipher
Question: 16
Caesar cipher: Caesar cipher is an encryption method which rotates each letter by 13
places. The symbols are left unchanged.
Example: INPUT: Hello! How are you? OUTPUT: Uryyb! Ubj ner lbh?
Aim:
To accept a String and encrypt the string by rotating each letter by 13 places.
Program:
import java.util.*;
class CaesarCipher
{
static char encrypt(int n){
if(n>=65 && n<=78 || n>=97 && n<=110)
n+=13;
else if(n>=78 && n<=90 || n>=110 && n<=122)
n-=13;
return (char)n;
}
Word Count
Question: 17
Word count: Accept a paragraph of text and count the number of words in each sentence,
separated by ‘.’, ‘!’ or ‘?’. Example: Apple is a fruit. It is sweet! Number of words in ‘Apple
is a fruit’: 4. Number of words in ‘It is sweet!’: 3
Aim:
To accept a paragraph and count the number of words in each sentence.
Program:
import java.util.*;
class wordc
{
static int wc(String y)
{
int c = 0;
for(int i = 0;i<y.length();i++)
{
if(y.charAt(i)==' ')
c++;
}
return c;
}
static void sep(String s)
{
String t = "";
for(int i = 0;i<s.length();i++)
{
char c = s.charAt(i);
int u = (int)c;
t+=c;
if(u==33||u==46||u==63)
{
System.out.println("No of words in "+t+": " +wc(t));
t="";
}
}
}
static void main()
{
Scanner in = new Scanner (System.in);
System.out.println("ENTER A STRING");
String y = in.nextLine();
sep(y);
}
Sentence Rearrange
Question: 18
Write a program to accept a sentence which may be terminated by either ‘.’ , ‘?’ or ‘!’ only.
The words are to be separated by a single blank space and are in UPPER CASE.
Perform the following tasks:
(a) Check for the validity of the accepted sentence only for the terminating
character.
(b) Arrange the words in ascending order of their length. If two or more words
have the same length, then sort them alphabetically.
(c) Display the original sentence along with the converted sentence.
Aim:
To accept a paragraph and rearrange the words according to their length.
Program:
import java.util.*;
System.out.println(“Enter a sentence:”);
if (str.charAt(len – 1) != ‘.’) {
System.out.println(“Invalid Input!”);
return;
if (Character.isLowerCase(str.charAt(0))) {
System.out.println(“Invalid Input!”);
System.out.println(“Sentence should start with upper case letter.”);
return;
strArr[i] = st.nextToken();
String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
strArr[0] = Character.toUpperCase(strArr[0].charAt(0)) +
strArr[0].substring(1);
System.out.println(“Sorted String:”);
System.out.print(strArr[i]);
if (i == wordCount – 1) {
System.out.print(“.”);
else {
System.out.print(“ “);
Adder Program
Question: 19
A class Adder has been defined to add any two accepted time.
Example: Time A-6 hours 35 minutes Time B-7 hours 45 minutes. Their sum is-14 hours 20
minutes (where 60 minutes 1 hour) The details of the members of the class are given
below:
Class name: Adder
Data member instance variable:
a[]: integer array to hold two elements (hours and minutes) Member
functions/methods.
Adder constructor to assign 0 to the array elements
void readtime() to enter the elements of the array
void addtime(Adder X, Adder Y) adds the time of the two parameterized objects X and Y
and stores the sum in the current calling object
void disptime(): displays the array elements with an appropriate message (i.e. hours and
minutes).
Specify the class Adder giving details of the constructor, void readtime(), void addtimes
and void disptime(). Define the main() function to create objects and call the functions
accordingly to enable the task.
Aim:
To accept two different times in string format and print the sum of the time
Program:
import java.io.*;
class Adder {
inta[];
Adder()
{
a = new int[2];
}
void readtime() throws IOException {
InputStreamReader x = new InputStreamReader(System.in);
BufferedReader y = new BufferedReader(x);
System.out.println(“Time: ”);
System.out.println(“Enter hour:”);
a[0] = Integer.parseInt(y.readLine());
System.out.println(“Enter minute :”);
a[1] = Integer.parseInt(y.readLine());
}
void addtime(Adder X, Adder Y) {
int hour1 = X.a[0];
int min1 = X.a[1];
int hour2 = Y.a[0];
int min2 = Y.a[1];
int hourSum = hour1 + hour2;
int minSum = min1 + min2;
a[0] = hourSum + (minSum/60);
a[1] = minSum%60;
}
void disptime() {
System.out.println(“Their sum is-“)
System.out.println(“hours =” + a[0] +” minutes =” + a[1]);
}
Collection Program
Question: 20
A class collection contains an array of 100 integers, Using the following class
descriptions create an array with some common elements from two integers
arrays. Some of the members of the class are given below:
Class name Collection
Data members
arr[]
Members/Function
Collection(int) Parameterized constructor to assign the length of the array. to accept the
array elements, returns a Collection containing the common elements of current Collection
object and the collection object passed as a parameter.
Void arrange() sort the array elements of the object containing common elements in
ascending order using any sorting technique.
Aim:
To accept 100 integer from the user and sort the integer using any sorting technique
Program:
import java.io.* ;
int arr[];
int size ;
public Collection( ) {
Size = 0;
}
Size = size ;
System.out.print(arr[i] +””);
System.out.println( ) ;
int HIndex = i ;
HIndex = j ;
arr[HIndex] = temp ;
System.out.println(“Enter
Mixer Program
Question: 21
A class Mixer has been defined to merge two sorted integer arrays in ascending order.
Some of the members of the class are given below:
Classname:Mixer
Data members/instance variables: I
nt arr[ ]: to store the elements of an array
int n: to store the size of the array
Member functions:
Mixer(int nn): constructor to assign n=nn
void accept(): to accept the elements of the array in ascending order
without any duplicates
Mixer mix(Mixer A) : to merge the current object array elements with the
parameterized array elements and return the resultant object
void display(): to display the elements of the array
Specify the class Mixer, giving details of the constructor(int), void accept( ),
Mixer mix(Mixer) and void display() . Define the main() function to create
an object and call the function accordingly to enable the task.
Aim:
To accept to different arrays and merge them using object.
Program:
import java.util.Scanner;
class Mixer {
int[] arr;
int n;
Mixer(int nn) {
n = nn;
void accept() {
arr[i] = num;
} else {
i--;
Mixer mix(Mixer A) {
int i = 0, j = 0, k = 0;
result.arr[k++] = arr[i++];
} else {
result.arr[k++] = A.arr[j++];
}
}
while (i < n) {
result.arr[k++] = arr[i++];
result.arr[k++] = A.arr[j++];
return result;
void display() {
System.out.println();
}
static void main() {
System.out.println();
m1.accept();
m2.accept();
Mixer mm = m1.mix(m2);
mm.display();
Admission Program
Question: 22
A class Admission contain the admission numbers of 100 students. Some of the data
members/member functions are given below:
Class name: Admission
Data member/instance variable:
Adno[ ]: Integer array to store admission numbers
Member functions/methods:
Admission(): constructur to initialize the array elements void fillArray(): to accept the
element of the array in ascending order int binSearch(int I. int u, int v): to search for a
particular admission number(v) using binary search and recursive technique and return 1 if
Specify the class Admission giving details of the constructor, void fillArrray() and int
hinSearch(int. int, int). Define the main() function to create an object and call the functions
accordingly to enable task.
Aim:
To accept the data of 100 students and perform binary search in the array
Program:
import java.util.*;
class Admission {
Admission() {
Adno[i] = scanner.nextInt();
}
static int bs(int n) {
int l = 0,r=9;
while (l <= r) {
int m = l + (r - l) / 2;
if (Adno[m] == n)
return 1;
if (Adno[m] < n)
l = m + 1;
else
r = m - 1;
return -1;
ob.fl();
int sn = scanner.nextInt();
int r = ob.bs(sn);
if (r == 1) {
} else {
System.out.println();
REVERSE STRING
(USING RECURSION)
Question: 23
A class Revstr defines a recursive function to reverse a string and check whether it is a
palindrome. The details of the class are given below:
Class name : Revstr
Data members
Str : stores the string.
Revst : stores the reverse of the string. Member functions
void getStr() : to accept the string.
void recReverse(int) : to reverse the string using recursive technique.
void check() : to display the original string, its reverse and whether the string is a
palindrome or not.
Specify the class Revstr giving details of the functions void getStr(), void recReverse(int)
and void check()
Aim:
To accept a String and reverse it using recursion technique.
Program:
Change Program
(Using recursion)
Question: 24
Design a class Change to perform string related operations. The details of the class are
given below:
Data members/instance variables :
str : stores the word,
newstr : stores the changed word,
len : stores the length of the word
Member functions :
Change( ) : default constructor,
Void inputword( ) : to accept word,
Char caseConvert(char ch) : converts the case of the character and returns
it,
Void recchange(int) : extracts characters using recursive technique and
changes its case using caseconvert( ) and forms a new word,
Void display( ) : displays both the words
Specify the class Change, going details of the Constructor( ), and member
functions void inputword( ),char caseconvert(char ch),void recchange(int)
and void display(). Define the main() function to create an object and call
the functions accordingly to enable the above change in the given word.
Aim:
To input a string from the user and convert the lowercase letters to uppercase and vise versa
using recursion
Program:
import java.util.*;
class revstr
{
System.out.println("Enter a string");
str = in.nextLine();
if(r==0)
return;
else{
revst+=str.charAt(--r);
recreverse(r);
if(str.equals(revst))
else
System.out.println();
getstr();
recreverse(str.length());
check();
Happy Number
(Using recursion)
Question: 25
A happy number is a number in which the eventual sum of the square of the digits of the
number is equal to 1.
Example:
28=2^2+8^2=4+64=68
68=6^2+8^2=36+64=100
100=1^2+0^2+0^2=1 +0+0=1
Hence,28 is a happy number.
Example:12 =1^2+2^2=1+4=5
Hence, 12 is not a happy number.
Design a class Happy to check if a given number is a happy number.Some of the member of
the class are given below:
Classname:Happy
Data members/ instance variables:
n: stores the number Member
functions:
Happy(): constructor to assign 0 to n
void getnum(int nn): to assign the parameter value to the number n=nn int
sum_sq_digits(int x): returns the sum of the square of the digit of the
number x. using the recursive technique
void ishappy(): checks if the given number is a happy number by calling the
function sum_sq_digits (int) and displays an appropriate message Specify
the class Happy giving details of the constructor( ), void getnum(int) , int
sum_sq_digits(int) and void ishappy() . Also define a main() functionc to
create an object and call the methods to check for happy number.
Aim:
To input a number from the user and check weither the number is happy number or not using
recursion
Program:
import java.util.*;
class Happy {
private int n;
Happy() {
N = 0;
}
N = nn;
int sum_sq_digits(int x) {
if (x == 0) {
return 0;
else{
void ishappy() {
int num = n;
while (num>9) {
num = sum_sq_digits(num);
if (num == 1) {
else {
Ob.getnum(num);
Ob.ishappy();
Armstrong Number
Question: 26
An Armstrong number is such that the sum of the cube of the digits of the number is the
number itself.
Example 153= 13+53+33
Design a class Arm to perform the given task. Some of the members of the class are given
below:
Class name : Arm
Data member/Instance variables : no :
integer to store the number
sum : integer to store the sum of the cube of the digits Member
methods:
Arm(….): to initialize member data no, and assign 0 to sum.
long fnPower(int a, int b) : to calculate a^b using recursive function void
fnPerform() : to verify and print whether the member data is an
Armstrong number or not.
Specify the class Arm, giving the details of the above member data and methods.
Also define the main() to create an object and call the relevant methods accordingly
to enable the task
Aim:
To input a number and check weither the number is armstrong number or not using recursion
Program:
import java.util.`*;
class Arm {
int no;
int sum;
Arm(int num) {
no = num;
sum = 0;
return 1;
void fnPerform() {
temp /= 10;
If (sum == no) {
} else {
ob.fnPerform();
Aim:
To accept the length, breadth and height and print the area and the perimeter of the
parallelogram using inheritance
Program:
A superclass Detail has been defined to store the details of the customer. Define a subclass
Bill to compute the monthly telephone charge of the customer as per the chart is given
below:
Number of calls:
Rate 1 – 100: Only rental charge
101 – 200: 60 paise per call + rental charge
201 – 300: 80 paise per call + rental charge Above 300:
1 rupee per call + rental charge
The details of both the classes are given below:
Class name: Detail
Data members/instance variables:
name: to store the name of the customer
address: to store the address of the customer
telno: to store the phone number of the customer
rent: to store the monthly rental charge
Member functions:
Detail (…): parameterized constructor to assign values to data members
void show (): to display the details of the customer
Class name: Bill Data
members/instance variables:
n: to store the number of calls
amt: to store the amount to be paid by the customer
Member functions: Bill (…): parameterized constructor to assign values to data
members of both classes and to initialize amt = 0.0
void cal(): calculate the monthly telephone charge as per the chart is given
above
void show(): displays the details of the customer and amount to be paid.
Specify the class Detail giving details of the constructor, and void show().
Using the concept of inheritance, specify the class Bill giving details of the
constructor(), void cal() and void show()
Aim:
To store the details of the customer and compute the monthly telephone charge of the
customer
Program:
import java.util.*;
class Detail {
String name;
String address;
String telno;
double rent;
name = n;
address = a;
telno = t;
rent = r;
void show() {
System.out.println(“Name: “ + name);
System.out.println(“Address: “ + address);
import java.util.*;
int n;
double amt;
super(n, a, t, r);
this.n=num;
amt = 0.0;
}
void cal() {
If (n <= 100) {
amt = rent;
} else {
void show() {
super.show();
ob.cal();
ob.show();
Bank Program
Question: 29
A super class Bank has been defined to store the details of a customer.
Define a sub-class
Account that enables transactions for the customer with the bank. The
details of both the classes are given below:
Class name : Bank
Data member/instance variable:
name : stores the name of the customer
accno : stores the account number
p : stores the principal amount in decimals
Member functions/methods:
Bank(…) : parameterized constructor to assign values to the instance variables
void display( ) : displays the details of the customer
Class name: Account
Data member/instance variable:
amt : stores the transaction amount in decimals
Member functions/methods:
Account(…) : parameterized constructor to assign values to the instance
variables of both the classes
void deposit( ) : accepts the amount and updates the principal as p=p + amt
void withdraw( ) : accepts the amount and updates the principal as p=p+amt If
the withdrawal amount is more than the principal amount, then display the
message “INSUFFICIENT BALANCE”. If the principal amount after withdrawal is
less than 500, then a penalty is imposed by using the formula p=p-(500-p)/10
void display( ) : displays the details of the customer Assume that the super class
Bank has been defined.
Using the concept of Inheritance, specify the class Account giving details of the
constructor(…), void deposit( ),void withdraw( ) and void display( ).
Aim:
Using inheritance store the details of the customer in the bank and wanted to compute the
withdraw amount and the deposit amount
Program:
class Bank {
String name;
int accno;
double p;
name = n;
accno = acc;
p = principal;
void display() {
System.out.println(“Name: “ + name);
System.out.println(“Principal Amount: “ + p)
import java.util.*;
amt = amount;
}
void deposit() {
p += amt;
void withdraw() {
if (amt > p) {
System.out.println(“INSUFFICIENT BALANCE”);
else {
p -= amt;
if (p < 500) {
p -= (500 – p) / 10;
void display() {
super.display();
}
public static void main() {
String n = in.nextLine();
int ac = in.nextInt();
System.out.println(“Enter principle”);
int p = in.nextInt();
int ch = in.nextInt();
if(ch==1)
int a = in.nextInt();
System.out.println();
System.out.println(“Before Transactions:”);
customerAccount.display();
customerAccount.withdraw();
System.out.println();
System.out.println(“After Transactions:”);
customerAccount.display();
}
if(ch==2)
int a = in.nextInt();
System.out.println();
System.out.println(“Before Transactions:”);
customerAccount.display();
System.out.println();
customerAccount.deposit();
System.out.println(“After Transactions:”);
customerAccount.display();
Insertion Sort
Question: 30
WAP in Java to accept n elements from user and sort it using Insertion sort
method.
Aim:
To accept n element from the user and sort them using insertion sort techinque
Program:
import java.util.*;
Class Insertion
int n = in.nextInt();
System.out.println(“Enter “ + n + “ elements:”);
arr[i] = in.nextInt();
int n = arr.length;
for (int i = 1; i < n; i++) {
int k = arr[i];
int j = I – 1;
arr[j + 1] = arr[j];
j--;
arr[j + 1] = k;
System.out.print(arr[i] + “ “);
input();
System.out.println(“Orignal array:”);
display();
insertionSort();
System.out.println(“\nSorted array:”);
display();
Register Program
Question: 31
Register is an entity which can hold a maximum of 100 names. The register enables the user
to add and remove names from the topmost end only. Define a class Register with the
following details:
Aim:
To create a register which can maximum hold upto 100 names. And the register enables the
user to add and remove names from the topmost end only.
Program:
import java.util.*;
class Register {
String stud[];
int cap;
int top;
Register(int max) {
cap = max;
top = -1;
boolean isEmpty() {
boolean isFull() {
If (isFull()) {
stud[++top] = name;
String pop() {
if (isEmpty()) {
return null;
String rn = stud[top];
stud[top] = null;
top--;
return rn;
void display()
System.out.print(stud[i] + “ “);
}
boolean v = true;
while(v)
System.out.println(“Enter 4 to exit”);
int ch = in.nextInt();
if(ch==1)
String na ;
ob.push(in.next());
System.out.println();
If(ch==2)
Ob.pop();
if(ch==3)
ob.display();
if(ch==4)
v=false;
return;
Queue Program
Question: 32
Queue is a linear data structure which enables the user to add elements from the rear end
and remove elements from the front end only, using the concept of FIFO Note:. Since
insertion and deletion both takes place from different ends, we have to keep record of the
index of both the front as well as the rear end. Consider a queue implemented using an
array q[] index of the front element is stored in the variable' front and index of the last
element is stored in the variable rear.
Aim:
To create a queue linear data structure and enables the user to add elements from the rear
end and remove the element s from the front end only, using the councept of fifo note
Program:
import java.util.*;
Class Queue {
int q[];
int front;
int rear;
int maxSize;
maxSize = size;
q = new int[maxSize];
front = -1;
rear = -1;
boolean isEmpty() {
boolean isFull() {
If (isFull()) {
System.out.println(“Queue is full. Cannot add elements.”)
return;
If (isEmpty()) {
front = 0;
q[++rear] = item;
int dq() {
If (isEmpty()) {
return -1;
front++;
return item;
}
Void display() {
If (isEmpty()) {
System.out.println(“Queue is empty.”);
return;
System.out.println(“Queue elements:”);
System.out.print(q[i] + “ “);
System.out.println();
boolean v = true;
while (v) {
int ch = in.nextInt();
if (ch == 1) {
ob.eq(in.nextInt());
} else if (ch == 2) {
ob.dq();
} else if (ch == 3) {
ob.display();
} else if (ch == 4) {
v = false;
return;
Linear Queue
Question: 33
Write a java program to perform the following functions function in a linear queue.
IsEmpt() check the queue is empty
isFull() check queue is full
display() display the elements in the queue
enqueue() insert an element in the queue
dequeue() remove the element from the queue
Aim:
To create a linear queue data structure and enables the user to add elements from the rear
end and remove the elements
Program:
import java.util.*;
class Linear {
int queue[];
int front;
int rear;
int maxSize;
Linear(int size) {
maxSize = size;
queue = new int[maxSize];
front = -1;
rear = -1;
}
boolean isEmpty() {
return front == -1;
}
boolean isFull() {
return rear == maxSize – 1;
}
void enqueue(int item) {
if (isFull()) {
System.out.println(“Queue is full. Cannot enqueue.”);
return;
}
if (isEmpty()) {
front = 0;
}
queue[++rear] = item;
System.out.println(“Enqueued: “ + item);
}
int dequeue() {
if (isEmpty()) {
System.out.println(“Queue is empty. Cannot dequeue.”);
return -1;
}
int item = queue[front];
if (front == rear) {
front = rear = -1;
}
else {
front++;
}
System.out.println(“Dequeued: “ + item);
return item;
}
void display() {
if (isEmpty()) {
System.out.println(“Queue is empty.”);
return;
}
System.out.print(“Queue elements: “);
for (int I = front; I <= rear; i++) {
System.out.print(queue[i] + “ “);
}
System.out.println();
}
Aim:
To explain the importance of the exception handling by explicitly creating a exception
Program:
import java.util.*;
class Explicit {
int n = in.nextInt();
int d = in.nextInt();
try {
System.out.println(“Result: “ + (n/d));
catch (ArithmeticException e) {
Infix-Postfix
(using stack)
Question: 35
Aim:
To accept expression and want to change the infix to postfix expression using stack
Program:
import java.util.*;
class ItoP
int top=-1;
void push(char c)
Try {
a[++top]= c;
}
catch(StringIndexOutOfBoundsException e)
System.exit(0);
char pop()
return a[top--];
boolean isEmpty()
return (top==-1);
char peek()
return a[top];
}
static String toPostfix(String infix)
char symbol;
for(int i=0;i<infix.length();++i) {
symbol = infix.charAt(i);
if(Character.isLetter(symbol))
else if (symbol==’(‘)
ob.push(symbol);
else if (symbol==’)’) {
ob.pop();
else {
ob.push(symbol);
}
}
while (!ob.isEmpty())
return postfix;
if (x == ‘+’ || x == ‘-‘)
return 1;
return 2;
return 0;
Output: