CS Proj-1
CS Proj-1
CS Proj-1
A class Octal has been defined to convert a decimal number into its
equivalent octal number. Some of the members of the class are given below:
Class name : Octal
Data members
n : stores the decimal number
oct : stores the equivalent octal number
Member functions :
Octal () : constructor to initialize the data members to 0
voidgetnum(intnn) : assigns nn to n
intdeci_oct() : calculates the octal equivalent of n and stores it in oct.
void show() : displays the decimal number n calls the functiondeci_oct() and
displays its octal equivalent
Specify the class Octal, giving details of the constructor( ),void getnum(int),
void deci_oct( ) and void show( ). From the main() function invoke the above
methods.
ALGORITHM
1. Start
2. Print “Enter decimal number to find octal value: “
3. Store entered number in int nn
4. Initialize int n=nn
5. Initialize int rem to store remainder
6. Create array char octalchars[]={'0','1','2','3','4','5','6','7'}
7. Repeat Steps 8 to 10 while n>8
8. rem=n%8;
9. octal=octalchars[rem]+octal;
10. n=n/8;
11. octal=octalchars[n]+octal if n>8
12. Convert octal into int and store it in int b
13. Print “Decimal number: “ along with nn
14. Print “Octal Number: “ along with b
15. Stop
Page 1 of 123
CODE:-
import java.util.*;
class P1_Octal
{
int n,oct;
P1_Octal()
{
n=0;
oct=0;
}
void getnum(int nn)
{
n=nn;
}
int deci_oct()
{
int rem; //declaring variable to store remainder
String octal=""; //declaring variable to store octal
char octalchars[]={'0','1','2','3','4','5','6','7'}; //declaring array of octal numbers
//writing logic of n to octal conversion
while(n>=8)
{
rem=n%8;
octal=octalchars[rem]+octal;
n=n/8;
}
if(n<8 )
octal=octalchars[n]+octal;
oct=Integer.parseInt(octal);
Page 2 of 123
return oct;
}
void show(int nn)
{
System.out.println("decimal number: "+nn);
System.out.println("Octal equivalent is "+ oct);
}
public static void main(String Args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter decimal number to find its octal value");
int nn=sc.nextInt();
P1_Octal ob= new P1_Octal();
ob.getnum(nn);
int b=ob.deci_oct();
ob.show(nn);
}
}
OUTPUT:
1) Enter decimal number to find its octal value
7
decimal number: 7
Octal equivalent is 7
Page 3 of 123
Program 2
A Smith number is a composite number, the sum of whose digits is the sum
of the digits of its prime factor obtained as a result of prime factorization
(excluding 1). The first few such numbers are 4, 22, 27, 58, 85, 94, 121......
Example: 1. 666 Prime factors are 2, 3, 3, and 37
Sum of the digits are (6+6+6) = 18
Sum of the digits of the factors (2+3+3+(3+7)) = 18
2. 4937775 Prime factors are 3, 5, 5, 65837
Sum of the digits are (4+9+3+7+7+7+5) = 42
Sum of the digits of the factors (3+5+5+(6+5+8+3+7)) = 42
Write a program to input a number and display whether the number is Smith
number or not.
Sample data:
Input
94
Output
SMITH Number
Input 102
Output
NOT SMITH Number
Input 666
Output
SMITH Number
ALGORITHM
1. Start
2. Print “N= “
3. Store the entered integer in int n
Page 4 of 123
4. Repeat Steps 5 to 11 while num>1
5. Repeat Steps 6 to 10 while (num % p==0)
6. Initialize int s=0
7. Repeat Steps 8 to 9 while(num!=0)
8. s += n % 10;
9. n /= 10;
10. SumOfFactors + = s
11. p++
12. Repeat Steps 6 to 9
13. Print “SMITH NUMBER” if (SumOfFactors= s)
14. Else print “ Not A Smith Number”
15. Stop
CODE:-
import java.util.Scanner;
class P2_Smith
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("N = "); //Enters the Number
int n = Integer.parseInt(in.nextLine());
int num = n, p = 2, sumOfFactors = 0;
while(num > 1)
{
while(num % p == 0)
{
sumOfFactors += sumOfDigits(p); //Finds Sum of digits of factors
num /= p;
}
p++;
}
if(sumOfDigits(n) == sumOfFactors)
System.out.println(" SMITH NUMBER");
Page 5 of 123
else
System.out.println(" NOT SMITH NUMBER");
}
public static int sumOfDigits(int z)
{
int s = 0;
while(z!= 0) //Calculates the Sum of the Digits
{
s += z % 10;
z/= 10;
}
return s;
}
}
OUTPUT
1. N = 22
SMITH NUMBER
2. N = 69
NOT SMITH NUMBER
3. N = 666
SMITH NUMBER
Page 6 of 123
Program 3:
Design a class Perfect to check if a given number is a perfect number or not.
[A number is said to be perfect if sum of the factors of the number excluding
itself is equal to the original number ]
Example : 6 = 1 + 2 + 3 (where 1, 2 and 3 are factors of 6, excluding itself)
Some of the members of the class are given below:
Class name : Perfect Data
members/instance variables:
num : to store the number
Methods/Member functions:
Perfect (int nn) : parameterized constructor to initialize the data member.
int sum_of_factors(int i) : returns the sum of the factors of the number(num),
excluding itself, using recursive technique
void check() : checks whether the given number is perfect by invoking the
function sum_of_factors() and displays the result with an appropriate
message.
Specify the class Perfect giving details of the constructor (), int
sum_of_factors(int) and void check (). Define a main() function to create an
object and call the functions accordingly to enable the task.
ALGORITHM
1. Start
2. Print “Enter a number to find if its Perfect or not”
3. Store entered number in int nn
4. num=n
5. int i=num-1 ,sum=0
6. if(num <= 1)
sum= -1;
7. if(i == num)
Repeat Steps 6 to 10 for (i - 1);
8. else if(i == 1)
sum=1;
9. else if(num % i == 0)
sum+ = i + [Repeat Steps 6 to 10 for (i - 1)]
10. else
Page 7 of 123
sum= Repeat Steps 6 to 10 for (i - 1);
11. Print(“Perfect Number”) if (sum=num)
12. Else Print(“Not a perfect Number”)
13. Stop
CODE
import java.util.*;
class P3_Perfect
{
int num;
P3_Perfect(int nn)//stores number
{
num=nn;
}
public int sumOfFactors(int i) //Finds sum of factors using recursion
{
if(num <= 1)
return -1;
if(i == num)
return sumOfFactors(i - 1);
else if(i == 1)
return 1;
else if(num % i == 0)
return i + sumOfFactors(i - 1);
else
return sumOfFactors(i - 1);
}
void check()
{
int i=num-1,sum=0;
sum=sumOfFactors(i);
Page 8 of 123
if(sum==num) //If sum of Factors is equal to the number
System.out.println("Perfect Number");
else
System.out.println("Not a Perfect Number");
}
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter a number to find if its Perfect or not");
int nn=sc.nextInt();
P3_Perfect ob =new P3_Perfect(nn);
ob.check();
}
}
OUTPUT
1. Enter a number to find if its Perfect or not
6
Perfect Number
2. Enter a number to find if its Perfect or not
16
Not a Perfect Number
3. Enter a number to find if its Perfect or not
28
Perfect Number
Page 9 of 123
Program 4:
A positive whole number ‘n’ that has ‘d’ number of digits is squared and split
into two pieces, a righthand piece that has ‘d’ digits and a left-hand piece
that has remaining ‘d’ or ‘d-1’ digits. If the sum of the two pieces is equal to
the number, then ‘n’ is a Kaprekar number. The first few Kaprekar numbers
are: 9, 45, 297 …….. Example 1:
9
9^2 = 81,
right-hand piece of 81 = 1 and left hand piece of 81 = 8
Sum = 1 + 8 = 9, i.e. equal to the number.
Example 2: 45
45^2 = 2025, right-hand piece of 2025 = 25 and left hand piece of 2025 = 20
Sum = 25 + 20 = 45, i.e. equal to the number.
Example 3: 297
297^2 = 88209, right-hand piece of 88209 = 209 and left hand piece of 88209
= 88
Sum = 209 + 88 = 297, i.e. equal to the number.
Given the two positive integers p and q, where p < q, write a program to
determine how many Kaprekar numbers are there in the range between p
and q (both inclusive) and output them. The input contains two positive
integers’ p and q. Assume p < 5000 and q < 5000.
You are to output the number of Kaprekar numbers in the specified range
along with their values in the format specified below:
SAMPLE DATA:
INPUT:
p = 1 q = 1000
OUTPUT: THE KAPREKAR NUMBERS ARE:- 1, 9, 45, 55, 99, 297, 703, 999
FREQUENCY OF KAPREKAR NUMBERS IS: 8
Page 10 of 123
ALGORITHM
1. Start
2. Print (“p= “)
3. Store entered number in int p
4. Print(“q =”)
5. Store entered number in int q
6. if(p >= q || p >= 5000 || q >= 5000)
{
7. Print(“Invalid Range”)
8. Exit from program
}
9. Int count=0
10. Print(“THE KAPREKAR NUMBERS ARE: “)
11. Repeat Steps 12 to 36 for(int i = p; i <= q; i++)
12. int left = 0;
13. int right = 0;
14. String l = "";
15. String r = "";
16. int count=0
17. if(i==0) int digits= 1
18. else
{
19. Repeat Step 20 for(int i = n; i != 0; i /= 10)
20. count++
21. int digits =count
}
22. int sq = i * i;
23. Repeat Steps 24 to 26 for(int j = 1; j <= digits; j++)
24. int d = sq % 10;
25. r = d + r
26. sq /= 10
27. l = l + sq
28. left = Integer.parseInt(l)
29. right = Integer.parseInt(r)
30. int sum = left + right
31. if(i == sum)
{
32. count++;
33. if(count == 1)
34. print(i);
35. else
36. print(", " + i);
}
Page 11 of 123
37. Print(“ FREQUENCY OF KAPREKAR NUMBERS IS: “+ count)
38. Stop
CODE:-
import java.util.Scanner;
class Kaprekar
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("p = ");
int p = Integer.parseInt(in.nextLine());
System.out.print("q = ");
int q = Integer.parseInt(in.nextLine());
if(p >= q || p >= 5000 || q >= 5000)
{
System.out.println("INVALID RANGE!");
return;
}
int count = 0;
System.out.println("THE KAPREKAR NUMBERS ARE:");
for(int i = p; i <= q; i++)
{
int left = 0;
int right = 0;
String l = "";
String r = "";
int digits = countDigits(i);
int sq = i * i;
for(int j = 1; j <= digits; j++)
{
int d = sq % 10; //Stores the left and Right part as Strings
r = d + r;;
sq /= 10;
}
l = l + sq;
left = Integer.parseInt(l); //Converts the 2 parts into Integer
right = Integer.parseInt(r);
int sum = left + right;
if(i == sum)
{
count++;
Page 12 of 123
if(count == 1)
System.out.print(i);
else
System.out.print(", " + i);
}
}
System.out.println("\nFREQUENCY of KAPREKAR NUMBERS IS: " + count);
}
public static int countDigits(int n)
{
int count = 0;
if(n == 0)
return 1;
for(int i = n; i != 0; i /= 10)
count++;
return count;
}
OUTPUT
1. p = 100
q = 1000
THE KAPREKAR NUMBERS ARE:
297, 703, 999
FREQUENCY of KAPREKAR NUMBERS IS: 3
2. p = 1
q = 1000
THE KAPREKAR NUMBERS ARE:
1, 9, 45, 55, 99, 297, 703, 999
FREQUENCY of KAPREKAR NUMBERS IS: 8
3. p = 20
q = 10
INVALID RANGE!
Page 13 of 123
Program 5:
A number is said to Bouncy number if the digits of the number are unsorted.
For example, 22344 - It is not a Bouncy number because the digits are sorted
in ascending order.
774410 - It is not a Bouncy number because the digits are sorted in
descending order.
155349 - It is a Bouncy number because the digits are unsorted.
A number below 100 can never be a Bouncy number. Write a program in java
to accept 2 numbers and display all the Bouncy numbers within that range
ALGORITHM
1. Start
2. Initialize Boolean asc and desc as true
3. Print “Enter Range”
4. Store the minimum and maximum in int p and int q
5. Print “ Bouncy Numbers are: “
6. Repeat steps 7 to 20 for(int n=p;n<=q;n++)
7. int len =String.valueOf(n).length();
8. int j = 0;
9. int i = n;
10. int a[] = new int[len];
11. Repeat Steps 11 to 12 while( i != 0)
12. a[j++] = i % 10;
13. i /= 10;
14. Repeat Steps 15 for( i = 0; i < a.length - 1; i++)
15. If if(a[i] > a[i + 1])
asc = false;
break;
16. Repeat Steps 17 for for( i = 0; i < a.length - 1; i++)
17. if(a[i] < a[i + 1])
{
desc = false;
break;
}
18. Print n if(!asc && !desc)
19. asc=true
20. desc = true
Page 14 of 123
21. Stop
CODE
import java.util.Scanner;
class P5_Bouncy
{
int p,q;
boolean asc = true;
boolean desc = true;
void input()
{
Scanner in = new Scanner(System.in); //Accepts Range from User
System.out.println("Enter Range ");
p= in.nextInt();
q=in.nextInt();
System.out.print("\n Bouncy numbers are: \n");
}
void bounce()
{
for(int n=p;n<=q;n++)
{
int len =String.valueOf(n).length(); //Converts number to String
int j = 0;
int i = n;
int a[] = new int[len]; //Array to store all digits
while(i != 0)
{
a[j++] = i % 10;
Page 15 of 123
i /= 10;
}
for( i = 0; i < a.length - 1; i++)
{
if(a[i] > a[i + 1])
{
asc = false;
break;
}
}
for( i = 0; i < a.length - 1; i++)
{
if(a[i] < a[i + 1])
{
desc = false;
break;
}
}
if(!asc && !desc)
System.out.print(n+”\t”);
asc = true;
desc = true;
}
}
public static void main(String[] args)
{
P5_Bouncy ob = new P5_Bouncy();
ob.input();
ob.bounce();
Page 16 of 123
}
OUTPUT
1. Enter Range
100
110
Bouncy numbers are:
101 102 103 104 105 106 107 108 109
2. Enter Range
1
102
Bouncy numbers are:
101 102
Page 17 of 123
Program 6:
A company manufactures packing cartons in four sizes, i.e. cartons to
accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to
accept the number of boxes to be packed (N) by the user (maximum up to
1000 boxes) and display the break-up of the cartons used in descending order
of capacity (i.e. preference should be given to the highest capacity available,
and if boxes left are less than 6, an extra carton of capacity 6 should be used.)
Test your program with the following data and some random data:
Example 1
INPUT: N = 726
OUTPUT:
48 * 15 = 720
6*1=6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Example 2
INPUT: N = 140
OUTPUT: 48 * 2 = 96
24 * 1 = 24
12 * 1 = 12
6*1=6
Remaining boxes = 2 * 1 = 2
Total number of boxes = 140
Total number of cartons = 6
Example 3
INPUT: N = 4296
OUTPUT: INVALID INPUT
Page 18 of 123
ALGORITHM
1. Start
2. Print “Enter Number of Packages”
3. Store the entered number in int N
4. Print “Excess ordered “ and stop the program if (N>1000)
5. int rempak =N
6. p48 = N/ 48;
7. N %= 48;
8. p24 = N / 24;
9. N %= 24;
10. p12 = N/ 12;
11. N %= 12;
12. p6 = N / 6;
13. N%= 6;
14. P6++ if(N>6)
15. Print (“ 48 x “+ p48 +”=”+ p48*48) if( >0)
16. Print (“24 x “+ p24 +”=”+ p24*24 “) if( >0)
17. Print (“12 x “+ p12 +”=”+ p12*12 “) if( >0)
18. Print( “6 x “+ p6 +”=”+ p6*6 “) if( >0)
19. Print(“ Remaining boxes : “+ N)
20. Print(“Total Number of boxes = “+rempak)
21. Print(”Total Number of cartons: “+(p6+p12+p24+p48))
22. Stop
CODE
import java.util.*;
class P6_packets
{
int N;
int p6 = 0;
int p12 = 0;
int p24 = 0;
int p48 = 0; //P1 has 6 packs,p2 has 12,p3 has 24 and p4 has 48
void placeorder()//enters value
{
Page 19 of 123
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of packages");
N=sc.nextInt();
if(N>1000)
{
System.out.println("Excess ordered");
System.exit(0);
}
}
void packorder() //number of packs needed of each size
{
int rempak=N;
p48 = N/ 48;
N %= 48;
p24 = N / 24;
N %= 24;
p12 = N/ 12;
N %= 12;
p6 = N / 6;
N%= 6;
if(N > 0)
p6++;
if(p48 > 0)
System.out.println("48 x " + p48 +"="+ p48*48);
if(p24 > 0)
System.out.println("24 x " + p24 +"="+ p24*24);
if(p12 > 0)
System.out.println("12 x " + p12 +"="+ p12*12);
if(p6 > 0)
Page 20 of 123
System.out.println("6 x " + p6+"="+ p6*6);
System.out.println("Remaining boxes: "+ N);
System.out.println("Total number of boxes = "+rempak);
System.out.println("Total number of cartons: "+(p6+p12+p24+p48));
}
public static void main(String args[])
{
P6_packets ob=new P6_packets();
ob.placeorder();
ob.packorder();
}
}
OUTPUT
1. Enter number of packages
726
48 x 15=720
6 x 1=6
Remaining boxes: 0
Total number of boxes = 726
Total number of cartons: 16
2. Enter number of packages
140
48 x 2=96
24 x 1=24
12 x 1=12
6 x 2=12
Remaining boxes: 2
Total number of boxes = 140
Total number of cartons: 6
Page 21 of 123
3. Enter number of packages
4296
Excess ordered
Page 22 of 123
Program 7:
Strontio numbers are those four digits numbers when multiplied by 2
give the same digit at the hundreds and tens place. Remember that the input
number must be a four-digit number.
Strontio Number Example
1386*2=2772,we observe that at tens and hundreds place digits are
the same. Hence, 1386 is a strontio number.
1221*2=2442, digits at tens and hundreds place are the same. Hence,
1221 is a strontio number.
Some other strontio numbers are 1111, 2222, 3333, 4444, 5555, 6666,
7777, 8888, 9999, 1001, 2002, 3003, etc. WAP in java to display all 4-digit
Strontio number along with the frequency.
ALGORITHM
1. Start
2. int p =n*2
3. String s=String.valueOf(p);
4. int len=s.length();
5. if(s.charAt(len - 2) == s.charAt(len - 3))
{
6. Print(n)
7. c++
}
8. Print("Number of strontio numbers:- "+c)
9. Stop
CODE
import java.util.Scanner;
class P7_Strontio
{
public static void main(String[] args)
{
int c=0;
for(int i=1000;i<=9999;i++)
Page 23 of 123
{
int p = i * 2;
String s = String.valueOf(p);
int len = s.length();
if(s.charAt(len - 2) == s.charAt(len - 3))
{
System.out.println(i);
c++;}}
System.out.println("Number of Strontio numbers: "+c);
}}
OUTPUT
1000
1001
1002
1003
1004
1055
1056
1057
1058…
… 9942
9943
9944
9995
9996
9997
9998
9999
Number of Strontio numbers: 900
Page 24 of 123
Program 8:
Write a program to accept 2 dates in the string format dd/mm/yyyy
and find the difference in days between the 2 dates. The program should
include the part for validating the inputs namely the date and the day on 1st
January of that year. Example:
Input:
Date 1 : 20/12/2012
Date 2 : 11/02/2013
Output:
Difference = 54 days
ALGORITHM
1. Start
2. int d1[] = new int[3]
3. int d2[] = new int[3]
4. Print(“Enter First Date: ”)
5. Input in d1[0]
6. Print(“Enter Month: ”)
7. Input in d1[1]
8. Print(“Enter Year”)
9. Input in d1[2]
10. Print(“Enter Second Date: ”)
11. Input in d2[0]
12. Print(“Enter Month: ”)
13. Input in d2[1]
14. Print(“Enter Year”)
15. Input in d2[2]
16. int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
17. int n1 = d1[2] * 365 + d1[0]
18. int n2 = d2[2] * 365 + d2[0]
19. n1 += monthDays[i] for (int i = 0; i < d1[1] - 1; i++)
20. n2 += monthDays[i] for (int i = 0; i < d2[1] - 1; i++)
21. int y = d1[1] <= 2 ? d1[2] - 1 : d1[2]
22. n1 += y / 4 - y / 100 + y / 400
23. y = d2[1] <= 2 ? d2[2] - 1 : d2[2]
24. n2 += y / 4 - y / 100 + y / 400
25. int diff = Math.abs(n2 - n1)+1
26. Println("Difference = " + diff + " days")
27. Stop
Page 25 of 123
CODE
import java.io.*;
public class Program8
{
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
int d1[] = new int[3];
int d2[] = new int[3];
System.out.println("Enter First Date: ");
System.out.print("Enter Day: ");
d1[0] = Integer.parseInt(in.readLine());
System.out.print("Enter Month: ");
d1[1] = Integer.parseInt(in.readLine());
System.out.print("Enter Year: ");
d1[2] = Integer.parseInt(in.readLine());
System.out.println("Enter Second Date: "); // to enter the details of the second
date
System.out.print("Enter Day: ");
d2[0] = Integer.parseInt(in.readLine());
System.out.print("Enter Month: ");
d2[1] = Integer.parseInt(in.readLine());
System.out.print("Enter Year: ");
d2[2] = Integer.parseInt(in.readLine());
int monthDays[] = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31}; // We store the end of month days in an
array
int n1 = d1[2] * 365 + d1[0];
int n2 = d2[2] * 365 + d2[0];
for (int i = 0; i < d1[1] - 1; i++)
Page 26 of 123
{
n1 += monthDays[i]; // to add to the month days
}
for (int i = 0; i < d2[1] - 1; i++)
{
n2 += monthDays[i];
}
int y = d1[1] <= 2 ? d1[2] - 1 : d1[2];
n1 += y / 4 - y / 100 + y / 400;
y = d2[1] <= 2 ? d2[2] - 1 : d2[2];
n2 += y / 4 - y / 100 + y / 400;
int diff = Math.abs(n2 - n1)+1; // to find the difference between the two dates
System.out.println("Difference = " + diff + " days"); // to print the difference
between the days
}
}
Page 27 of 123
OUTPUT
1. Enter First Date:
Enter Day: 20
Enter Month: 12
Enter Year: 2012
Enter Second Date:
Enter Day: 11
Enter Month: 02
Enter Year: 2013
Difference = 54 days
Page 28 of 123
Program 9.
Write a Program in Java to input a number in Decimal number system and
convert it into its equivalent number in the Hexadecimal number system.
Note: Hexadecimal Number system is a number system which can represent
a number in any other number system in terms of digits ranging from 0 to 9
and then A – F only. This number system consists of only sixteen basic digits
i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. Here 10 is represented as A, 11
as B and so on till 15 which is represented as F.
For Example: 47 in the Decimal number system can be represented as 2F in
the Hexadecimal number system.
Example:
Enter a decimal number : 47
Output = 2F
ALGORITHM
1. Start
2. Print(“Enter decimal to convert it into hexadecimal”)
3. Input value for decimal number and store it in variable ‘dec’
4. Initialize an array char ‘hexchars’ as {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}
5. Initialize String hex=””
6. Repeat Steps 7 to 9 while(dec>0)
7. rem=decimal%16
8. hex=hexchars[rem]+hex
9. dec=dec/16
10. Print("Hexadecimal of "+ dec+" is: "+hex)
11. Stop
CODE
import java.util.*;
class P9_Hex
{
static String toHex(int decimal)
{
int rem;
String hex="";
Page 29 of 123
char hexchars[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(decimal>0)
{
rem=decimal%16;
hex=hexchars[rem]+hex;
decimal=decimal/16;
}
return hex;
}
static int input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter decimal to convert it into hexadecimal");
return(sc.nextInt());
}
public static void main(String args[]) {
P9_Hex ob = new P9_Hex();
int dec=input();
System.out.println("Hexadecimal of "+ dec+" is: "+ toHex(dec));
}}
OUTPUT
1. Enter decimal to convert it into hexadecimal
47
Hexadecimal of 47 is: 2F
2. Enter decimal to convert it into hexadecimal
8
Hexadecimal of 8 is: 8
3. Enter decimal to convert it into hexadecimal
69420
Hexadecimal of 69420 is: 10F2C
Page 30 of 123
Program 10.
Given a time in numbers we can convert it into words.
Example:
5: 00 —— five o’clock
5: 10 —— ten minutes past five
5: 15 —— quarter past five
5: 30 —— half past five
5: 40 —— twenty minutes to six
5: 45 —— quarter to six
5: 47 —— thirteen minutes to six
Write a program which first inputs two integers, the first between 1 and 12
(both inclusive) and second between 0 and 59 (both inclusive) and then
prints out the time they represent, in words. Your program should follow the
format of the examples above.
ALGORITHM
1. Start
2. Print (“Enter Hours:”)
3. Input value for Hours and store in variable int ‘h’
4. Print (“Enter Minutess:”)
5. Input value for Hours and store in variable int ‘m’
6. if((h>=1 && h<=12) && (m>=0 && m<=59))
{
7. String plu,a
8. Create a String array having 1 to 30 in words
9. If(m==1 || m==59) plu=”Minute”
10. Else plu=”Minutes”
11. a=word[1] if(h==12)
12. Else a=words[h+1]
13. Print ("Output : "+h+":"+m+" ----- ")
14. if(m==0)
System.out.println(words[h]+" O' clock");
15. else if(m==15)
System.out.println("Quarter past "+words[h]);
16. else if(m==30)
System.out.println("Half past "+words[h])
Page 31 of 123
17. else if(m==45)
System.out.println("Quarter to "+a)
18. else if(m<30)
System.out.println(words[m]+" "+plu+" past "+words[h])
19. else
System.out.println(words[60-m]+" "+plu+" to "+a)
}
20. Print ("Invalid Input !")
21. Stop
CODE
import java.io.*;
import java.util.Scanner;
public class TimeInWords
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Hours : ");
int h = sc.nextInt();
System.out.print("Enter Minutes : ");
int m = sc.nextInt();
if((h>=1 && h<=12) && (m>=0 && m<=59))
{
String words[]={"", "One", "Two", "Three", "Four", "Five", "Six","Seven", "Eight",
"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eig
hteen"," Nineteen","Twenty","Twenty one", "Twenty two", "Twenty three", "Twenty four",
"Twenty five","Twenty six","Twenty seven","Twenty eight", "Twenty nine"};
/* The below code is for finding whether to print the word 'minute' or 'minutes' */
String plu, a;
if(m == 1 || m == 59)
plu = "Minute";
else
Page 32 of 123
plu = "Minutes";
if(h==12)
a = words[1]; //storing 'one' when hour is 12
else
a = words[h+1]; //if hour is not 12, then storing in words, an hour ahead of given hour
/* The below code checks minutes and accordingly prints the time in words using array. */
System.out.print("Output : "+h+":"+m+" ----- "); //printing the given time in numbers
if(m==0)
System.out.println(words[h]+" O' clock");
else if(m==15)
System.out.println("Quarter past "+words[h]);
else if(m==30)
System.out.println("Half past "+words[h]);
else if(m==45)
System.out.println("Quarter to "+a);
else if(m<30) // condition for minutes between 1-29
System.out.println(words[m]+" "+plu+" past "+words[h]);
else // condition for minutes between 31-59
System.out.println(words[60-m]+" "+plu+" to "+a);
} //end of outer if
else
System.out.println("Invalid Input !");
}
}
Page 33 of 123
OUTPUT
1. Enter Hours : 12
Enter Minutes : 59
Output : 12:59 ----- One Minute to One
2. Enter Hours : 6
Enter Minutes : 1
Output : 6:1 ----- One Minute past Six
3. Enter Hours : 13
Enter Minutes : 69
Invalid Input !
Page 34 of 123
Program 11.
Design a class Sort which enables a word to be arranged in alphabetical
order.
The details of the members of the class are given below:
Class name : Sort
Data members/instance variables:
str : stores a word
len : to store the length of the word
Methods/Member functions:
Sort( ) : default constructor
voidreadword( ) : to accept the word
void arrange ( ) : to arrange the word in alphabetical order using any
standard sorting technique.
void display( ) : displays the original word along with the sorted word
Specify the class Sort giving details of the constructor, void readword( ), void
arrange( ) and void display( ). Define the main( ) function to create an object
and call the functions accordingly to enable the task.
ALGORITHM
1. Start
2. Print(“enter word to arrange it in alphabetical order”)
3. Input the Word in variable String str
4. int len=str.length()
5. char[] alph=new char[len];
6. repeat Step 7 for i=1;i<len;i++
7. alph[i]=str.charAt(i)
8. Repeat Step 9 to 13 for i=0;i<len;i++
9. Repeat Step 10 to 13 for int j=0;j<len;j++
10. if((int)(Character.toLowerCase(alph[j])) > (int)(Character.toLowerCase(alph[i])))
{
11. char t=alph[j];
12. alph[j]=alph[i];
13. alph[i]=t;
Page 35 of 123
}
14. Print ("Entered word: "+str)
15. Print ("Alphabetically Arranged word : ")
16. Print(alph[i]) for (i=0;i<len;i++)
17. Stop
CODE
import java.util.*;
class P11_Sort
String str;
int len,i;
void readword()
str=sc.next().trim();
len=str.length();
void arrange()
for(i=1;i<len;i++)
alph[i]=str.charAt(i);
for(i=0;i<len;i++)
char t=alph[j];
alph[j]=alph[i];
Page 36 of 123
alph[i]=t;
void display()
for(i=0;i<len;i++)
System.out.print(alph[i]);
ob.readword();
ob.arrange();
ob.display();
OUTPUT
abcdeeefghhijklmnoooopqrrstuuvwxyz
aaccer
Page 37 of 123
Program 12.
Write a program to declare a square matrix A[][] of order MXM where M is
an positive integer and represents row and column. M should be greater than
2 and less than 10. Accept the value of M from user. Display an appropriate
message for invalid input.
Perform the following task:
a) Display the original matrix
b) Check if the given matrix is symmetric or not.
If the element of the ithrow and jthcolumn is same as element of the jth row
and ith column,.
c) Find the sum of the left and right diagonal of the matrix and display them
Example 1:
INPUT: M=3
123
245
356
OUTPUT:
Original matrix
123
245
356
The given matrix is symmetric
Sum of the left diagonal=11
Sum of the right diagonal=10
Example 2:
INPUT: M=4
7892
4563
Page 38 of 123
8531
7642
OUTPUT:
Original matrix:
7892
4563
8531
7642
The given matrix is not symmetric
Sum of the left diagonal=17
Sum of the right diagonal=20
Example 3:
INPUT: M=12
OUTPUT:
Matrix size is out of range
ALGORITHM
1. Start
2. Print(“Enter order of matrix between 2 and 10 ")
3. Input the value in variable int m
4. Check if(m<2||m>10)
{
5. Print("Enter between 2 and 10")
6. Exit the Program
}
7. int arr[][]=new int[m][m];
8. Print("Fill the matrix")
9. Repeat Step 9 for (i=0;i<m;i++)
10. Repeat Step 10 for (j=0;j<m;j++)
11. Store value in arr[i][j]
12. Repeat Step 13 for(i=0;i<m;i++)
13. sumrd=sumrd+arr[i][i]
Page 39 of 123
14. j=0
15. Repeat Step 16 to 17 for(i=m-1;i>=0;i--)
16. sumld=sumld+arr[i][j];
17. j++;
18. Repeat Step 19 for(int i=0;i<m;i++)
19. Repeat Step 20 for(int j=0;j<m;j++)
20. Boolean symm =false if(arr[i][j]!=arr[j][i])
21. else Boolean symm =true
22. Print("Original Matrix : ")
23. Repeat Steps 24 to 26 for(i=0;i<m;i++)
24. Repeat Steps 25 for(j=0;j<m;j++)
25. System.out.print(arr[i][j]+"\t");
26. System.out.println();
27. Print("The given matrix is symmetrical") if( symm==true)
28. Else Print ("The given matrix is not symmetrical")
29. Print ("Sum of left diagonal is : "+ sumld)
30. Print("Sum of Right diagonal is : "+ sumrd)
31. Stop
CODE
import java.util.*;
import java.util.Arrays;
class P12_sqmat
{
public static void main(String args[])
{
int m,i,j,sumrd=0,sumld=0;
//inputs
Scanner sc=new Scanner(System.in);
System.out.println("Enter order of matrix between 2 and 10");
m=sc.nextInt();
if(m<2||m>10)
{
System.out.println("Enter between 2 and 10");
System.exit(0);
}
int arr[][]=new int[m][m];
//fills matrix
System.out.println("Fill the matrix");
for(i=0;i<m;i++)
for(j=0;j<m;j++)
arr[i][j]=sc.nextInt();
Page 40 of 123
//Diagonal sum
for(i=0;i<m;i++)
sumrd=sumrd+arr[i][i];
j=0;
for(i=m-1;i>=0;i--)
{
sumld=sumld+arr[i][j];
j++;
}
P12_sqmat ob=new P12_sqmat();
boolean symm=isymmatrix(m, arr);
//displays
System.out.println("Original Matrix : ");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
System.out.print(arr[i][j]+"\t");
System.out.println();
}
if(symm==true)
System.out.println("The given matrix is symmetrical");
else
System.out.println("The given matrix is not symmetrical");
System.out.println("Sum of left diagonal is : "+ sumld);
System.out.println("Sum of Right diagonal is : "+ sumrd);
}
static boolean isymmatrix(int m,int[][] arr)
{
for(int i=0;i<m;i++)
for(int j=0;j<m;j++)
if(arr[i][j]!=arr[j][i])
return(false);
return(true);
}
}
OUTPUT
1. Enter order of matrix between 2 and 10
3
Fill the matrix
1
2
Page 41 of 123
3
2
4
5
3
5
6
Original Matrix :
1 2 3
2 4 5
3 5 6
The given matrix is symmetrical
Sum of left diagonal is : 10
Sum of Right diagonal is : 11
Page 42 of 123
Program 13. Write a program to declare a single dimensional array a[] and a
square matrix b[][] of size N, where N > 2 and N < 10. Allow the user to input
positive integers into the single dimensional array.Perform the following task
on the matrix:
a) Sort the elements of the single dimensional array in ascending order using
any sorting technique and display the sorted elements.
b) Fill the matrix b[][] in the following format.
If the array a[] ={5,2,8,1} then after sorting, a[]={1,2,5,8}
Then the matrix b[][] would fill as below:
1258
1251
1212
1125
c) Display the filled matrix in the above format
Test your program for some random data.
Example 1:
INPUT : N=3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT :
SORTED ARRAY : 1 3 7
FILLED MATRIX :
137
131
113
Example 1:
INPUT : N=3
OUTPUT : MATRIX SIZE OUT OF RANGE
Page 43 of 123
ALGORITHM
1. Start
2. Print(“N=”)
3. Store the entered value in variable int n
4. if(n < 3 || n > 9)
{
5. System.out.println("MATRIX SIZE OUT OF RANGE");
6. return;
}
7. int a[] = new int[n];
8. Print(“ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:")
9. Repeat Step 10 for(int i = 0; i < a.length; i++)
10. Input value to a[i]
11. Repeat Step 12 for(int i = 0; i < a.length; i++)
{
12. Repeat Step 13 for(int j = 0; j < a.length - 1 - i; j++)
{
13. if(a[j] > a[j + 1])
{
14. int temp = a[j];
15. a[j] = a[j + 1];
16. a[j + 1] = temp;
}
17. Print("SORTED ARRAY: ")
18. Print(a[i] + " ") for(int i = 0; i < a.length; i++)
19. int m[][] = new int[n][n]
20. Repeat Steps 21 to 29 for(int i = m.length - 1; i >= 0; i--)
21. {
22. col = 0;
23. int j;
24. Repeat Steps 25 to 26for(j = 0; j <= i; j++)
{
25. m[row][col] = a[j];
26. col++;
}
27. int k = 0;
28. Repeat Step 29 for(; j < a.length; j++)
29. m[row][j] = a[k++];
30. row++;
31. Print("\nFILLED MATRIX")
32. Repeat Steps 33 to 35for(int i = 0; i < m.length; i++)
33. Repeat Step 34 for(int j = 0; j < m.length; j++)
34. System.out.print(m[i][j] + "\t");
Page 44 of 123
35. System.out.println();
36. Stop
CODE
import java.util.Scanner;
class P13_Matrix
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(n < 3 || n > 9)
{
System.out.println("MATRIX SIZE OUT OF RANGE");
return;
}
int a[] = new int[n];
System.out.println("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:");
for(int i = 0; i < a.length; i++)
a[i] = Integer.parseInt(in.nextLine());
for(int i = 0; i < a.length; i++) //SORTS ARRAY
{
for(int j = 0; j < a.length - 1 - i; j++)
{
if(a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
Page 45 of 123
}
}
System.out.print("SORTED ARRAY: ");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
int m[][] = new int[n][n];
int row = 0;
int col = 0;
for(int i = m.length - 1; i >= 0; i--) //CHANGES THE ELEMENTS
{
col = 0;
int j;
for(j = 0; j <= i; j++)
{
m[row][col] = a[j];
col++;
}
int k = 0;
for(; j < a.length; j++)
m[row][j] = a[k++];
row++;
}
System.out.println("\nFILLED MATRIX");
for(int i = 0; i < m.length; i++)
{
for(int j = 0; j < m.length; j++)
System.out.print(m[i][j] + "\t");
System.out.println();
}
Page 46 of 123
}
}
OUTPUT
1. N = 3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:
1
3
7
SORTED ARRAY: 1 3 7
FILLED MATRIX
1 3 7
1 3 1
1 1 3
2. N = 11
MATRIX SIZE OUT OF RANGE
3. N = 4
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:
2
53
6
7
SORTED ARRAY: 2 6 7 53
FILLED MATRIX
2 6 7 53
2 6 7 2
2 6 2 6
2 2 6 7
Page 47 of 123
Program 14:
The names of the teams participating in a competition should be displayed
on a banner vertically, to accommodate as many teams as possible in a single
banner. Design a program to accept the names of N teams, where 2 < N < 9
and display them in vertical order, side by side with a horizontal tab (i.e.
eight spaces).
Test your program for the following data and some random data:
Example 1 : INPUT :
N=3
Team 1 : Emus
Team 2 : Road Rols
Team 3 : Coyote
OUTPUT :
E R C
m o o
u a y
s d o
t
R e
O
L
s
ALGORITHM
1. Start
2. Print("N = ")
3. Input value in variable int n
4. if(n < 3 || n > 8)
{
5. System.out.println("OUT OF RANGE");
Page 48 of 123
6. return;
}
7. String a[] = new String[n]
8. Print("Enter " + n + " names:")
9. a[i] = in.nextLine().toUpperCase() for (int i = 0; i < a.length; i++)
10. String l = a[0]
11. Repeat Steps 12 to 17 for(int i = 1; i < a.length; i++)
12. if(l.length()<s.length())
13. issmaller=true
else
14. Issmaller= false
15. l = a[i] if(issmaller ==true)
16. Repeat Steps 17 to 20 for(int i = 0; i < l.length(); i++)
17. Repeat Steps 18 to 19 for(int j = 0; j < n; j++)
18. Print(a[j].charAt(i) + "\t") if(i < a[j].length())
19. Else Print(“\t”)
20. System.out.println()
21. Stop
CODE
import java.util.Scanner;
class P14_Banner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(n < 3 || n > 8)
{
System.out.println("OUT OF RANGE");
return;
}
String a[] = new String[n];
System.out.println("Enter " + n + " names:");
for(int i = 0; i < a.length; i++)
Page 49 of 123
a[i] = in.nextLine().toUpperCase();
String l = a[0];
for(int i = 1; i < a.length; i++)
{
boolean issmaller=issmaller(l,a[i]);
if(issmaller ==true)
l = a[i];
}
for(int i = 0; i < l.length(); i++) //PRINTS IN THE FORMAT
{
for(int j = 0; j < n; j++)
{
if(i < a[j].length())
System.out.print(a[j].charAt(i) + "\t");
else
System.out.print("\t");
}
System.out.println();
}
}
static boolean issmaller(String l,String s)
{
if(l.length()<s.length())
return (true);
else
return(false);
}
}
Page 50 of 123
OUTPUT
1. N = 3
Enter 3 names:
Emus
Road Rols
Coyote
E R C
M O O
U A Y
S D O
T
R E
O
L
S
2. N = 2
OUT OF RANGE
4. N = 9
OUT OF RANGE
Page 51 of 123
Program 15: Write a program to accept a set of n integers (where n > 0) in a
single dimensional array. Arrange the elements of the array such that the
lowest number appears in the centre of the array, next lower number in the
right cell of the centre, next lower in the left cell of the centre and so on....
The process will stop when the highest number will set in its appropriate cell.
Finally, display the array elements.Assume that the memory space is less.
Hence, you don't need to create extra array for the aforesaid task. Example:
Input : 1 2 3 4 5
Output: 5 3 1 2 4
Input : 11 12 31 14 5 45
Output: 31 12 5 11 14 45
ALGORITHM
1. Start
2. Print(“Enter number of Integers”)
3. Input and store the value in variable int n
4. int a[] = new int[n];
5. Print("Enter the numbers: ")
6. for(int i=0;i<n;i++)
store number in a[i]
7. int b[] = new int[a.length]
8. int mid = (a.length - 1) / 2
9. initialize int p and int q as mid
10. Repeat Steps 11 to 13 for(i = 0; i < a.length; i++)
11. if(i == 0)
b[mid] = a[i];
12. else if(i % 2 == 1)
b[++q] = a[i];
13. else
b[--p] = a[i];
14. Repeat Step 15 for(i = 0; i < b.length; i++)
15. Print(b[i]+ “ “)
16. Stop
CODE
import java.util.*;
class P15_Arrange
Page 52 of 123
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of Integers: "); //ENTERS THE NUMBERS
int n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter the numbers: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int b[] = new int[a.length];
int mid = (a.length - 1) / 2;
int i = 0;
int p = mid;
int q = mid;
for(i = 0; i < a.length; i++) //ARRANGES THE INTEGERS
{
if(i == 0)
b[mid] = a[i];
else if(i % 2 == 1)
b[++q] = a[i];
else
b[--p] = a[i];
}
for(i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
}
}
Page 53 of 123
OUTPUT
1. Enter number of Integers:
5
Enter the numbers:
1
2
3
4
5
53124
1. Enter number of Integers:
6
Enter the numbers:
11
12
31
14
5
45
5 31 11 12 14 45
2. Enter number of Integers:
5
Enter the numbers:
6
7
8
9
0
08679
Page 54 of 123
Program 16:
WAP in java to enter values into 2 one dimensional arrays of size m and n.
Now merge the contents of the two arrays in such a way that the values gets
arranged while merging.
Example
First Array m= 5
values : 1 9 11 3 2 6
Second Array n = 7
values : 0 2 5 13 11 7 6
Values of the Merged the array 0 1 2 3 5 6 7 9 11 13
ALGORITHM
1. Start
2. Print("Enter dimensions of the 2 arrays: ")
3. Store the dimensions of both arrays in int variables m and n
4. Create int arr1[] of size m;
5. Create int arr2[] of size n
6. Create int sortedarray[] of size (m+n)
7. Print ("Enter the first array :")
8. Repeat Step 9 for(i=0;i<m;i++)
9. Input and store integer in arr1[i]
10. Print ("Enter the second array :");
11. Repeat Step 12 for(i=0;i<n;i++)
12. Input and store integer in arr2[i]
13. Repeat Step 14 for(int i=0; i< arr1.length; i++)
14. Repeat Step 15 for(int j=i+1; j<arr1.length; j++)
15. if(arr1[i]>=arr1[j])
{
16. int temp=arr1[j];
17. arr1[j]=arr1[i];
18. arr1[i]=temp;
}
19. Repeat Step 20 for(int i=0; i< arr2.length; i++)
20. Repeat Step 21 for(int j=i+1; j<arr2.length; j++)
21. if(arr2[i]>=arr2[j])
{
22. int temp=arr2[j];
Page 55 of 123
23. arr2[j]=arr2[i];
24. arr2[i]=temp;
}
25. Repeat Steps 26 to 36 while (i<m && j <n)
26. if(arr1[i]==arr2[j])
{
27. j++;
28. continue;
}
29. if (arr1[i] < arr2[j])
{
30. sortedarr[k++] = arr1[i];
31. i++;
32. c++
}
33. else
{
34. sortedarr[k++] = arr2[j];
35. j++;
36. c++
}
37. sortedarr[k++] = arr1[i++] while (i < m)
38. sortedarr[k++] = arr2[j++] while (j < n)
39. Print ("Sorted Array :")
40. Repeat Steps 41 to 42 while(i<c)
{
41. Print(sortedarr[i] +"\t");
42. i++;
}
43. Stop
CODE
import java.util.*;
class P16_mergesort
{
int m,n,i,j,c=0;
Scanner sc=new Scanner(System.in);
int arr1[];
int arr2[];
int sortedarr[];
Page 56 of 123
void inputdimensions() //Enters dimensions of both arrays
{
System.out.println("Enter dimensions of the 2 arrays: ");
m=sc.nextInt();
n=sc.nextInt();
arr1=new int[m];
arr2=new int[n];
sortedarr=new int[(m+n)];
}
void fillarr() //fills the arrays
{
System.out.println("Enter the first array :");
for(i=0;i<m;i++)
arr1[i]=sc.nextInt();
System.out.println("Enter the second array :");
for(i=0;i<n;i++)
arr2[i]=sc.nextInt();
}
void sort() //sorts array
{
//sorts the first array in ascending array
for(int i=0; i< arr1.length; i++)
{
for(int j=i+1; j<arr1.length; j++)
{
if(arr1[i]>=arr1[j])
{
int temp=arr1[j];
arr1[j]=arr1[i];
Page 57 of 123
arr1[i]=temp;
}
}
}
//Sorts second array in ascending array
for(int i=0; i< arr2.length; i++)
{
for(int j=i+1; j<arr2.length; j++)
{
if(arr2[i]>=arr2[j])
{
int temp=arr2[j];
arr2[j]=arr2[i];
arr2[i]=temp;
}
}
}
//merging
int k=0,j=0,i=0;
while (i<m && j <n)
{
// Check if current element of first array is smaller than current element of second
array. If yes, store //first array element and increment first array index. Otherwise do
same with second array
if(arr1[i]==arr2[j])
{
j++;
continue;
}
if (arr1[i] < arr2[j])
Page 58 of 123
{
sortedarr[k++] = arr1[i];
i++;
c++;
}
else
{
sortedarr[k++] = arr2[j];
j++;
c++;
}
}
// Store remaining elements of first array
while (i < m)
sortedarr[k++] = arr1[i++];
// Store remaining elements of second array
while (j < n)
sortedarr[k++] = arr2[j++];
}
void display()
{
System.out.println("Sorted Array :");
i=0;
while(i<=c)
{
System.out.print(sortedarr[i] +"\t");
i++;
}
}
Page 59 of 123
public static void main(String args[])
{
P16_mergesort ob= new P16_mergesort();
ob.inputdimensions();
ob.fillarr();
ob.sort();
ob.display();
}
}
OUTPUT
1. Enter dimensions of the 2 arrays:
3
3
Enter the first array :
1
2
3
Enter the second array :
4
5
6
Sorted Array :
1 2 3 4 5 6
Page 60 of 123
2. Enter dimensions of the 2 arrays:
6
7
Enter the first array :
1
9
11
3
2
6
Enter the second array :
0
2
5
13
11
7
6
Sorted Array :
0 1 2 3 5 6 7 9 11 13
Page 61 of 123
Program 17:
WAP in java to enter two 2-Dimenional arrays of user defined choice and
print the union and intersection of the 2 arrays Both the arrays have the
same size .
First Array
R1= 3
C1=4
Values of the First Array
5 6 9 7 1 2 8
14 20 54 19 0
Values of the Second Array
4 8 6 9 2 14 20
22 30 54 0 19
Union of the 2 arrays
0 1 2 4 5 6 7 8 9 14 19 20
22 30 54
Intersection of the 2 arrays
0 2 6 8 9 14 19
20 54
ALGORITHM
1. Start
2. Print(“Enter the Row and column of both the arrays:”)
3. Input the values in variables m and n
4. Int arr1[]=new int[m][n]
5. Int arr2[]=new int[m][n]
6. Int u=new int[2*(m*n)]
7. Int insec=new int[m*n]
8. Print ("Enter the first array")
9. Repeat Steps 10 to 13 for(i=0;i<m;i++)
10. Repeat Steps 11 to 12 for(j=0;j<n;j++)
11. Input value in arr1[i][j]
12. u[c++]=arr1[i][j]
13. Print new line
Page 62 of 123
14. print("Enter the Second array")
15. Repeat Steps 16 to 18 for(i=0;i<m;i++)
16. Repeat Steps 17 for(j=0;j<n;j++)
17. Input value in arr2[i][j]
18. Print new line
19. Boolean sem=false
20. Repeat Step 21 to 28 for(i=0;i<m;i++)
21. Repeat Steps 22 to 28 for(j=0;j<n;j++)
22. Repeat Steps 23 to 26 for(int k=0;k<c;k++)
23. if(arr2[i][j] == u[k])
{
24. insec[g++]=arr2[i][j];
25. sem=true;
26. break;
}
27. u[c++]= arr2[i][j] if(sem=false)
28. sem=false;
29. Print(“Union: “)
30. Repeat Steps 31 to 33 for(i=0;i<c;i++)
{
31. if(u[i]==u[i+1] && i<(c-1))
{
32. continue;
}
33. System.out.print(u[i]+"\t");
}
34. Print(“\n Intersection: “)
35. Repeat Steps 36 to 38 for(i=0;i<g;i++)
36. if(i<(g-1) && insec[i]==insec[i+1])
37. continue
38. System.out.print(insec[i]+"\t")
39. Stop
CODE
import java.util.*;
class P17
{
int arr1[][];
int arr2[][];
int u[]; //Stores the elements in a 1d array
int insec[];
Page 63 of 123
int m,n,i,j,k,g=0,c=0;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Row and column of both the arrays: ");
m = sc.nextInt();
n = sc.nextInt();
arr1 = new int[m][n];
arr2 = new int[m][n];//M is rows,N is columns
u = new int[2*(m*n)];
insec = new int[m*n];
}
void fill()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first array"); //Inputs the numbers row wise
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
arr1[i][j]=sc.nextInt();
u[c++]=arr1[i][j];
}
System.out.println();
}
System.out.print("Enter the Second array");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
Page 64 of 123
{
System.out.print("\t");
arr2[i][j]=sc.nextInt();
}
System.out.println();
}
}
void uniosection() //Sorts the Array and sends same element from both to another array
{
boolean sem=false;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
for(int k=0;k<c;k++)
{
if(arr2[i][j] == u[k])
{
insec[g++]=arr2[i][j];
sem=true;
break;
}
}
if(sem=false)
u[c++]= arr2[i][j];
sem=false;
}
}
}
Page 65 of 123
void display()
{
System.out.println("Union : ");
for(i=0;i<c;i++)
{
if(u[i]==u[i+1] && i<(c-1))
{
continue;
}
System.out.print(u[i]+"\t");
}
Page 66 of 123
OUTPUT
1. Enter the Row and column of both the arrays:
2
6
Enter the first array
5 6 9 7 1 2
8 14 20 54 19 0
Enter the Second array
4 8 6 9 2 14
20 22 30 54 19 0
Union :
14 5 1 0 2 6 9 7 8 19 20 54
Intersection:
8 6 9 2 14 20 54 19 0
2. Enter the Row and column of both the arrays:
2
2
Enter the first array
1
2
2
3
Enter the Second array 4
2
6
5
Union :
1 2 3 4 5 6
Intersection:
2
Page 67 of 123
Program 18.
WAP in java to create an overloaded function as follows :
boolean isAnagram(String S1,String S2)- to find if the two strings are
anagram.
An anagram of a string is another string that contains the same characters,
only the order of characters can be different.
For example, “abcd” and “dabc” are an anagram of each other.
boolean isAnagram(int S1,int S2)- to find if the two numbers are anagram.
Write a menu driven program, to enter 2 different strings or integers
depending upon users choice. For an invalid choice display appropriate error
message.
String Examples Race – care, part-trap, Triangle- Integral , heart- earth
Number examples 1721-1271 , 12898 – 91288
ALGORITHM
1. Start
2. Print ("Enter 1 to find anagram of String or 2 for Anagram of Integers")
3. Store the choice in int variable ch
4. Switch(ch)
5. Case 1:
{
6. Print ("Enter the 2 Strings: ")
7. Input and store the words in String S1 and S2
8. if(S1.length()!=S2.length())
9. Boolean ana=false
10. else
11. Repeat Steps 12 to 13for(int i=0;i<S1.length();i++)
12. Repeat Step 13 for(int j=0;j<S2.length();j++)
13. c++ if(S1.charAt(i)=S2.charAt(j))
14. if(c>=S1.length())
15. Boolean ana =true;
16. else
17. Boolean ana =false
18. Print("Not Anagram") if(ana=false)
19. Else Print ("Anagram")
}
Page 68 of 123
20. Case 2
{
21. Print(“Enter the 2 numbers: “)
22. Store the 2 numbers in n1 and n2
23. for(j=S2;j>0;j=j/10)
l2++;
24. for( i=S1;i>0;i=i/10)
l1++;
25. if(l2!=l1)
26. anag=false
27. Repeat Steps 28 to 30 for( i=S1;i>0;i=i/10)
28. Repeat Step 29 for(j=S2;j>0;j=j/10)
29. c++ if(i%10==j%10)
30. if(c>=l1)
31. Boolean anag =true;
32. else
33. Boolean anag=false
34. Print("Not Anagram") if(anag=false)
35. Else Print ("Anagram")
}
36. Stop
CODE
import java.util.*;
class P18_Anagram
{
static boolean isAnagram(String S1,String S2)
{
if(S1.length()!=S2.length())
return(false);
int c=0;
for(int i=0;i<S1.length();i++)
{
for(int j=0;j<S2.length();j++)
if(S1.charAt(i)==S2.charAt(j))
{
c++ ;
Page 69 of 123
continue;
}
}
if(c>=S1.length())
return(true);
else
return(false);
}
static boolean isAnagram(int S1,int S2)
{
int c=0,i,j,l2=0,l1=0;
for(j=S2;j>0;j=j/10)
l2++;
for( i=S1;i>0;i=i/10)
l1++;
if(l2!=l1)
return(false);
for( i=S1;i>0;i=i/10)
{
for(j=S2;j>0;j=j/10)
if(i%10==j%10)
{
c++ ;
continue;
}
}
if(c>=l1)
return(true);
else
Page 70 of 123
return(false);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter 1 to find anagram of String or 2 for Anagram of Integers") ;
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the 2 Strings: ");
String S1=sc.next();
String S2=sc.next();
boolean ana=isAnagram(S1,S2);
if(ana==false)
System.out.println("Not Anagram");
else
System.out.println("Anagram");
break;
case 2:
System.out.println("Enter the 2 Numbers: ");
int n1=sc.nextInt();
int n2=sc.nextInt();
boolean anag=isAnagram(n1,n2);
if(anag==false)
System.out.println("Not Anagram");
else
Page 71 of 123
System.out.println("Anagram");
break;
}
}
}
OUTPUT
Page 72 of 123
Program 19.
A sentence is terminated 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.
Write a program to:
(i) Obtain the length of the sentence (measured in words) and the
frequency of vowels in each sentence
(ii) (ii) Generate the output as shown below using the given data
Sample data:
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
Sentence No of words/vowels
------------------------------------------------------------------------------- 1
VVVVVV
WWW
2 VVVVVVVVVVVVVVV
WWWWWWWW
3 VVVVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWW
4 VVVVVVVVV
WWWWWWWW
------------------------------------------------
Scale used: 1:3
ALGORITHM
1. Start
2. Print("Enter the text:")
3. Input in string text and convert it to upper case
4. Initialize String tokenizer
5. int num = st.countTokens()
Page 73 of 123
6. Print ("Maximum 10 sentences allowed!") and exit if(num > 10)
7. int a[][] = new int[num][2]
8. Repeat Steps 9 to 19 for (int i = 1; i <= num; i++)
9. String s = st.nextToken()
10. col = 0
11. Initialize String Tokenizer for s
12. int numOfWords = x.countTokens()
13. println("Sentence " + i + " No. of words: " + numOfWords)
14. Repeat Step 15 for(int j = 0; j < s.length(); j++)
15. v++ if("AEIOU".indexOf(s.charAt(j)) >= 0)
16. println("Number of vowels: " + v)
17. a[row][col] = v
18. a[row][++col] = numOfWords
19. row++
20. Repeat Steps 21 to 26 for(int i = 0; i < a.length; i++)
21. println("Sentence" + (i + 1) + ": \t")
22. Repeat Steps 23 to 25 for(int j = 0; j < 2; j++)
23. Repeat Steps 24 and 25 for(int k = 1; k <= a[i][j] * 3; k++)
24. print("V") if(j == 0)
25. else print("W")
26. println("\t")
27. Stop
CODE
import java.util.Scanner;
class Frequency{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the text:");
String text = in.nextLine().toUpperCase();
StringTokenizer st = new StringTokenizer(text, ".!?");
int num = st.countTokens();
if(num > 10){
System.out.println("Maximum 10 sentences allowed!");
return; }
int a[][] = new int[num][2];
int row = 0;
Page 74 of 123
int col = 0;
for(int i = 1; i <= num; i++){
String s = st.nextToken();
col = 0;
StringTokenizer x = new StringTokenizer(s);
int numOfWords = x.countTokens();
System.out.println("Sentence " + i + " No. of words: " + numOfWords);
int v = 0;
for(int j = 0; j < s.length(); j++){
if("AEIOU".indexOf(s.charAt(j)) >= 0)
v++; }
System.out.println("Number of vowels: " + v);
a[row][col] = v;
a[row][++col] = numOfWords;
row++; }
for(int i = 0; i < a.length; i++){
System.out.println("Sentence" + (i + 1) + ": \t");
for(int j = 0; j < 2; j++){
for(int k = 1; k <= a[i][j] * 3; k++)
if(j == 0)
System.out.print("V");
else
System.out.print("W");
System.out.println("\t"); } } } }
OUTPUT
1. Enter the text:
Russell Baker’s tragic past, and his desire to entertain create a tone of mocking sarcasm in “The Plot
Against People. For example, Baker states that the one “goal of all inanimate objects is to resist man
and ultimately defeat him.” He is speaking as if inanimate objects can think and reason and actually
have joined together to plot mankind’s destruction. The absurdity of this statement makes it funny
and causes the reader to perhaps laugh at his or her own experiences with such objects. In addition,
Page 75 of 123
Baker speculates that perhaps things that get lost have a “secret method of locomotion” that they
can conceal whenever a “human eye falls upon them.” The mental image of a pair of pliers suddenly
sprouting arms and legs when we can’t see them is hilarious. This is, of course, just plain silly and
quite obviously meant to get a laugh from the reader. Finally, Baker feels those things that don’t
work have “given man the only peace he receives from inanimate objects” and have therefore
“attained the highest state possible for an inanimate object.” Baker experiencing the tragedy of
losing his father, and having to leave behind his sister cause him to see the unimportance of the
need to control these objects. He understands that peace can only come from placing no
expectations on the areas of ones life that one cannot control. In conclusion, Baker’s past and his
sense of humor go hand in hand to put a sarcastic spin on the importance of lifes little nuisences.
Maximum 10 sentences allowed!
Page 76 of 123
Program 20.
A class Capital has been defined to check whether a sentence has words
beginning with a capital letter or not.
Some of the members of the class are given below:
Class name : Capital
Data member/instance variable:
sent : to store a sentence
freq : stores the frequency of words beginning with a capital letter Member
functions/methods:
Capital( ) : default constructor
void input() : to accept the sentence
boolean isCap(String w) : checks and returns true if word begins with a
capital letter, otherwise returns false
void display () : displays the sentence along with the frequency of the words
beginning with a capital letter
Specify the class Capital, giving the details of the constructor( ), void input( ),
boolean isCap(String) and void display( ). Define the main( ) function to
create an object and call the functions accordingly to enable the task .
ALGORITHM
1. Start
2. Print ("Enter the sentence: ")
3. Input the value in variable String sent
4. Print("Sentence: " + sent)
5. Store number of words In int count
6. Step Steps 7 to 8 for(int i = 1; i <= count; i++)
{
7. if(Character.isUpperCase(w.charAt(0) = true )
8. freq++;
}
9. Print(“Frequency: “+freq)
Page 77 of 123
CODE
import java.util.*;
class Capital
{
String sent;
int freq;
public Capital()
{
sent = "";
freq = 0;
}
public void input()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
sent = in.nextLine().trim()+" ";
}
public boolean isCap(String w)
{
return Character.isUpperCase(w.charAt(0));
}
public void display()
{
System.out.println("Sentence: " + sent);
StringTokenizer st = new StringTokenizer(sent);
int count = st.countTokens();
for(int i = 1; i <= count; i++) //Checks Capital Letter for each Word in the
sentence
{
Page 78 of 123
if(isCap(st.nextToken()))
freq++;
}
System.out.println("Frequency: " + freq);
}
public static void main(String[] args){
Capital obj = new Capital();
obj.input();
obj.display();
}
}
OUTPUT
1. Enter the sentence: Indian Institute of Technology Bombay
Sentence: Indian Institute of Technology Bombay
Frequency: 4
2. Enter the sentence: Computer Science is an Interesting subject!
Sentence: Computer Science is an Interesting subject!
Frequency: 3
Page 79 of 123
Program 21.
A class Comp_Magic contains a two dimensional array of order [M x N]. The
maximum value possible for both ‘m’ and ‘n’ is 20.
Design a class Comp_Magic to fill the array with the first (M x N) Composite
Magic numbers in column wise order.
The details of the members of the class are given below:
A magic number is a number in which the eventual sum of the digits is equal
to 1. For example 28= 2+8 = 10 = 1+0 = 1.
A composite number is a number which has more than 2 factors.
Class name : Comp_Magic
Data members/instance variables:
arr[ ] [ ] : stores the Composite Magic numbers column wise
M : integer to store the number of rows
N : integer to store the number of columns
Member functions/methods:
Comp_Magic (int mm, int nn ): to initialize the size of the matrix M=mm and
N=nn int isComposite( int p ) : returns 1 if number is Composite otherwise
returns 0
int isMagic( int p ) : returns 1 if number is Magic otherwise returns 0
void fill ( ) : to fill the elements of the array with the first (M× N) Composite
Magic numbers in column wise order
void display( ) : displays the array in a matrix form
Define a main( ) function to create an object and call the functions
accordingly to enable the task
ALGORITHM
1. Start
2. Print("Number of rows: ")
3. Input the value of rows in variable int mm
4. Print("Number of columns: ")
5. Input the value of coloumns in variable int nn
Page 80 of 123
6. if(mm > 20 || nn > 20)
{
7. Print(“INVALID INPUT”)
8. Close the program
}
9. Int p=0
10. Repeat Steps 11 to 29 for(int i = 0; i < n; i++)
{
11. Repeat Steps 12 to 28 for(int j = 0; j < m;)
{
12. int f = 0
13. Repeat Steps 14 and 15 for(int i = 1; i <= p; i++)
{
14. if(p % i == 0)
15. f++
}
16. if(f > 2) return 1
17. Else return 0
18. Repeat Steps 19 to 22 while(p > 9)
{
19. int sum = 0;
20. for(int i = p; i != 0; i /= 10)
21. sum += i % 10;
22. p = sum;
}
23. if(p == 1)
24. return 1;
25. return 0;
26. if(Steps 12 to 17 = 1 && Steps 18 to 25== 1)
{
27. arr[j][i] = p
28. j++
}
29. p++
}
}
30. Repeat Steps 31 to 32 for(int i = 0; i < m; i++)
31. Print(arr[i][j] + "\t") for(int j = 0; j < n; j++)
32. Print(“\n”)
33. Stop
Page 81 of 123
CODE
import java.util.Scanner;
class P21_C_M{
int m;
int n;
int arr[][];
public P21_C_M(int mm, int nn)
{
m = mm;
n = nn;
arr = new int[m][n];
}
public int isComposite(int p)
{
int f = 0;
for(int i = 1; i <= p; i++)
{
if(p % i == 0)
f++; //Finds the number of Factors
}
if(f > 2)
return 1;
return 0;
}
public int isMagic(int p)
{
while(p > 9)
{
int sum = 0;
Page 82 of 123
for(int i = p; i != 0; i /= 10) //Finds if it’s a Magic Number
sum += i % 10;
p = sum;
}
if(p == 1)
return 1;
return 0;
}
public void fill()
{
int p = 10;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m;)
{
if(isComposite(p) == 1 && isMagic(p) == 1){
arr[j][i] = p;
j++;
}
p++;
}
}
}
public void display()
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
System.out.print(arr[i][j] + "\t");
Page 83 of 123
System.out.println();
}
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Number of rows: ");
int mm = Integer.parseInt(in.nextLine());
System.out.print("Number of columns: ");
int nn = Integer.parseInt(in.nextLine());
if(mm > 20 || nn > 20)
{
System.out.println("INVALID INPUT");
return;
}
P21_C_M obj = new P21_C_M(mm, nn);
obj.fill();
obj.display();
}
}
OUTPUT
1. Number of rows: 3
Number of columns: 3
10 55 91
28 64 100
46 82 118
Page 84 of 123
2. Number of rows: 10
Number of columns: 10
10 145 262 370 496 622 721 847 964 1081
28 154 280 388 505 640 730 856 973 1090
46 172 289 406 514 649 748 865 982 1099
55 190 298 415 532 658 766 874 1000 1108
64 208 316 424 550 667 775 892 1018 1126
82 217 325 442 559 676 784 901 1027 1135
91 226 334 451 568 685 793 910 1036 1144
100 235 343 460 586 694 802 928 1045 1162
118 244 352 469 595 703 820 946 1054 1180
136 253 361 478 604 712 838 955 1072 1189
3. Number of rows: 21
Number of columns: 21
INVALID INPUT
Page 85 of 123
Program 22.
A class Recursion has been defined to find the Fibonacci series upto a
limit. Some of the members of the class are given below: Class Name :
Recursion .
Data Members/instance variables :
a, b, c, limit (all integers)
Member functions/methods :
Recursion() : constructor to assign a,b,c with appropriate values.
void input() : to accept the limit of the series.
int fib(int n) : to return the nth Fibonacci term using recursive
technique.
void genearate_fibseries() : to generate the Fibonacci series upto the
given limit.
Specify the class Recursion giving details of the constructor, int fib() ,
void generate_fibseries().
You may assume other functions are written for you and you need not
write the main function.
Example:
Enter the limit : 11
The Fibonacci Series is: 0 1 1 2 3 5 8 13
21 34 55
ALGORITHM
1. Start
2. Print("Enter limit: ")
3. Input the limit in variable lim
4. Repeat Steps 5 to 10 for (j=1;j>=0;j++)
5. if(j = 1|| j<=0)
6. fibo= 0;
7. if(n = 2)
8. fibo=1;
9. fibo =Steps 5 to 8 (n - 1) + Steps 5 to 8 (n - 2)
10. Print( fibo +"\t")
Page 86 of 123
11. i++
12. if(i>=lim)
13. Break
14. Stop
CODE
import java.util.*;
class P22_recursion
{
int a,b,c,lim;
P22_recursion()
{
a=0;
b=1;
c=a+b;
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter limit: ");
lim=sc.nextInt();
}
int fib(int n)
{
if(n == 1|| n<=0)
return 0;
if(n == 2)
return 1;
return fib(n - 1) + fib(n - 2); //Fibonacci series
}
void generate_fibseries()
Page 87 of 123
{
int i=0,j=0,fibo;
for(j=1;j>=0;j++)
{
fibo=fib(j);
System.out.print( fibo +"\t");
i++;
if(i>=lim)
break;
}
}
public static void main(String args[])
{
P22_recursion ob= new P22_recursion();
ob.input();
ob.generate_fibseries();
}
}
OUTPUT
1. Enter limit: 7
0 1 1 2 3 5 8
2. Enter limit: 5
0 1 1 2 3
Page 88 of 123
Program 23.
A Special number is a number in which the sum of the factorial of its digits is
equal to the number.
Example: 145 ( 1! + 4! + 5! = 145 ).
Thus, 145 is a Special number.
Design a class Special to check if the given number is a Special number or not.
Some of the members of the class are given below:
Class name : Special Data
member/instance variable:
n : integer to store number
Member functions/methods:
Special( ) : default constructor
void read( ) : to accept the number
int factorial(int x) : returns the factorial of a number using recursive functions
booleanisSpecial( ) : checks for the special number by invoking the function
factorial( ) and returns true if special, otherwise returns false
void display( ) : displays the result with an appropriate message .
Specify the class Special, giving details of the Constructor, void read( ), int
factorial(int), booleanisSpecial( ) and void display( ). Define the main()
function to create an object and call the member functions accordingly to
enable the task.
AlGORITHM
1. Start
2. Print ("Enter number: ")
3. Input the number in variable n
4. int i=n,sum=0
5. Repeat Steps 6 and 8 while(i>0)
6. sum=sum+1 if(i=0||i=1)
7. else sum=sum+ Steps 6 and 7 with (--i)
8. i/=10
9. Boolean special=true if(sum=n)
10. Else Boolean special=false
Page 89 of 123
11. if(special==true) Print(n+" is a Special number")
12. else Print(n+" is not a Special number")
13. Stop
CODE
import java.util.*;
class P23_Special
{
int n;
void read()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number: ");
n=sc.nextInt();
}
int factorial(int x)
{
if(x==0||x==1)
return(1);
return(x)*factorial(--x);
}
boolean isSpecial() //Finds if it is Special
{
int i=n,sum=0;
while(i>0)
{
sum=sum+factorial(i%10);
i/=10;
}
if(sum==n)
Page 90 of 123
return (true);
else
return(false);
}
void display()
{
boolean special=isSpecial();
if(special==true)
System.out.println(n+" is a Special number");
else
System.out.println(n+" is not a Special number");
}
public static void main(String args[])
{
P23_Special ob=new P23_Special();
ob.read();
ob.display();
}
}
OUTPUT
1. Enter number:
45
45 is not a Special number
2. Enter number:
145
145 is a Special number
3. Enter number:
69
69 is not a Special number
Page 91 of 123
Program 24.
A class Admission contains the admission numbers of 100 students.
Some of the data members / member functions are given below
Class name : Admission
Data member/
Adno [] : integer array to store admission numbers
Member functions/methods:
Admission( ) : constructor to initialize the array element
void fillArray( ): to accept the elements of the array in ascending order
int binSearch(int l, int u, int v): to search for a particular admission number
(v) using binary search and recursive technique and returns | if found
otherwise returns -1
Specify the class Admission gi s of the constructor, void fillArray( ) and
int binSearch(int, int, . in( ) function to create an object and call the
functions .
ALGORITHM
1. Start
2. Repeat Steps 3 to 12 for(int i = 0; i < adno.length;)
{
3. boolean valid = true;
4. Print("Admission number " + (i + 1) + ": ");
5. Store the entered value in x
6. Repeat Steps 7 to 9 for(int j = 0; j < i; j++)
{
7. if(x < adno[j])
{
8. valid = false;
9. break;
}
10. if(valid)
{
11. adno[i] = x;
12. i++;
}
}
13. Print("Admission number to be searched: ")
Page 92 of 123
14. Input the value in variable key
15. Initialize int result=0
16. public int binSearch(int l, int u, int v)
{
17. if(l > u)
18. return -1;
19. int m = (l + u) / 2;
20. if(v == adno[m])
21. return 1;
22. if(v < adno[m])
23. return binSearch(l, m - 1, v);
24. return binSearch(m + 1, u, v);
25. }
26. result=binSeach(0,99,key)
27. Print (key + " found!") if(result == 1)
28. Else Print (key + " not found.")
29. Stop
CODE
import java.util.Scanner;
class P24_ADM{
int adno[];
public P24_ADM()
int x = Integer.parseInt(in.nextLine());
Page 93 of 123
valid = false;
break;
if(valid)
adno[i] = x;
i++;
public int binSearch(int l, int u, int v) //SEARCHES FOR THE REQUIRED ADM NO
if(l > u)
return -1;
int m = (l + u) / 2;
if(v == adno[m])
return 1;
obj.fillArray();
if(result == 1)
Page 94 of 123
System.out.println(key + " found!");
else
OUTPUT
1. Admission number 1: 100
Admission number 2: 101
Admission number 3: 103
Admission number 4: 104
Admission number 5: 105
Admission number to be searched: 100
100 found!
2. Admission number 1: 16877
Admission number 2: 16878
Admission number 3: 16879
Admission number 4: 16880
Admission number 5: 16882
Admission number to be searched: 16882
16882 found!
Page 95 of 123
Program 25.
A super class Record has been defined to store the names and ranks of 50
students. Define a sub-class Rank to find the highest rank along with the
name. The details of both classes are given below:
Class Name :
Record
Data member/instance variables:
name[] : to store the names of students
rnk[] : to store the ranks of students
Data members/ instance variables:
Record() : constructor to initialize data members
void readvalues() : to store names and ranks
void display() : display the names and corresponding ranks
Class Name : Rank
Data Members/ instance variables :
index : integer to store the index of the topmost rank
Member Functions :
Rank() : constructor to invoke the base class constructor and to initialize
index=0
void highest() : finds the index/location of the topmost rank and stores it in
index without sorting the array.
void display() : displays the names and ranks along with the name having
topmost rank.
Specify the class Record giving details of the constructor(), void readvalues()
and void display(). Using the concept of inheritance, specify the class Rank
giving details of constructor, void highest() and void display().
Page 96 of 123
ALGORITHM
1. Create array int rnk and String name of size 50
2. Repeat Steps 3 to 6 for(int i = 0; i < name.length; i++)
{
3. Print("Name " + (i + 1) + ": ")
4. Input in name[i]
5. Print("Rank: ")
6. Input in rnk[i]
}
7. Int index=0
8. Repeat Steps 7 to 8 for(int i = 1; i < name.length; i++)
9. if(rnk[index] > rnk[i])
10. index = i
11. Print(name[i] + " - " + rnk[i]) for(int i = 0; i < name.length; i++)
12. Println("Topmost rank: " + name[index])
13. Stop
CODE
import java.util.Scanner;
class Student
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Rank obj = new Rank();
obj.readValues();
obj.highest();
obj.display();
}
}
class Record
{
Page 97 of 123
protected String name[];
protected int rnk[];
public Record()
{
name = new String[50];
rnk = new int[50];
}
public void readValues(){
Scanner in = new Scanner(System.in);
for(int i = 0; i < name.length; i++)
{
System.out.print("Name " + (i + 1) + ": ");
name[i] = in.nextLine();
System.out.print("Rank: ");
rnk[i] = Integer.parseInt(in.nextLine());
}
}
public void display(){
for(int i = 0; i < name.length; i++)
System.out.println(name[i] + " - " + rnk[i]);
}
}
class Rank extends Record
{
int index;
public Rank()
{
super();
index = 0;
Page 98 of 123
}
public void highest()
{
for(int i = 1; i < name.length; i++)
{
if(rnk[index] > rnk[i])
index = i;
}
}
public void display()
{
super.display();
System.out.println("Topmost rank: " + name[index]);
}
}
OUTPUT
1. Name 1: Shreyansh
Rank: 6942
Name 2: Anirudh
Rank: 69420
Name 3: Priyanshu
Rank: 420690
Name 4: SK
Rank: 100
Name 5: SSR
Rank: 1
Shreyansh - 6942
Anirudh - 69420
Priyanshu - 420690
SK - 100
SSR - 1
Topmost rank: SSR
2. Name 1: a
Rank: 1
Page 99 of 123
Name 2: b
Rank: 2
Name 3: c
Rank: 3
Name 4: d
Rank: 4
Name 5: e
Rank: 5
a-1
b-2
c-3
d-4
e-5
Topmost rank: a
ALGORITHM
1. Start
2. Print ("Customer name: ")
3. Input in string n
4. Print ("Address: ")
5. Input in String a
6. Print("Telephone number: ")
7. Input in long t
8. Print("Rent: ")
9. Input in double r
10. print("Number of calls: ")
11. Input in int num
12. String name=n
13. String address=a
14. Long telno=t
15. Int rent=r
16. Int n=num
17. Double amt=0.0
18. if(n <= 100)
amt = rent;
19. else if(n <= 200)
amt = 0.6 * n + rent;
20. else if(n <= 300)
amt = 0.8 * n + rent;
21. else
amt = n + rent
22. print("Customer name: " + name)
23. print("Address: " + address)
24. print("Telephone No: " + telno)
25. print("Monthly rent: " + rent)
26. Print ("Number of calls: " + n)
27. Print("Amount: " + amt)
28. Stop
CODE
import java.util.Scanner;
class Detail{
OUTPUT
1. Customer name: SDAS
Address: SPS
Telephone number: 1234567890
Rent: 120
Number of calls: 100
Customer name: SDAS
Address: SPS
Telephone No: 1234567890
Monthly rent: 120.0
Number of calls: 100
Amount: 120.0
CODE
import java.util.Scanner;
class Parallelogram{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Length: ");
double l = Double.parseDouble(in.nextLine());
System.out.print("Breadth: ");
double b = Double.parseDouble(in.nextLine());
System.out.print("Height: ");
double h = Double.parseDouble(in.nextLine());
Area obj = new Area(l, b, h);
obj.doArea();
obj.show();
}
}
class Perimeter{
protected double a;
OUTPUT
1. Length: 3
Breadth: 4
Height: 5
Length = 3.0
Breadth = 4.0
Perimeter = 14.0
Area = 20.0
2. Length: 10
Breadth: 20
Height: 15
Length = 10.0
Breadth = 20.0
Perimeter = 60.0
Area = 300.0
CODE
import java.util.Scanner;
class MyInheritance{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Item name: ");
String i = in.nextLine();
OUTPUT
1. Item name: Maggi
Quantity: 20
Rate: 10
CODE
import java.util.Scanner;
class p29
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String n = in.nextLine();
System.out.print("Account Number: ");
long a = Long.parseLong(in.nextLine());
System.out.print("Principal Amount: ");
double p = Double.parseDouble(in.nextLine());
Account obj = new Account(n, a, p);
boolean r=true;
while(true){
System.out.println("1. Deposit Money");
System.out.println("2. Withdraw Money");
System.out.println("3. Display Details");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(in.nextLine());
switch(choice){
case 1:
obj.deposit();
r=false;
break;
case 2:
obj.withdraw();
OUTPUT
1. Name: SDAS
Account Number: 12345678
Principal Amount: 129837
1. Deposit Money
2. Withdraw Money
3. Display Details
Enter your choice: 1
CODE
import java.util.Scanner;
class P30{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
Series obj = new Series(n);
obj.calSum();
obj.display();
}
}
class Number{
protected int n;
public Number(int nn){
n = nn;
}
public int factorial(int a){
if(a == 0 || a == 1)
return 1;
OUTPUT
1. N = 6
N=6
Sum = 873
2. N = 4
N=4
Sum = 33