Professional Documents
Culture Documents
Karprekar Number: Question No: 1
Karprekar Number: Question No: 1
Question No: 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
import java.util.*;
public class karprekar
{
public static boolean check(int num, int n)
{
String s = Integer.toString(n);
if (s.length()>=2)
{
int mid =s.length()/2;
String f =s.substring(0,mid);
String t =s.substring(mid);
int n1 =Integer.valueOf (f) + Integer.parseInt(t);
if (num == n1)
{
return true;
}
else
return false;
}
else
return false;
}
public static void main(String args[])
{
Scanner in =new Scanner(System.in);
System.out.println("enter a number");
int n =in.nextInt();
if (check(n,(n*n)))
System.out.println("KARPREKAR");
else
System.out.println("NOT A KARPREKAR");
}
}
OUTPUT:
LUCKY NUMBER
QUESTION NO: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.
PROGRAM:
import java.util.*;
int n=sc.nextInt();
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)
arr[j]=arr[j+1];
n--;
del++;
System.out.print(arr[i]+" ");
System.out.println();
System.out.print(arr[i]+" ");
}
OUTPUT:
Prime Adam
Question: 3
Prime Adam: A Prime-Adam integer is a positive integer (without leading zeros) which is a prime as
well as an Adam number. Prime number: A number which has only two factors, i.e. 1 and the
number itself. Example: 2, 3, 5, 7 … etc. Adam number: The square of a number and the square of
its reverse are reverse to each other. Example: If n = 13 and reverse of 'n' = 31, then, (13)2 = 169
(31)2 = 961 which is reverse of 169 thus 13, is an Adam number. Accept two positive integers m and
n, where m is less than n as user input. Display all Prime-Adam integers that are in the range
between m and n (both inclusive) and display the output.
Aim: To print all the prime adam numbers within a specified range
Program:
import java.util.*;
int rev = 0;
return rev;
{
int a = square(num);
int b = square(reverseDigits(num));
if (a == reverseDigits(b))
return true;
return false;
String f = "";
int c = 0,num;
boolean u = true;
if(isAdamNumber(i) != true)
u=false;
else
if(i%num==0)
u=false;
break;
return u;
}
if (fin(num))
else
Output:
MOBIUS FUNCTION
QUESTION NO : 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 ) M(12) = 0 ( for 12 = 2 * 2 * 3
M(12) = 0 for 2 appears two times) M(17) = -1 ( for 17 = 17 M(17) = ( -1)1 = -1 )
AIM: To check a number by the Mobius function and return its value as specified above
PROGRAM:
import java.util.*;
if (n < 2)
return false;
if (n % i == 0)
return false;
return true;
if (N == 1)
return 1;
int p = 0;
if (N % i == 0 && isPrime(i)) {
if (N % (i * i) == 0)
return 0;
else
p++;
return (p % 2 != 0) ? -1 : 1;
System.out.println("Enter no");
int N =in.nextInt();
OUTPUT:
GOLDBACH
QUESTION NUMBER : 5
A Goldbach number is a positive even integer that can be expressed as the sum of two odd
primes. Note: All even integer numbers greater than 4 are Goldbach numbers. Example: 6 = 3
+ 3 10 = 3 + 7 10 = 5 + 5 Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd
prime pairs, i.e. 3 and 7, 5 and 5. Write a program to accept an even integer ‘N’ where N > 9
and N < 50. Find all the odd prime pairs whose sum is equal to the number ‘N’.
AIM: To print all the odd prime pairs whose sum is equal to the number ‘N
PROGRAM:
import java.util.Scanner;
int c = 0;
if (num % i == 0) {
c++;
return c == 2;
int n = in.nextInt();
if (n % 2 != 0) {
return;
int a = 3;
int b = 0;
while (a <= n / 2) {
b = n - a;
a += 2;
OUTPUT:
DATE PROGRAM
QUESTION NO: 6
Design a program to accept a day number (between 1 and 366), year (in 4 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 print the current date and future date by getting the corresponding values from the user.
PROGRAM:
import java.util.Scanner;
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;
if (leap) {
monthDays[1] = 29;
int i = 0;
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();
}
public static void main(String args[]) {
System.out.print("YEAR: ");
int n = in.nextInt();
return;
return;
nYear = nYear + 1;
System.out.println();
OUTPUT:
MIRROR MATRIX
QUESTION NUMBER : 7
Write a program in Java to enter natural numbers in a double dimensional array m x n (where m is the
number of rows and n is the number of columns). Display the new matrix in such a way that the new
matrix is the mirror image of the original matrix.
AIM: To display the mirror matrix of a matrix which is entered by the user.
PROGRAM:
import java.util.Scanner;
int m = in.nextInt();
int n = in.nextInt();
arr[i][j] = in.nextInt();
System.out.println("Input Array:");
System.out.print(arr[i][j] + "\t");
System.out.println();
newArr[i][n - 1 - j] = arr[i][j];
System.out.print(newArr[i][j] + "\t");
System.out.println();
}
OUTPUT:
SADDLE POINT
QUESTION NUMBER: 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 inout for a matrix of order mxn and print the
saddle point of it.
PROGRAM:
import java.util.*;
static int m;
m = in.nextInt();
System.out.println();
matrix[i][j] = in.nextInt();
}
System.out.println();
int k;
input();
int i,j;
System.out.println();
min = matrix[i][0];
min = matrix[i][j];
index[0][0] = i;
index[0][1] = j;
j = index[0][1];
max = matrix[0][j];
max = matrix[i][j];
index[1][0] = k;
index[1][1] = j;
if (min == max)
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. Example :
PROGRAM:
import java.util.*;
class Magic
int num = 1;
int r = 0;
int c = n / 2;
sq[r][c] = num;
num++;
int nr = (r - 1 + n) % n;
int nc = (c + 1) % n;
if (sq[nr][nc] != 0)
r = (r + 1) % n;
else
r = nr;
c = nc;
return sq;
System.out.print(mat[i][j] + "\t");
System.out.println();
}
}
int n = in.nextInt();
System.out.println("Magic Square:");
display(sq,n);
OUTPUT:
CIRCULAR MATRIX
QUESTION NUMBER: 10
Circular matrix: WAP to get the order of a square matrix ‘n’ and get the input for elements
and arrange it in a circular manner. Finally, print the circular matrix. Example:
PROGRAM:
import java.util.*;
class CIRCULAR{
int n = in.nextInt();
System.out.println("Circular Matrix:");
display(cir,n);
int num = 1;
int r = 0, c = 0;
int ro = 0, co = 1;
s[r][c] = num++;
if (c + co >= n || c + co < 0||r + ro >= n || r + ro < 0||s[r + ro][c + co] != 0) {
int t = co;
co = -ro;
ro =t;
r += ro;
c += co;
return s;
System.out.print(a[i][j] + "\t");
System.out.println();
}
OUTPUT:
TRANSPOSE MATRIX
QUESTION: 11
Given a matrix of size N X M, find the transpose of the matrix Transpose of a matrix is
obtained by changing rows to columns and columns to rows. In other words, transpose of
A[N][M] is obtained by changing A[i][j] to A[j][i].
PROGRAM:
import java.util.*;
class transpose
m = in.nextInt();
n = in.nextInt();
a= new int[m][n];
b=new int[m][n];
System.out.println();
a[i][j] = in.nextInt();
System.out.println();
b[i][j] = a[j][i];
System.out.print(mat[i][j] + "\t");
System.out.println();
}
}
input();
System.out.println();
System.out.println("Input matrix");
System.out.println();
display(a);
change();
System.out.println();
System.out.println("Transpose matrix");
System.out.println();
display(b);
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.
AIM: To get the order of the matrix and the matrix from the user and perform the above
tasks.
PROGRAM:
import java.util.*;
class SYMMETRIC {
static int m;
a= new int[m][m];
System.out.println();
a[i][j] = in.nextInt();
System.out.println();
int c = 0;
if(a[i][j]==a[j][i])
c++;
if(c==9)
else
}
static void display()
System.out.print(a[i][j] + "\t");
System.out.println();
int c1=0,c2=0,v=0;
c1+=a[i][i];
for(int j = m-1;j>=0;j--) {
c2+=a[v][j];
v++;
System.out.println();
input();
System.out.println();
System.out.println("Orignal matrix:");
System.out.println();
display();
System.out.println();
sym();
sd();
OUTPUT:
MATRIX MULTIPLICATION
QUESTION: 13
PROGRAM:
import java.util.*;
class MUL
System.out.println();
a1[i][j] = in.nextInt();
System.out.println();
return a1;
return p;
System.out.println();
int m1,n1,m2,n2,a[][],b[][];
m1 = in.nextInt();
n1 = in.nextInt();
m2 = in.nextInt();
n2 = in.nextInt();
if(n1!=m2){
System.exit(0);
System.out.println();
a = input(m1,n1,1);
b = input(m2,n2,2);
System.out.println("Matrix 1");
display(a,m1,n1);
System.out.println();
System.out.println("Matrix 2");
display(b,m2,n2);
System.out.println();
System.out.println("Product matrix");
display(p1,m1,n2);
OUTPUT:
TEXT FILE SORTING
QUESTION NUMBER: 14
WAP to accept 10 names and store it in a text file names names.txt. Sort the names
alphabetically and store it in another text file with the name order.txt.
AIM: To accept 10 names, store it in a text file, sort it and store it in another txt file.
PROGRAM:
import java.io.*;
class TXT{
try{
for(int i = 0;i<10;i++) {
pw.println(n1[i]);
pw.close();
catch(IOException e) {
System.err.println(e);
for(int i = 0;i<10;i++) {
names[i] = in.readLine();
write("namex.txt",names);
Arrays.sort(names);
write("order.txt",names);
System.out.println();
Output:
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 read product code from user and display the corresponding details of the product
PROGRAM:
import java.io.*;
import java.io.IOException;
class product
try{
boolean pf = false;
while(!EOF)
try{
int pc,up,q;
pc = ds.readInt();
up = ds.readInt();
q = ds.readInt();
if (pc == p) {
pf = true;
break;
catch(EOFException e1)
EOF = true;
if (!pf) {
catch(IOException e)
System.err.println(e);
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
findpro(Integer.parseInt(in.readLine()));
OUTPUT:
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?
PROGRAM:
import java.util.Scanner;
System.out.println("INVALID LENGTH");
return;
char ch = str.charAt(i);
if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
sb.append((char)(ch + 13));
else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
sb.append((char)(ch - 13));
}
else {
sb.append(ch);
System.out.println(cipher);
OUTPUT:
WORD COUNT
QUESTION NUMBER: 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
PROGRAM:
import java.util.*;
class COUNT
int c = 0;
for(int i = 0;i<y.length();i++)
if(y.charAt(i)==' ')
c++;
return c;
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)
t="";
System.out.println("ENTER A STRING");
String y = in.nextLine();
sep(y);
OUTPUT:
SENTENCE REARRANGE
QUESTION NUMBER: 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 get a sentence and sort the words in ascending order of their length.
PROGRAM:
import java.util.*;
strArr[i] = st.nextToken();
String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
} }
sb.append(strArr[i]);
sb.append(" ");
return sb.toString().trim();
System.out.println("Enter a sentence:");
System.out.println();
if (str.charAt(len - 1) != '.'
System.out.println("INVALID INPUT");
return;
System.out.println(sortedStr);
OUTPUT:
ADDER PROGRAM
Question: 19
A class Adder has been defined to add any two accepted time. [10] 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
Program:
import java.util.*;
public class adder
{
int a[];
adder()
{
a = new int [2];
}
void rt(String y)
{
Scanner in = new Scanner(System.in);
System.out.println("enter"+y+"hour");
a[0] = in.nextInt();
System.out.println("enter"+y+"minute");
a[1]=in.nextInt();
}
void addtime(adder x, adder y)
{
this.a[1] =x.a[1]+y.a[1];
this.a[0] =x.a[0]+y.a[0]+this.a[1]/60;
this.a[1]%=60;
}
void disptime()
{
System.out.println("hours="+ this.a[0]);
System.out.println("minutes="+ this.a[1]);
}
static void main()
{
adder ob = new adder();
ob.rt("first");
adder ob1 =new adder();
ob1.rt("second");
adder ob2 = new adder();
ob2.addtime(ob, ob1);
ob2.disptime();
}
}
OUTPUT:
COLLECTION PROGRAM
QUESTION NUMBER: 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[] len integer array
length of the array Members Function: Collection():default constructor Collection(int):
Parameterized constructor to assign the length Void inparri()to accept the array elements
Void arrange() sort the array elements of the object containing common elements in
ascending order using any sorting technique. Void display() display the array elements.
PROGRAM:
import java.util.*;
class Collection {
Collection(){
len=0;
Collection(int len){
this.len=len;
for(int i=0;i<len;i++){
arr[i] = in.nextInt();
void arrange(){
int min,temp;
for(int i=0;i<len-1;i++){
min=i;
for(int j=i+1;j<len;j++){
if(arr[j]<arr[min])
min = j;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
void display(){
for(int i=0;i<len;i++){
}}
input();
ob.arrange();
ob.display();
}
OUTPUT:
MIXER PROGRAM
QUESTION NUMBER: 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: int 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
PROGRAM:
import java.util.Scanner;
class Mixer {
int[] arr;
int n;
Mixer(int nn) {
n = nn;
void accept() {
duplicates:");
arr[0] = in.nextInt();
} 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();
m1.accept();
m2.accept();
Mixer mm = m1.mix(m2);
mm.display();
OUTPUT:
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 found
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 find an admission number from a list of 100 admission numbers using binary search.
Program:
import java.util.*;
class Admission {
Admission() {
Adno[i] = in.nextInt();
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 = in.nextInt();
int r = ob.bs(sn);
if (r == 1)
else
System.out.println();
Output:
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().
PROGRAM:
import java.util.*;
public class Revstr
{
String str;
String Revst;
Revstr()
{
str="";
Revst="";
}
void getStr()
{
Scanner in = new Scanner(System.in);
System.out.println("enter a string");
str=in.next();
}
void recReverse(int i)
{
if(i==0) return;
else {
Revst = Revst+str.charAt(i -1);
recReverse(i-1);
}
}
void check()
{
System.out.println("orginal string:"+ str);
recReverse(str.length());
System.out.println("reversed string:"+ Revst);
if(str.equals(Revst))
System.out.println("string"+ str+" is a palindrome");
else
System.out.println("string"+ str+" is not a palindrome");
}
}
OUTPUT:
CHANGE PROGRAM
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 convert the cases of the caracters in a string and return it.
PROGRAM:
import java.util.*;
Change()
str="";
newstr="";
len=0;
System.out.println("ENTER A Word");
str=in.next();
len=str.length();
ch=Character.toLowerCase(ch);
ch=Character.toUpperCase(ch);
return ch;
if(pos>-1) {
c=str.charAt(pos);
recchange(pos-1);
newstr+=caseconvert(c);
else
return;
}
static void display()
System.out.println("Original Word:"+str);
System.out.println("Changed Word:"+newstr);
ob1.inputword();
ob1.recchange(len-1);
ob1.display();
OUTPUT:
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
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();
System.out.println();
}
Output:
ARMSTRONG NUMBER
QUESTION NO: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
PROGRAM:
import java.util.Scanner;
class Arm {
int no;
int sum;
Arm(int num) {
no = num;
sum = 0;
if (exponent == 0) {
return 1;
}
void fnPerform() {
temp /= 10;
if (sum == no) {
} else {
ob.fnPerform();
}
OUTPUT:
Perimeter and Area (Using inheritance)
Question: 27
A superclass Perimeter has been defined to calculate the perimeter of a parallelogram. Define
a subclass Area to compute the area of the parallelogram by using the required data
members of the super class. The details are given below: Class name: Perimeter Data
members/instance variables; a: to store the length in decimal, b: to store the breadth in
decimal Member functions: Perimeter(...); parameterized constructor to assign values to data
members. double calculate(): calculate and return the perimeter of a parallelogram as 2
(length + breadth). void show(): to display the data members along with the perimeter of the
parallelogram Class name: Area Data members/instance variables: h: to store the height in
decimal. area: to store the area of the parallelogram. Member functions: Area1(...):
parameterized constructor to assign values to data members of both the classes void
doArea(): compute the area as (breadth height) void show(): display the data members of
both classes along with the area and perimeter of the parallelogram. Specify the class
Perimeter giving details of the constructor, double calculate() and void show(). Using the
concept of inheritance, specify the class Area giving details of the constructor, void do Area()
and void show().
Program:
class Perimeter {
double a;
double b;
a = length;
b = breadth;
double calculate() {
return 2 * (a + b);
void show() {
System.out.println("Length: " + a);
import java.util.*;
double h;
double area;
super(length, breadth);
h = height;
void doArea() {
area = b * h;
void show() {
super.show();
}
static void main(String[] args) {
ob.doArea();
ob.show();
Output:
Customer Details Program
Question: 28
A superclass Detail has been defined to store the details of a customer. Define a subclass Bill
to compute the monthly telephone charge of the customer as per the chart is given below:
Number of calls: 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. Page 82 of 107 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().
Program:
import java.util.Scanner;
class Detail {
String name;
String address;
String telno;
double rent;
name = n;
address = a;
telno = t;
rent = r;
void show() {
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();
Output:
BANK PROGRAM
QUESTION NUMBER: 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=pamt 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( ).
PROGRAM:
class Bank {
String name;
int accno;
double p;
name = n;
accno = acc;
p = principal;
void display() {
System.out.println("Name: " + name);
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();
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) {
System.out.println("Enter amount to be deposit");
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();
} }}
OUTPUT:
INSERTION SORT
QUESTION: 30
WAP in Java to accept n elements from user and sort it using Insertion sort method.
PROGRAM:
import java.util.*;
int n = array.length;
int i = j-1;
i--;
array[i+1] = key;
int n = in.nextInt();
a[i]=in.nextInt();
for(int i =0;i<n;i++){
System.out.print(a[i]+" ");
System.out.println();
insertionSort(a);
for(int i =0;i<n;i++){
System.out.print(a[i]+" ");
OUTPUT:
REGISTER PROGRAM
QUESTIONJ NO: 31
Register is an entity which can hold a aximum 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: Class name: Register Data members/instance variables: stud[]: array to store the
names of the students. cap: stores the maximum capacity of the array. top: to point the index
of the top end. Member functions: Register(int max): constructor to initialize the data
members cap = max. top = -1 and create the string array
PROGRAM:
import java.util.*;
class Register {
String stud[];
int cap;
int top;
Register(int max) {
cap = max;
top = -1;
boolean isEmpty() {
boolean isFull() {
}
void push(String name) {
if (isFull()) {
return;
stud[++top] = name;
String pop() {
if (isEmpty()) {
return null;
String rn = stud[top];
stud[top] = null;
top--;
return rn;
void display()
}
static void main() {
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;
OUTPUT:
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.
PROGRAM:
import java.util.*;
class QU {
int q[];
int front;
int rear;
int maxSize;
QU(int size) {
maxSize = size;
q = new int[maxSize];
front = -1;
rear = -1;
boolean isEmpty() {
boolean isFull() {
return rear == maxSize - 1;
if (isFull()) {
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.println();
QU ob = new QU(5);
boolean v = true;
while (v) {
System.out.println("Enter 4 to exit");
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;
OUTPUT:
LINEAR QUEUE
QUESTION NUMBER: 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
PROGRAM:
import java.util.*;
class LQ {
int queue[];
int front;
int rear;
int maxSize;
LQ(int size) {
maxSize = size;
front = -1;
rear = -1;
boolean isEmpty() {
boolean isFull() {
return;
if (isEmpty()) {
front = 0;
queue[++rear] = item;
int dequeue() {
if (isEmpty()) {
return -1;
if (front == rear) {
} else {
front++;
return item;
void display() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return;
System.out.println();
while (true) {
System.out.println("\nEnter 1 to enqueue");
System.out.println("Enter 2 to dequeue");
System.out.println("Enter 3 to display");
System.out.println("Enter 6 to exit");
int ch = in.nextInt();
switch (ch) {
case 1:
ob.enqueue(enqElement);
break;
case 2:
if (deqElement != -1) {
break;
case 3:
ob.display();
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println("Exiting...");
System.exit(0);
default:
}
OUTPUT:
EXCEPTION HANDLING
QUESTION: 34
Write a program in Java to explain the importance of exception handling. (Explicit)
AIM: To see the importance of exception handling while dividing a number with 0
PROGRAM:
import java.util.*;
class EXH{
int n = in.nextInt();
int d = in.nextInt();
try {
} catch (ArithmeticException e) {
}}}
OUTPUT:
INFIX-POSTFIX USING STACK
QUESTION: 35
PROGRAM:
import java.util.*;
class INP
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];
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;
toPostfix(infix));
OUTPUT: