You are on page 1of 167

BISHOP COTTON GIRLS’ SCHOOL

COMPUTER SCIENCE PROJECT


2023 – 2024

Name: Aishwarya Mahesh B


Stream: XII Science
Index Number: 6
ACKNOWLEDGEMENT

I would like to thank my Computer Science teacher, Mrs.


Priscilla Joyce, for her guidance and support in completing my
project.

I would also like to express my gratitude to the principal of our


school, Dr. Mrs. Lavanya Mithran, for providing me with the
necessary facilities.

Last but not the least, I would like to thank my parents for their
unending support and love which motivates me to give my best.
Thank you.

X
____________________________________
Signature of School Principal/School Seal

X
____________________________________
Signature of External Examiner

X
____________________________________
Signature of Concerned Subject Teacher

1
INDEX

S. PAGE
TITLE OF PROGRAM
NO. NO.
SET 1: Objects and Classes
1. “Add_Dist” 7

2. “Display” 9

3. Combination of consecutive numbers 12

4. Automorphic Numbers 14

5. Convert Binary Number to Decimal or Decimal Number to Binary 16

6. Circular Prime 19

7. Goldbach Number 22

SET 2: Statements and Scope

8. Smith Number 27

9. Evil Number 29

10. Bouncy Number 31

11. Pronic Number 33

12. Fascinating Number 35

SET 3: String Manipulations

13. Pig Latin 38

14. Encoding 40

15. Deleting vowels from a word 42

16. Combinations of a three-lettered word 44

2
17. Decoding a given String 46

18. Deleting a word as specified 48

19. placing words beginning and ending with a vowel 51

20. Displaying names of teams in vertical order 54

SET 4: Arrays
21. Deleting duplicate numbers 58

22. To convert decimal number to hexadecimal number 60

23. To display the date in words 62

24. To arrange the words of a sentence in decreasing order of their length 65

25. To display the time in words 68

26. Arranging the elements of the roads in ascending order 72

27. Circular Matrix 75

28. Magic Square 78

29. Rotated Matrix 82

30. Sorting non boundary elements in ascending order 88

SET 5: Methods (Functions)

31. Telcall 94

32. Special Number 96

33. Sorting the array in ascending order 99

34. Binary search in Array 102

35. Magic Number 105

36. Sum of Rows and Columns of Matrix 107

3
37. To convert decimal number to hexadecimal number and vice versa 110

38. StringOP 113

39. Exchanging first and last letters 115

40. Merging two arrays 118

SET 6: Recursion

41. Reverse Number 121

42. Convert Decimal Number to Binary Number 122

43. Binary Search 123

44. Factorial of a Number 125

45. Finding Prime Numbers 127

46. Finding admission number by binary search 129

47. Disarium Number 131

48. Palindrome Number 133

SET 7: Inheritance, Interfaces and Polymorphism

49. Product of Numbers 136

50. Salary 138

51. Bank Account 140

52. Overriding 142

53. Finding Maximum Number 144

54. Area and Volume of sphere 146

55. Marks of a student 148

SET 8: Data Structures

4
56. Stack 151

57. StackOperations 153

58. Queue 156

59. QueueOperations 158

60. Dequeue 161

61. CQueue 164

5
SET 1: Classes and Objects

6
PROGRAM 1

QUESTION:

Design a class ‘Add_Dist’ with the following specification:


Class: Add_Dist
Data members/Instance variables:
int km, mts, cm
Member methods:
void get_dist() : to accept a distance in km, mts and cm.
void show_dist() : to display the distance in km, mts and cm.
Write a main function to create an object of class ‘Add_Dist’ and call the member methods.

SOURCE CODE:

//A program to accept and display the given distance in km, mts and cm
// Importing the java.util package to use Scanner class for input
import java.util.*;
// Class declaration for Add_Dist
class Add_Dist
{
// Creating a Scanner object to read input
Scanner sc = new Scanner(System.in);
// Declaring instance variables to store distance in km, mts, and cm
int km, mts, cm;
// Method to get distance from user
void get_dist()
{
// Prompting user to enter the distance in km, mts, and cm
System.out.println("Enter the distance in kilometres, metres and centimetres");
// Reading input values for km, mts, and cm
km = sc.nextInt();
mts = sc.nextInt();
cm = sc.nextInt();
}
// Method to display the distance entered by user
void show_dist()
{
// Displaying the distance in km, mts, and cm
System.out.println("The distance in kilometres, metres and centimetres: "+km+"km
"+mts+"m "+cm+"cm");
}
// Main method to create object of Add_Dist class and call methods

7
public static void main(String args[])
{
// Creating an object of Add_Dist class
Add_Dist ob = new Add_Dist();

// Calling get_dist method to get distance from user


ob.get_dist();

// Calling show_dist method to display the distance entered by user


ob.show_dist();
}
}

OUTPUT:

8
PROGRAM 2

QUESTION:

Write a class template ‘Display’ with the following specification:


Class: Display
Data members/Instance variables
Int a,b,c;
Member methods:
void Accept() : to accept the values of and b.
void Max() : to find greater of the two numbers ‘a’ and ‘b’ and store the result in c. Display
the result.
void Min() : to find smaller of the two numbers ‘a’ and ‘b’ and store the result in c. Display
the result.
void Diff() : to store the difference between ‘a’ and ‘b’ and store the result in c. Display the
result.
Write a main class to create an object of class ‘Display’ and call the member methods.

SOURCE CODE:

//A program to accept two numbers and find the greatest, smallest and the difference between
the two
// Importing the java.util package to use Scanner class for input
import java.util.*;
// Class declaration for Display
class Display
{
// Creating a Scanner object to read input
Scanner sc = new Scanner(System.in);
// Declaring instance variables to store two numbers and their difference
int a, b, c = 0;
// Method to accept two numbers from user
void Accept()
{
// Prompting user to enter two numbers
System.out.println("Enter two numbers");
// Reading input values for a and b
a = sc.nextInt();
b = sc.nextInt();
}
// Method to find the maximum of two numbers
void Max()
{
// Using Math.max method to find the maximum of a and b

9
c = Math.max(a,b);
// Displaying the greater number
System.out.println("The greater number: "+c);
}
// Method to find the minimum of two numbers
void Min()
{
// Using Math.min method to find the minimum of a and b
c = Math.min(a,b);
// Displaying the smaller number
System.out.println("The smaller number: "+c);
}
// Method to find the absolute difference between two numbers
void Diff()
{
// Using Math.abs method to find the difference between a and b
c = Math.abs((a-b));
// Displaying the difference between the two numbers
System.out.println("The difference between the two numbers: "+c);
}
// Main method to create object of Display class and call methods
public static void main(String args[])
{
// Creating an object of Display class
Display ob = new Display();
// Calling Accept method to get two numbers from user
ob.Accept();
// Calling Max method to find and display the greater number
ob.Max();
// Calling Min method to find and display the smaller number
ob.Min();
// Calling Diff method to find and display the difference between two numbers
ob.Diff();
}
}

10
OUTPUT:

11
PROGRAM 3

QUESTION:

Write a program in Java to enter a natural number. Display all the possible combinations
of consecutive natural numbers which adds up to give the sum equal to the original
number.
Sample input: 15
Sample output: 1, 2, 3, 4, 5 (i.e., 1 + 2 + 3 + 4 + 5 = 15)
4, 5, 6 (i.e., 4 + 5 + 6 = 15)
7, 8 (i.e., 7 + 8 = 15)

SOURCE CODE:

//To find the different combinations of the consecutive number equal to the original number
// Importing the java.util package to use Scanner class for input
import java.util.*;
public class Combination
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring variables
int i, j, k, n, sum;
// Creating a Scanner object to read input
Scanner sc = new Scanner(System.in);
// Prompting user to enter a number to print combination of consecutive numbers
System.out.println("Enter a number to print the combination of consecutive numbers");
System.out.println("Enter the number:");
// Reading input value for n
n = sc.nextInt();
// Loop to find and print combination of consecutive numbers
for(i=0;i<=n/2+1;i++)
{
sum=0;
for(j=i;j<=n/2+1;j++)
{
sum=sum+j;
if(sum==n)
break;
}
if(j<=n/2+1)
{

12
for(k=i;k<=j;k++)
System.out.print(k+" ");
System.out.println();
}
}
}
}

OUTPUT:

13
PROGRAM 4

QUESTION:

Write a program in Java to print ‘n’ number of terms of ‘Automorphic’ numbers, as


entered by the users as a response to: “Enter the number of terms of Automorphic
numbers to be displayed”
Enter number of terms:
6
Automorphic numbers are:
1
5
6
25
76
376

SOURCE CODE:

//To display Automorphic numbers


// Importing the java.util package to use Scanner class for input
import java.util.*;
public class Automorphic
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring variables
Scanner sc = new Scanner(System.in);
int n, i=1, j=0, i2, d=0, p;
double a, s;
// Prompting user to enter the number of Automorphic numbers to be displayed
System.out.println("How many Automorphic numbers are to be displayed?");
System.out.println("Enter number of terms");
// Reading input value for n
n = sc.nextInt();
// Prompting user that Automorphic numbers are to be displayed
System.out.println("Automorphic numbers are:");
// Loop to calculate and display Automorphic numbers
while(j<n)
{
// Calculating square of i
s=(int)(Math.pow(i,2));
i2=i;

14
d=0;
// Loop to count digits in i
while(i2>0)
{
i2/=10;
d++;
}
// Calculating power of 10 to the number of digits in i
a=(Math.pow(10,d));
p=(int)(s%a);
// Checking if i is equal to the last digits of s
if(i==p)
{
// Displaying the Automorphic number
System.out.println(i);
j++;
}
i++;
}
}
}

OUTPUT:

15
PROGRAM 5

QUESTION:

Write a menu driven program to perform the given task as per the User’s choice:
(i) To accept a Binary number (base 2) and convert it into its Decimal equivalent
(base 10).
Sample Input: (110011)2
Sample Output: (51)10
(ii) To input a Decimal number (base 10) and convert it into its Binary equivalent.
Sample Input: (35)10
Sample Output: (100011)2

SOURCE CODE:

//A menu driven program as per the user's choice


// Importing the java.util package to use Scanner class for input
import java.util.*;
public class Menu
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring variables
Scanner sc = new Scanner(System.in);
int ch;
// Prompting user to enter menu choices
System.out.println("Enter 1 to convert a binary number to its decimal equivalent");
System.out.println("Enter 2 to convert a decimal number to its binary equivalent");
System.out.println("Enter your choice");
// Reading input value for ch
ch = sc.nextInt();
// Creating switch case statements based on user's choice
switch(ch)
{
// Case 1 to convert binary to decimal
case 1:
int c=0,n;
double d=0,r;
// Prompting user to enter binary number
System.out.println("Enter binary numbers");
n = sc.nextInt();
// Loop to convert binary to decimal

16
while(n!=0)
{
r=n%10;
d=d+r*Math.pow(2,c);
n=n/10;
c=c+1;
}
// Displaying the decimal equivalent
System.out.println("The decimal equivalent = "+(int)d);
break;
// Case 2 to convert decimal to binary
case 2:
int r1;
String st="";
// Prompting user to enter a decimal number
System.out.println("Enter a number");
n = sc.nextInt();
// Loop to convert decimal to binary
while(n!=0)
{
r1=n%2;
st=Integer.toString(r1)+st;
n=n/2;
}
// Displaying the binary equivalent
System.out.println("The binary equivalent = "+st);
break;
// Default case
default:
System.out.println("Wrong choice!!");
}
}
}

17
OUTPUT:

18
PROGRAM 6

QUESTION:

A Circular Prime is a prime number that remains prime under cyclic shifts of its digits.
When the leftmost digit is removed and replaced at end of the remaining string of digits,
the generated number is still prime. The process is repeated until the original number is
reached again.
A number is said to be prime if it has only two factors 1 (one) and itself.

Example:
131
311
113
Hence, 131 is a circular prime.
Test your program with the sample data and some random data:

Example 1
Sample Input: N = 197
Sample Output:
197
917
791
197 is a Circular Prime.

Example 2
Sample Input: N = 29
Sample Output:
29
92
29 is not a Circular Prime

SOURCE CODE:

//A program to check circular prime number


// Importing the java.util package to use Scanner class for input
import java.util.*;
class CircularPrime
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring variables
Scanner sc = new Scanner(System.in);
int i, j, n, p, r1, r2, c=0, f=0;

19
// Prompting user to enter a number
System.out.println("Enter a number");
n = sc.nextInt();
// Prompting user that different combinations of Prime numbers will be displayed
System.out.println("The different combinations of Prime Numbers are:");
// Initialising variables for calculation
p=n;
c=0;
// Loop to count the number of digits in the input number
while(p>0)
{
p=p/10;
c++;
}
// Resetting value of p
p=n;
// Outer loop to handle circular permutations
outer:
for(i=1;i<=c;i++)
{
f=1;
// Loop to check if number is prime
for(j=2;j<p;j++)
{
if(p%j==0)
{
f=0;
break outer;
}
}
// If number is prime, display it and calculate the next circular permutation
if(f==1)
{
System.out.println(p);
r1=(int)(p/Math.pow(10,c-1));
r2=(int)(p%Math.pow(10,c-1));
p=r2*10+r1;
}
}
// Displaying whether the input number is a circular prime or not
if(f==0)
System.out.println("Not a circular prime");
else
System.out.println("Hence, "+n+" is a circular prime");

20
}
}

OUTPUT:

21
PROGRAM 7

QUESTION:

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 odd prime
pairs whose sum is equal to the number ‘N’.
Test your program with the following data and some random data:

Sample Input:
Enter an even number
14
Sample Output:
Prime pairs are
3 11
7 7

Sample Input:
Enter an even number
30
Sample Output:
Prime pairs are
7 23
11 19
13 17

Sample Input:
Enter an even number
17
Sample Output:
Invalid Input, Number is Odd

Sample Input:
Enter an even number
126
Sample Output:
Invalid Input, Out of Range

22
SOURCE CODE:

//A program to display odd prime pairs


// Importing the java.util package to use Scanner class for input
import java.util.*;
public class PrimePair
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring variables
Scanner sc = new Scanner(System.in);
int n, i, j, k=0, f;
int a[] = new int[50];
// Prompting user to enter an even number
System.out.println("Enter an even number");
// Reading input value for n
n = sc.nextInt();
// Creating conditional statements to check input validity
if(n%2!=0)
System.out.println("Invalid Input, Number is Odd");
else
if(n<=9 || n>=50)
System.out.println("Invalid Input, Out of Range");
else
{
// Loop to find all prime numbers up to n
for(i=2;i<=n;i++)
{
f=1;
for(j=2;j<i;j++)
{
if(i%j==0)
f=0;
}
if(f==1)
{
a[k++]=i;
}
}
// Displaying prime pairs that add up to n
System.out.println("Prime Pairs are");
for(i=0;i<k;i++)
{

23
for(j=i;j<k;j++)
{
if(a[i]+a[j]==n)
System.out.println(a[i]+"\t"+a[j]);
}
}
}
}
}

OUTPUT:

24
25
SET 2: Statements and Scope

26
PROGRAM 1

QUESTION:

A Smith number is a composite number, whose sum of the digits is equal to the sum of its
prime factors.
For example:
4, 22, 27, 58, 85, 94, 121 ……………………………… are Smith numbers.
Write a program in Java to enter a number and check whether it is a Smith number or not.
Sample Input:
666
Sum of the digits: 6 + 6 + 6 = 18
Prime factors are: 2, 3, 3, 37
Sum of the digits of the prime factors: 2 + 3 + 3 + (3 + 7) = 18
Thus, 666 is a Smith Number.

SOURCE CODE:

// Importing the java.util package to use Scanner class for input


import java.util.Scanner;
public class Smithnumber
{
int sumDig(int num) //method to find the sum of digits of the number
{
int sum=0;
while(num>0)
{
sum=sum+num%10;
num=num/10;
}
return sum;
}
int sumPrimeFact(int num) //method to find the sum of the prime factors
{
int i=2, sum=0;
while(num>1)
{
if(num%i==0)
{
sum=sum+sumDig(i);
num=num/i;
}
else
i++;

27
}
return sum;
}
public static void main(String args[]) // Main method where execution begins
{
// Creating a Scanner object to read input
Scanner sc = new Scanner(System.in);
Smithnumber obj = new Smithnumber(); //creating object of the class
System.out.println("Enter a Number : ");
int num = sc.nextInt();
int x=obj.sumDig(num); //calling methods on the objects
int y=obj.sumPrimeFact(num);
if(x==y) //output statements
System.out.println("Number is a Smith Number");
else
System.out.println("Number is not a Smith Number");
}
}

SOURCE CODE:

28
PROGRAM 2

QUESTION:

An Evil number is a positive whole number which has even number of 1’s in its binary
equivalent. Example: Binary equivalent of 9 is 1001, which contains even number of 1’s. A
few evil numbers are 3, 5, 6, 9….
Design a program to accept a positive whole number and find the binary equivalent of the
number and count the number of 1’s in it and display whether it is a Evil number or not
with an appropriate message.
Output the result in format given below:
Example 1:
Input: 15
Binary Equivalent: 1111
No. of 1’s: 4
Output: Evil Number
Example 2:
Input: 26
Binary Equivalent: 11010
No. of 1’s: 3
Output: Not an Evil Number

SOURCE CODE:

// Importing the java.util package to use Scanner class for input


import java.util.*;
public class Evilnumber
{
public static void main(String args[]) // Main method where execution begins
{
Scanner sc = new Scanner(System.in);
int num;
System.out.println("Enter a positive number");
num = sc.nextInt(); // Reading input value for n
if(num < 0) // Creating conditional statements to check input validity
{
System.out.println("Invalid Input");
return;
}
int c = 0, p = 0, bnum = 0;
while(num > 0) // Loop to count the number of 1's in the binary equivalent of the
number
{
int d = num%2;
if(d == 1)

29
c++;
bnum = (int)( bnum + (d*Math.pow(10,p)));
p++;
num = num/2;
}
System.out.println("Binary Equivalent: "+bnum);
System.out.println("No. of 1's: "+c);
if(c%2 == 0)
System.out.println("Evil Number"); //displaying the output based on the result of the
conditional statement
else
System.out.println("Not an Evil Number");
}
}

OUTPUT:

30
PROGRAM 3

QUESTION:

A number is said to be a Bouncy number, if the digits of the number are unsorted.
For example,
223344: 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 a number. Check and display whether it is a Bouncy
number or not.

SOURCE CODE:

// Importing the java.util package to use Scanner class for input


import java.util.Scanner;
public class Bouncynumber
{
public static void main(String args[]) // Main method where execution begins
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt(); // Reading input value for n
if (num < 100) // Creating conditional statements to check input validity
{
System.out.println(num + " is not a Bouncy Number.");
return;
}
// Declaring variables
int t = num;
boolean isIncreasing = true, isDecreasing = true;
int prev = t % 10;
while (t != 0) // Loop to check whether the digits are in ascending order
{
int d = t % 10;
if (d > prev)
{
isIncreasing = false;
break;

31
}
prev = d;
t /= 10;
}
t = num;
prev = t % 10;
while (t != 0) // Loop to check whether the digits are in descending order
{
int d = t % 10;
if (d < prev)
{
isDecreasing = false;
break;
}
prev = d;
t /= 10;
}
if (!isIncreasing && !isDecreasing)
System.out.println(num + " is a Bouncy Number."); //displaying the output based on
the result of the conditional statement
else
System.out.println(num + " is not a Bouncy Number.");
}
}

OUTPUT:

32
PROGRAM 4

QUESTION:

Write a program in Java to input a number and check whether it is a Pronic Number or
Heteromecic Number or not.
Pronic Number: A Pronic number, oblong number, rectangular number or heteromecic
number, is a number which is the product of two consecutive integers, that is, n*(n+1).
The first few Pronic numbers are:
0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462
…, etc.

SOURCE CODE:

// Importing the java.util package to use Scanner class for input


import java.util.*;
public class Pronicnumber
{
public static void main(String args[]) // Main method where execution begins
{
Scanner sc = new Scanner(System.in);
// Declaring variables
int num, i;
boolean k = false;
int p = 0;
System.out.println("Enter a number");
num = sc.nextInt(); // Reading input value for num
for(i=0;i<=num;i++) // Loop to check whether the given number is a Pronic number or
not
{
p=i*(i+1);
if(p==num)
{
k = true;
break;
}
}
if(k==true)
System.out.println("The number is a Pronic number"); //displaying the output based on
the result of the conditional statement

33
else
System.out.println("The number is not a Pronic number");
}
}

OUTPUT:

34
PROGRAM 5

QUESTION:

Write a program in Java to input a number and check whether it is a Fascinating Number
or not.
Fascinating Numbers: Some numbers of 3 digits or more exhibit a very interesting property.
The property is such that, when the number is multiplied by2 and 3, and both these products
are concatenated with the original number, all digits from 1 to 9 are present exactly once,
regardless of the number of zeroes.
Let’s understand the concept of Fascinating Number through the following example:
Consider the number 192
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
Concatenating the results: 192 384 576
It could be observed that ‘192384576’ consists of all digits from 1 to 9 exactly once.
Hence, it could be concluded that 192 is a Fascinating Number.
Some examples of Fascinating Numbers are: 192, 219, 273 327, 1902, 1920, 2019 etc.

SOURCE CODE:

// Importing the java.util package to use Scanner class for input


import java.util.Scanner;
// Declaring class Fascinatingnumber
public class Fascinatingnumber
{
public static void main(String args[]) // Main method where execution begins
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to check: ");
int num = sc.nextInt(); // Reading input value for num
if (num < 100) // Creating conditional statements to check input validity
{
System.out.println(num + " is not a Fascinating Number");
return;
}
// Declaring variables
int n2 = num*2;
int n3 = num*3;
boolean isFascinating = true;
String st=""+num+n2+n3;
for (char i = '1'; i <= '9'; i++) // Loop to check whether all digits from 1-9 are present in
the number
{
int p1 = st.indexOf(i);
int p2 = st.lastIndexOf(i);
if (p1==-1 || p1!=p2)
{

35
isFascinating = false;
break;
}
}
if (isFascinating == true) //displaying the output based on the result of the conditional
statement
System.out.println(num + " is a Fascinating Number");
else
System.out.println(num + " is not a Fascinating Number");
}
}

OUTPUT:

36
SET 3: String Manipulations

37
PROGRAM 1

QUESTION:

Write a program in Java to accept a String and display all the words present in the String
in Pig Latin form.
Example:
Sample Input: THE CAPITAL OF INDIA IS NEW DELHI
Sample Output: ETHAY APITALCAY OFAY INDIAAY ISAY EWNAY ELHIDAY

SOURCE CODE:

// To display a string in Pig Latin form


import java.util.*;
public class Piglatin
{
public static void main(String str) // Reading input value for String
{
StringTokenizer st = new StringTokenizer(str);
int x,y;
String str1,c,d;
char b;
System.out.println("The String in Pig Latin form");
while(st.hasMoreTokens())
{
str1=st.nextToken();
x=str1.length();
for(y=0;y<x;y++) // Loop to find the first vowel of the String
{
b=(str1.charAt(y));
if(b=='a'||b=='e'||b=='i'||b=='o'||b=='u'||b=='A'||b=='E'||b=='I'||b=='O'||b=='U')
break;
}
c=str1.substring(y,x); // Printing the String in Pig Latin format
d=str1.substring(0,y);
System.out.print(c+d+"AY"+' ');
}
}
}

38
OUTPUT:

39
PROGRAM 2

QUESTION:

Write a program in Java to accept a String and display the new String after encoding with
move = 2;
Sample Input: “ZEOLOGY”
Sample Output: BGQNQIA

SOURCE CODE:

// To display Encoded String


import java.util.*;
public class Encode
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
// Declaring data variables
int i,a,c=0;
String str;
char ch, chr=0;
System.out.println("Enter your String to be coded:"); // Reading the input value of String
str=sc.nextLine();
a=str.length(); // Calculating the length of the String
System.out.println("Encoded: 2");
System.out.println("Encoded String:");
for(i=0;i<a;i++) // For loop to shift each letter by 2
{
ch=str.charAt(i);
if((ch>='a'&&ch<='x')||(ch>='A'&&ch<='X'))
c=(int)(ch+2);
chr=(char)(c);
if((ch>='y'&&ch<='z')||(ch>='Y'&&ch<='Z'))
c=(int)(ch-24);
chr=(char)(c);
System.out.print(chr); // Output statement
}
}
}

40
OUTPUT:

41
PROGRAM 3

QUESTION:

Write a program (Using Scanner Class) to enter a token / word in a mixed case and display
the new token after deleting all the vowels. Finally arrange the new token in alphabetical
order of letters.
Sample Input: Computer
Sample Output: Cmptr
Final Output: Cmprt

SOURCE CODE:

// To display the tokens after deleting vowels


import java.util.*;
public class Dvowels
{
// Main method to test Scanner class
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
// Declaring data variables
int i,j,p,q;
char ch,ch1;
String st,st2="",st3="";
System.out.println("Enter a word:");
st=sc.next(); // Reading input value of String
p=st.length();
for(i=0;i<p;i++) // For loop to delete vowels from the String
{
ch=st.charAt(i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
continue;
st2=st2+ch;
}
System.out.println(" The new token formed after deleting vowels:" +st2);
q=st2.length();
for(i=65;i<=90;i++) // For loop to arrange the letters in alphabetical order
{
for(j=0;j<q;j++)
{
ch1=st2.charAt(j);
if(ch1==(char)i||ch1==(char)(i+32))
st3=st3+ch1;
}
}
System.out.println(" The new token after arranging in alphabetical order:" +st3);
}
}

42
OUTPUT:

43
PROGRAM 4

QUESTION:

Write a program in Java to accept any three-letter word and print all the probable three-
letter combinations. No letter should be repeated within the output.
Sample Input: TOP
Sample Output:
The required combinations of the word:
TOP
TPO
OTP
OPT
PTO
POT

SOURCE CODE:

// To display the three letters combinations


import java.util.*;
public class Combinations
{
public static void main(String args[])
{
// Declaring data variables
String str;
int i,j,k,p;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a three letter word");
str=sc.next(); // reading input value of String
p=str.length(); // Calculating the length of the String
System.out.println("The required combinations of the word:");
for(i=0;i<p;i++) // For loop to print the combinations of a three-lettered word
{
for(j=0;j<p;j++)
{
for(k=0;k<p;k++)
{
if(i!=j&&j!=k&&k!=i)
// Output statement to display the combinations of the word
System.out.print(str.charAt(i)+""+str.charAt(j)+""+str.charAt(k));
}
System.out.println();
}
}
}
}

44
OUTPUT:

45
PROGRAM 5

QUESTION:

Write a program that takes the coded text (less than 100 characters), the shift value and
prints the decoded original text. Your program must reject any non-valid shift. Assume all
characters are in upper case.
A simple encryption system uses a shifting process to hide a message. The value of the shift
can be in the range of 1 to 26 (Otherwise, error ‘Invalid Entry’ should appear).
For example, Shift 7 means that A = U, B = V, C = W and so on-------------------.
Text: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T
An extra space is added to the end of the String. To make things a little more difficult, spaces
within the original text are replaced with QQ before the text in encrypted. Double Q (QQ)
was selected because no English word ends with Q or QQ.
Additionally, the coded message is printed in blocks of six characters separated by spaces.
The last block might not contain six characters separated by spaces. The last block might not
contain six characters.
Input coded text: UHINBLKKQCHHYLKK
Shift: 7
Decoded Text: ANOTHER WINNER
Input coded text: RUIJGGEVGGBKSAGG
Shift: 11
Decoded Text: BEST OF LUCK
Input coded text: RUIJGGEVGGBKSAGG
Shift: 29
Output: Invalid Entry

SOURCE CODE:

// A program to perform simple encryption


import java.util.*;
public class Decode1
{
public static void main(String args[])
{
// Declaring data variables
int i,l,a=0,s;
String str1,str2="";
char chr;
Scanner sc = new Scanner(System.in);
System.out.println("Enter coded text"); // Reading input value of String
str1=sc.next();
System.out.println("Enter shift"); // Reading input value of shift
s=sc.nextInt();
if((s<1)||(s>26)) // Conditional statement to check the validity of shift
System.out.println("Invalid Entry");
else
{
l=str1.length(); // calculating the length of the String

46
for(i=0;i<l;i++) // Loop to decode each letter
{
chr=str1.charAt(i);
a=(int)chr+(s-1);
if((char)a=='Q')
{
if(str1.charAt(i+1)+(s-1)=='Q'&&i<l)
{
a=32;
i++;
}
}
if(a>90)
{
a=a-26;
}
str2=str2+(char)a;
}
System.out.println("Decoded Text: "+str2); // Output statement
}
}
}

OUTPUT:

47
PROGRAM 6

QUESTION:

Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only
(any other character may be ignored). The words may be separated by more than one blank
space and are in upper case.
Perform the following tasks:
(a) Accept the sentence and reduce all extra blank spaces between two words to a single
blank space.
(b) Accept a word from the user which is a part of the sentence along with its position
number and delete the word and display the sentence.
Example 1:
Input: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
Word to be deleted: IS
Word position in the sentence: 6
Output: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
Example 2:
Input: AS YOU SOW, SO SO YOU REAP.
Word to be deleted: SO
Word position in the sentence: 4
Output: AS YOU SOW, SO YOU REAP.
Example 3:
Input: STUDY WELL ##
Output: Invalid Sentence

SOURCE CODE:

// A program to delete a word as specified


import java.util.*;
class WordRemove
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
// Declaring data variables
String word,st1;
int i,t,n;
char ch;
System.out.println("Enter a sentence ending with (.) or (?) or (!)");
st1=sc.nextLine().toUpperCase(); // Reading the input value of the String
int l=st1.length();
ch=st1.charAt(l-1);
if(ch=='.'||ch=='?'||ch=='!') // Conditional statement to check the validity of the String
{
System.out.println("Enter the word to be removed");
word=sc.next(); // Reading the input value of the String
System.out.println("Enter position number of the word to be removed:");
n=sc.nextInt(); // Reading input value
StringTokenizer st =new StringTokenizer(st1); // Declaring StringTokenizer class

48
int count=0; String w=""; String fin="";
while(st.hasMoreTokens())
{
w=st.nextToken();
w=w.trim();
count++;
if(count==n)continue;
fin+=" "+w;
}
System.out.println("Sentence after removing word:");
System.out.println(fin); // Output statement
}
else
System.out.println("Invalid Sentence");
}
}

OUTPUT:

49
50
PROGRAM 7

QUESTION:

Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’
only. The words may be separated by more than one blank space and are in UPPER
CASE.
Perform the following tasks:
(a) Find the number of words beginning and ending with a vowel.
(b) Place the words which begin and end with a vowel at the beginning, followed by the
remaining words as they occur in the sentence.
Test your program with the sample data and some random data:
Example 1:
Input: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
Output: Number of words beginning and ending with a vowel = 3
ANAMIKA ARE ANYMORE SUSAN NEVER GOING TO QUARREL.

Example 2:
Input: YOU MUST AIM TO BE A BETTER PERSON TOMORROW THAN YOU ARE
TODAY.
Output: Number of words beginning and ending with a vowel = 2
A ARE YOU MUST AIM TO BE BETTER PERSON TOMORROW THAN YOU TODAY.

Example 3:
Input: LOOK BEFORE YOU LEAP.
Output: Number of words beginning and ending with a vowel = 0
LOOK BEFORE YOU LEAP.

Example 4:
Input: HOW ARE YOU@
Output: Invalid Input

SOURCE CODE:

// a program to place words which begins and ends with vowel


import java.util.*;
public class VowelWords
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
// Declaring data variables
String sent,s1="",s2="",s3="",s4="";
int n,i,t,p;
char d;
System.out.println("Enter a sentence in upper case terminated by a (.) or (?) or (!)");
sent=sc.nextLine(); // Reading input value of String
p=sent.length(); // Calculating length of the String
char c=sent.charAt(p-1);
if(c=='.'||c=='?'||c=='!') // Conditional statement to check the validity of the String

51
{
sent=sent.substring(0,p-1);
StringTokenizer s=new StringTokenizer(sent); // Declaring StringTokenizer class
n=s.countTokens();
t=0;
for(i=1;i<=n;i++)
{
s1=s.nextToken();
c=s1.charAt(0);
d=s1.charAt(s1.length()-1);
if((c=='A'||c=='E'||c=='I'||c=='O'||c=='U')&&(d=='A'||d=='E'||d=='I'||d=='O'||d=='U'))
{
s2=s2+' '+s1;
t++; // Count variable
}
else
s3=s3+' '+s1;
}
s4=s2+' '+s3;
// Displaying the output
System.out.println("Number of words beginning and ending with vowels = "+t);
System.out.println("The new sentence:");
System.out.println(s4);
}
else
System.out.println("Invalid Input");
}
}

OUTPUT:

52
53
PROGRAM 8

QUESTION:

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 a
vertical order, side by side with a horizontal tab (i.e., eight spaces).
Test your program with the following data and some random data:

Example 1: Example 2:
Input: N = 3 Input: N = 4
Team 1: Emus Team 1: Royal
Team 2: Road Rols Team 2: Mars
Team 3: Coyote Team 3: De Rose
Team 4: Kings
Output: Output:

E R C R M D K
m o o o a e i
u a y y r n
s d o a s R g
t l o s
R e s
o e
l
s
Example 3:
Input: N = 10
Output: Invalid Input

SOURCE CODE:

// a program to display name of the teams in vertical order


import java.io.*;
class TeamNames
{
public static void main()throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
// Declaring data variables
int n,i,j,max;
System.out.println("Enter number of teams");
n=Integer.parseInt(in.readLine()); // Reading value of 'n'
if(n<=2||n>=9) // Conditional statement to check the validity of 'n'
System.out.println("Invalid Input");
else
{
// Creating arrays to store the names and the length of the names of the teams

54
String name[] = new String[n];
int len[] = new int[n];
for(i=0;i<n;i++) // For loop to read the input values of the team names
{
name[i]=in.readLine();
len[i]=name[i].length();
}
max=0;
for(i=0;i<n;i++) // For loop to find the largest value of length
if(len[i]>max)
max=len[i];
for(i=0;i<max;i++) // Loops to display the team names
{
for(j=0;j<n;j++)
{
if(i<len[j])
System.out.print(name[j].charAt(i)+"\t");
else
System.out.print("\t");
}
System.out.println();
}
}
}
}

OUTPUT:

55
56
SET 4: Arrays

57
PROGRAM 1

QUESTION:

Write a program in Java to store 10 different numbers in a Single Dimensional Array.


Display the numbers after eliminating the duplicate numbers from the array.
Sample Input:

m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7] m[8] m[9]
69 45 45 25 34 40 34 41 29 16

Sample Output: The result after removing duplicating numbers:


m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7]
69 45 25 34 40 41 29 16

SOURCE CODE:

// To eliminate the duplicate numbers from a given set of numbers


import java.util.*;
public class Duplicate
{
// Main method where execution begins
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
int i,j;
int a[] = new int[10];
int b[] = new int[10];
System.out.println("Enter 10 numbers in the array: ");
for(i=0;i<10;i++)
{
a[i]=in.nextInt(); // Reading the input value of the array
}
for(i=0;i<10;i++) // Loop to find the repeated numbers
{
for(j=i+1;j<10;j++)
{
if(a[i]==a[j])
a[j]=0;
}
}
j=0;
for(i=0;i<10;i++)
{
if(a[i]!=0)
{
b[j]=a[i];

58
j=j+1;
}
}
// Displaying the newly formed array
System.out.println("The result after removing duplicating numbers :"); // Displaying the
array after removing the repeated numbers
for(i=0;i<j;i++)
System.out.print(b[i]+ " ");
}
}

OUTPUT:

59
PROGRAM 2

QUESTION:

Write a program in Java to accept a decimal number (base 10). Convert the decimal
number to a hexadecimal number and display the result.
Sample Input: (1998)10
Sample Output: (7CE)16
Sample Input: (2748)10
Sample Output: (ABC)16

SOURCE CODE:

// To convert a Decimal number to a Hexadecimal number


import java.util.*;
class DeciHexa
{
// Main method where execution begins
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
int i=0,c=0,n,r;
int ar[] = new int[20];
System.out.println("Enter a Decimal Number");
n=in.nextInt(); // Reading the input value from the user
System.out.println("The HexaDecimal equivalent of Decimal Number:" +n);
while(n>0) // Loop to convert into hexadecimal number
{
r=n%16;
ar[i]=r;
n=n/16;
i++;
c++;
}
for(i=c-1;i>=0;i--) // Output statement to display the hexadecimal number
{
if((ar[i]>=10)&&(ar[i]<=15))
{
if(ar[i]==10)
System.out.print("A");
if(ar[i]==11)
System.out.print("B");
if(ar[i]==12)
System.out.print("C");
if(ar[i]==13)
System.out.print("D");
if(ar[i]==14)

60
System.out.print("E");
if(ar[i]==15)
System.out.print("F");
}
else
System.out.print(ar[i]);
}
System.out.println();
}
}

OUTPUT:

61
PROGRAM 3

QUESTION:

Write a program which takes a string (maximum 80 characters) terminated by a full stop.
The words in this string are assumed to be separated by one or more blanks. Arrange the
words of the input string in the descending order of their lengths. Words having the same
length should be sorted alphabetically. Each word must start with an uppercase letter and
the sentence should be terminated by a full stop.
Test your program for the following data and some random data.
Sample Data:
Input:
This is the human resources department
Output:
Department Resources Human This The Is.
Input:
To handle yourself use your head and to handle others use your heart.
Output:
Yourself Handle Handle Others Heart Head You’re your And Use Use To To.

SOURCE CODE:

// To arrange the words in a sentence in descending order


import java.util.*;
class Sentence
{
// Main method where execution begins
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
String word[] = new String[50];
String str,temp="";
int a,i,j,k,n=0,c,len;
char ch;
System.out.println("Enter a sentence and terminated with a full stop");
str=in.nextLine(); // Reading the input value of the String
str=str.toLowerCase();
len=str.length();
for(a=0;a<len;a++) // For loop split the words of the sentence into an array
{
if(str.charAt(a)!=' '&&str.charAt(a)!='.')
{
temp=temp+str.charAt(a);
}
else
{
word[n++]=temp;
temp="";

62
}
} // end of loop
for(i=0;i<n-1;i++) // For loop to display the elements of the array in decreasing order of
their length
{
for(j=i+1;j<n;j++)
{
if(word[i].length()<word[j].length())
{
temp=word[i];
word[i]=word[j];
word[j]=temp;
}
if(word[i].length()==word[j].length())
{
if(word[i].compareTo(word[j])>0)
{
temp=word[i];
word[i]=word[j];
word[j]=temp;
}
}
} // end of j loop
} // end of i loop
System.out.println("The word present in the sentence arranged in descending order:");
for(k=0;k<n;k++) // For loop to convert the first letter into uppercase
{
ch=word[k].charAt(0);
ch=Character.toUpperCase(ch);
word[k]=ch+word[k].substring(1);
System.out.print(word[k]+" "); // Displaying the final sentence
} // end of k loop
System.out.print(".");
} // end of main functions
} // end of class

OUTPUT:

63
64
PROGRAM 4

QUESTION:

Write a program to input long integer data not less than 5 digits. Your program should
reject, if data is less than 5 digits and ask to re-enter the value. In the input, last four digits
will be taken as year (the validity of the year should be checked that the year should be in
the range from 1900 to 3000 both inclusive, otherwise the computer should reject the input
and ask to re-enter data again) and remaining digits as total number of days. Your
program should display the output as actual date (using number of days extracted)
followed by month name and actual year.
Test your program with the following data and some random data.
Sample Input: 272008
Sample Output: 27 January 2008
Sample Input: 802005
Sample Output: 21 March 2005
Sample Input: 2008
Sample Input: Invalid Data! Re-enter value not less than 5 digits
Sample Input: 652008
Sample Output: 5 March 2008

SOURCE CODE:

// To display the actual date, month and year


import java.util.*;
class Display1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
String month[] = {" ", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
int dm[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int i,j,d,c=0,days,y,date;
System.out.println("Enter a data value not less than 5 digits");
d=in.nextInt(); // Reading the input value from the user
while(d<10000||d%10000<1900||d%10000>3000) // Conditional statement to check the
validity of the integer
{
System.out.println("Invalid data! Re-enter value not less than 5 digits");
d=in.nextInt();
}
// Calculating the year and days
y=d%10000;
days=d/10000;
if(days>365) // Loop to find the date
{
while(days>365)

65
{
y++;
if(y%4==0)
{
dm[2]=9; // to check leap year
days=days-366;
}
else
{
dm[2]=28;
days=days-365;
}
}
}
else
{
if(y%4==0)
dm[2]=29;
else
dm[2]=28;
}
for(i=1;i<=12;i++)
{
c=c+dm[i];
if(c>days)
break;
} // end of i loop
c=0;
for(j=1;j<i;j++)
{
c=c+dm[j];
} // end of j loop
date=days-c;
System.out.println("The required date as per the entered data value:");
if(date==0)
System.out.println(dm[i-1]+" "+month[i-1]+" "+y);
else
System.out.println(date+" "+month[i]+" "+y);
} // end of main function
} // end of class

OUTPUT:

66
67
PROGRAM 5

QUESTION:

Given a time in numbers, we can convert it into words.


For 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 Five
5:45 Quarter to Six
5:47 Thirteen minutes to Six
Write a program which first inputs two integers, the first between 1 to 12 (both inclusive)
and second between 0 to 59 (both inclusive) and prints out the time they represent, in
words. Your program should follow the format of the above examples.
Sample Data
Input: Time: 3, 0
Output: 3:00 Three O’clock
Input: Time: 7,29
Output: 7:29 Twenty nine minutes past Seven
Input: Time: 6,34
Output: 6:34 Twenty six minutes to Seven
Input: Time: 12, 1
Output: 12:01 One minute past Twelve
Input: Time: 12,45
Output: 12:45 Quarter to One
Test your program for the data values in the given examples above and some random data.

SOURCE CODE:

// A program to display time as per User’s choice


import java.util.*;
class Time
{
// Main method where execution begins
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring the data variables
int hr,min,n;
String word[] =
{“One”,”Two”,”Three”,”Four”,”Five”,”Six”,”Seven”,”Eight”,”Nine”,”Ten”,”Eleven”,”Twel
ve”,”Thirteen”,”Fourteen”,”Fifteen”,”Sixteen”,”Seventeen”,”Eighteen”,”Nineteen”,”Twenty”
,”Twenty One”,”Twenty Two”,”Twenty Three”,”Twenty Four”,”Twenty Five”,”Twenty
Six”,”Twenty Seven”,”Twenty Eight”,”Twenty Nine”};
do
{

68
System.out.println(“Enter hours”);
hr=in.nextInt(); // Reading the input value of hour
System.out.println(“Enter minutes”);
min=in.nextInt(); // Reading the input value of minutes
if(hr>12||min>60) // Conditional statement to check the validity of the time
System.out.println(“Invalid time entered”);
else
if(min==0) // Displaying the time in words
System.out.println(hr+”:”+min+” means “+word[hr-1]+” O’clock”);
else
{
if(min==30)
System.out.println(hr+”:”+min+” means “+”Half past “+word[hr-1]);
else
{
if(min<30)
{
if(min==1)
System.out.println(hr+”:0”+min+” means “+word[min-1]+” minute past
“+word[hr-1]);
else if(min<10 && min>1)
System.out.println(hr+”:0”+min+” means “+word[min-1]+” minutes past
“+word[hr-1]);
else if(min==15)
System.out.println(hr+”:”+min+” means “+”Quater past “+word[hr-1]);
else
System.out.println(hr+”:”+min+” means “+word[min-1]+” minutes past
“+word[hr-1]);
}
else
{
if(min==45)
System.out.println(hr+”:”+min+” means “+”Quater to “+word[hr]);
else if(min==59)
System.out.println(hr+”:”+min+” means “+word[60-min-1]+” minute to
“+word[hr]);
else
System.out.println(hr+”:”+min+” means “+word[60-min-1]+” minutes to
“+word[hr]);
}
}
}
System.out.println(“Want to continue …..., Press 1 for ‘Yes’ and 0 for ‘No’”);
n=in.nextInt(); // Reading the input value of the user’s choice
}
while(n>0);
System.out.println(“Program Ends!”);
}
}

69
OUTPUT:

70
71
PROGRAM 6

QUESTION:

Write a program in Java to store the numbers in a 4 × 4 matrix in Double Dimensional


Array. Arrange the numbers of each row in ascending order and display the result.
Sample Input Sample Output

22 14 23 25 14 22 23 25

81 26 31 10 10 26 31 81

58 64 17 12 12 17 58 64

55 33 26 14 14 26 33 55

SOURCE CODE:

// To arrange the elements of each row in ascending order


import java.util.*;
public class Arranging
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring the data variables
int i,j,k,t;
int m[][] = new int[4][4];
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements in the first array of 4x4 matrix:");
for(i=0;i<4;i++) // Reading input value of the matrix
{
for(j=0;j<4;j++)
{
m[i][j]=in.nextInt();
}
}
System.out.println("The elements of first 4x4 matrix are:");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
System.out.print(m[i][j]+" ");
}
System.out.println();
}
for(i=0;i<4;i++) // Nested for loop to re-arrange the elements of the rows in ascending
order

72
for(j=0;j<3;j++)
{
for(k=0;k<3-j;k++)
{
if(m[i][k]>m[i][k+1])
{
t=m[i][k];
m[i][k]=m[i][k+1];
m[i][k+1]=t;
}
}
}
System.out.println("The elements after arranging each row in ascending order:");
for(i=0;i<4;i++) // Displaying the re-arranged matrix
{
for(j=0;j<4;j++)
{
System.out.print(m[i][j]+" ");
}
System.out.println();
}
}
}

OUTPUT:

73
74
PROGRAM 7

QUESTION:

A square matrix is the matrix in which number of rows is equal to the number of columns.
Thus, a matrix of order n*n is called a Square Matrix.
Write a program in Java to fill the numbers in a circular fashion (clockwise) with natural
numbers from 1to n2, taking n as an input.
For example: if n = 4, then n2 = 16, then the array is filled as:

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

SOURCE CODE:

// To display the elements of a square matrix in circular fashion


import java.util.*;
class Circular_Matrix
{
// Main method where execution begins
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
int n,r1,r2,c1,c2,k=1,i,j;
System.out.println("Enter the size of the matrix");
n=in.nextInt(); // Reading the input value of 'n'
int a[][] = new int[n][n];
c1=0;c2=n-1;r1=0;r2=n-1;
do // Loop to store the elements of the matrix in circular order
{
for(i=c1;i<=c2;i++)
{
a[r1][i]=k;
k++;
}
for(j=r1+1;j<=r2;j++)
{
a[j][c2]=k;
k++;
}
for(i=c2-1;i>=c1;i--)
{

75
a[r2][i]=k;
k++;
}
for(j=r2-1;j>=r1+1;j--)
{
a[j][c1]=k;
k++;
}
c1++;c2--;r1++;r2--;
}
while(k<=n*n);
// Output statement displaying the matrix
System.out.println("Circular matrix is listed below:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}

OUTPUT:

76
77
PROGRAM 8

QUESTION:

A square matrix is said to be a magic square, if the sum of each row, each column and each
diagonal is same. Write a program to enter an integer number N. Create a magic square of
size N × N. Finally, print the elements of the matrix as magic square.
The program runs for a sample data as:
Enter matrix dimension of a magic square:
Enter number of rows only for a magic square:
4
Magic square of size 4 × 4 as shown below:

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

Enter matrix dimension of a magic square:


Enter number of rows only for a magic square:
5
Magic square of size 5 × 5 as shown below:

17 24 1 8 15

23 5 7 14 16

4 6 13 20 22

10 12 19 21 3

11 18 25 2 9

SOURCE CODE:

// A program on Magic square


import java.util.*;
class Magic_Square
{
// Main method where execution begins

78
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
int i,j,k,n,t;
System.out.println("Enter matrix dimension of a magic square:");
System.out.println("Enter number of rows only of a magic square:");
n=in.nextInt(); // Reading the input value of 'n'
int a[][] = new int[n][n];
// Initialising double dimensional array
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
a[i][j]=0;
}
// Storing the elements of a magic square having odd number of rows and columns
if(n%2!=0)
{
i=0;j=n/2;k=1;
while(k<=n*n)
{
a[i][j]=k++;
i--;j++;
if(i<0&&j>n-1)
{
i=i+2;
j--;
}
if(i<0)
i=n-1;
if(j>n-1)
j=0;
if(a[i][j]>0)
{
i=i+2;
j--;
}
}
}
// Storing the elements of a magic square having even number of rows and columns
else
{
k=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
a[i][j]=++k;
}
j=n-1;
for(i=0;i<n/2;i++)

79
{
t=a[i][i];
a[i][i]=a[j][j];
a[j][j]=t;
t=a[i][j];
a[i][j]=a[j][i];
a[j][i]=t;
j--;
}
}
// Output statement to display the magic square
System.out.println("Magic square of size "+n+"x"+n+" as shown below:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}

OUTPUT:

80
81
PROGRAM 9

QUESTION:

Declare a square matrix A[][] of order M × M where ‘M’ is the number of rows and the
number of columns, such that M must be greater than 2 and less than 10. Accept the value of
M from the user. Display an appropriate message for an invalid input. Allow the user to input
integers into this matrix, perform the following tasks:
(a) Display the original matrix.
(b) Rotate the matrix 90º clockwise as shown below:
Original Matrix Rotated Matrix

1 2 3 7 4 1

4 5 6 8 5 2

7 8 9 9 6 3

(c) Find the sum of the elements of the four corners of the matrix.
Test your program for the following data and some random data:

Example 1: Input: M = 3
Original Matrix Matrix after Rotation

1 2 3 7 4 1

4 5 6 8 5 2

7 8 9 9 6 3

Sum of corner elements = 20

Example 2: Input: M = 4
Original Matrix Matrix after Rotation

1 2 4 9 3 1 2 1

2 5 8 3 7 6 5 2

1 6 7 4 6 7 8 4

3 7 6 5 5 4 3 9

Sum of corner elements = 18

Example 3:

82
Input: M = 14
Output:
Size out of Range

SOURCE CODE:

// a program to rotate the Matrix Elements


import java.util.*;
class RotateMatrix
{
// Main method where execution begins
public static void main(String args[])
{
// Declaring data variables
int m,i,j,s=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the matrix dimension");
m=in.nextInt(); // Reading the input value of 'm'
if(m>2&&m<10)
{
int a[][] = new int[m][m];
System.out.println("Enter matrix elements");
for(i=0;i<m;i++) // For loop to read the input value of the matrix
{
for(j=0;j<m;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.println("Original Matrix"); // Output statements to display the original
matrix
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
System.out.println("Matrix after Rotation");
for(i=0;i<m;i++) // For loop to rotate the matrix through 90 degrees
{
for(j=m-1;j>=0;j--)
{
if(i==0&&j==0||i==0&&j==m-1||i==m-1&&j==0||i==m-1&&j==m-1)
s=s+a[i][j]; // Sum of the corner elements
System.out.print(a[j][i]+"\t"); // Output statement to display the re-arranged
matrix
}

83
System.out.println();
}
System.out.println("Sum of the corner elements = "+s); // Output statement to display
the sum of corner elements of the matrix
}
else
System.out.println("Size out of range");
}
}

OUTPUT:

84
85
86
87
PROGRAM 10

QUESTION:

Write a program to declare a square matrix A[][] of order (M × M) where ‘M’ must be
greater than 3 and less than 10. Allow the user to input positive integers into this matrix.
Perform the following tasks on the matrix:
(a) Sort the non-boundary elements in ascending order using any standard sorting technique
and rearrange them in the matrix.
(b) Calculate the sum of both the diagonals.
(c) Display the original matrix, rearranged matrix and only the diagonal elements of the
rearranged matrix with their sum.
Test your program with the sample data and some random data:
Example 1:
Input: M = 4
Output:
Original Matrix Rearranged Matrix

9 2 1 5 9 2 1 5

8 13 8 4 8 3 6 4

15 6 3 11 15 8 13 11

7 12 23 8 7 12 23 8

Output:
Original Matrix Diagonal Elements

9 2 1 5 9 5

8 13 8 4 3 6

15 6 3 11 8 13

7 12 23 8 7 8

Sum of the diagonal elements = 59

SOURCE CODE:

// a program to sort non-boundary Matrix Elements


import java.util.*;
class SortNon_Boundary
{

88
// Main method where execution begins
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
// Declaring data variables
int m,i,j,k,s,sd,t;s=0;
System.out.println("Enter value of 'm' which is greater than 3 and less than 10");
m=in.nextInt(); // Reading the input value of 'm'
System.out.println("Enter positive values in matrix");
if((m>3)&&(m<10))
{
int a[][] = new int[m][m];
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
a[i][j]=in.nextInt();
} // end of j loop
} // end of i loop
System.out.println("Original Matrix"); // Output statement to display the original
matrix
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
s=((m-2)*(m-2));
int b[] = new int[s];
k=0;
for(i=1;i<(m-1);i++)
{
for(j=1;j<(m-1);j++)
{
b[k]=a[i][j];
k++;
}
}
t=0;
for(i=0;i<s;i++)
{
for(j=i+1;j<s;j++)
{
if(b[i]>b[j])
{
t=b[j];
b[j]=b[i];
b[i]=t;

89
}
}
t=0;
}
k=0;
for(i=1;i<(m-1);i++)
{
for(j=1;j<(m-1);j++)
{
a[i][j]=b[k];
k++;
}
}
System.out.println("Re-arranged Matrix"); // Output statement to display the re-
arranged matrix
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
sd=0;
System.out.println("Diagonal Elements"); // Output statement to display only the
diagonal elements
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
if((i==j)||((i+j)==(m-1)))
{
sd=sd+a[i][j];
System.out.print(a[i][j]+" ");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
// Output statement to display the sum of the diagonal elements of the re-arranged
matrix
System.out.println("Sum of diagonal elements = "+sd);
}
else
{
System.out.println("The Matrix Size is out of Range");
}

90
}
}

OUTPUT:

91
92
SET 5: Methods (Functions)

93
PROGRAM 1

QUESTION:

A class ‘Telcall’ calculates the monthly phone bill of a consumer. Some of the details of the
class are given below:
Class name: Telcall
Data members/instance variables:
phno : Phone number
name : Name of consumer
n : Number of calls made (integer)
amt : Bill amount
Member functions/methods:
telcall(String x, String y, int k): Parametrized constructor to assign values to data members
void compute(): To calculate the phone bill amount based on the slab given below.
Number of calls: Rate
1 – 100: ₨. 500/- rental charge only
101 – 200: Rs. 1.00/- per call + rental charge
201 – 300: Rs. 1.20/- per call + rental charge
above 300: Rs. 1.50/- per call + rental charge
void display(): To display the details in the specified format.
Specify the class Telcall, giving the details of the constructors, void compute() and void
display().
In the main function, create an object of type telcall and display the phone bill in the
following format:
Phone number Name Total calls Amount
xxxxxxxxxxx xxxxx xxxxxxxx xxxxxxx

SOURCE CODE:

// A program to calculate the monthly telephone bill of a consumer


import java.util.*;
class Telcall
{
String name,phno;
int n;
double amt;
Telcall() // Initialising data variables
{
name="";
phno="";
n=0;
amt=0.0;
}
void accept(String nm,String ph,int nc) // Method to accept data variables
{
name=nm;
phno=ph;
n=nc;

94
}
void compute() // Method to calculate telephone bills
{
if(n<=100)
amt=500.00;
if(n>=101&&n<=200)
amt=500.00+(double)(n-100)*1.00;
if(n>=201&&n<=300)
amt=500.00+(double)(n-200)*1.20;
if(n>300)
amt=500.00+(double)(n-300)*1.50;
}
void display() // Method to display name, phone number, telephone bill and no. of calls
{
System.out.println("Phone Number \t\t Name \t\t No.of calls \t\t Amount");
System.out.println(phno+"\t\t"+name+"\t\t"+n+"\t\t Rs."+amt);
}
}
class Telephone
{
public static void main(String args[]) // Main method where execution begins
{
Scanner in = new Scanner(System.in);
String nm,ph;
int nc;
Telcall ob = new Telcall();
System.out.println("Enter name");
nm=in.nextLine();
System.out.println("Enter Phone Number");
ph=in.next();
System.out.println("Enter number of calls");
nc=in.nextInt();
ob.accept(nm,ph,nc);
ob.compute();
ob.display();
}
}

OUTPUT:

95
PROGRAM 2

QUESTION:

An integer number is said to be a special number, if sum of factorials of all its digits is equal
to the number itself.
For example, consider the number 145. Sum if its factorials is
= 1! + 4!+ 5!
= 1 + 24 + 120
= 145
So, 145 is a special number.
A class ‘Special’ is declared with following details:
Class name: Special
Data members/instance variables:
arr[] : A single dimensional array of long integers of maximum
size <= 150.
N : Integer to store actual size of array <= 150.
Member functions/methods:
Special(): A constructor to store 0 in each memory location of array arr[0].
Special(int nx): A constructor to assign nx to N as actual size of array
long fact(long g): To return factorial of g.
void input_numbers(): To enter integers in the array arr[] of size N.
void print_special(): To read the numbers one by one from arr[] and print only those
numbers which are special in nature along with a suitable message.
Specify the class Special by giving details of constructors and methods. Write a main method
to find the solution of the above problem.
After Execution:
Enter the size of array <= 150: 5
Enter a Number 234
Enter a Number 134
Enter a Number 145
Enter a Number 256
enter a Number 145
The Output:
145 is a Special Number
145 is a Special Number

SOURCE CODE:

// A program to display the special numbers


import java.util.*;
class Special
{
// Creating an array to store integers
int ar[] = new int[150];
int n,i;
Special() // initialising elements of the array
{
for(i=0;i<150;i++)

96
ar[i]=0;
}
Special(int nx) // to define array size
{
n=nx;
}
void input_numbers() // Accepting the values of the elements of the array
{
Scanner in = new Scanner(System.in);
for(i=0;i<n;i++)
{
System.out.println("Enter a number");
ar[i]=in.nextInt();
}
}
long fact(long g) // Method to calculate the factorial
{
long f=1;
int j;
for(j=1;j<=g;j++)
f=f*j;
return(f);
}
void print_special() // Method to check whether the number is a special number
{
long s,d,k,num;
for(i=0;i<n;i++)
{
s=0;
num=ar[i];
while(num!=0)
{
d=num%10;
k=fact(d);
s=s+k;
num=num/10;
}
if(s==ar[i]) // Output statement
{
System.out.println(ar[i]+" is a special number");
}
} // end of i loop
} // end of print_special()
}

97
OUTPUT:

98
PROGRAM 3

QUESTION:

A class Sorter contains an array of 100 integers. Some of the member functions/methods of
Sorter are given below:
Class name: Sorter
Data member/instance variables: Any array of 100 integers
Member functions/methods:
Sorter(): Constructor
void readlist(): To input 100 integers.
void displaylist(): To display the list of sorted integers.
int indexofmin(int startindex): Returns the index/subscript of the smallest integer in the array,
between the start index and the last index.
void selectionsort(): Sorts the array in ascending order using the selection sort technique.
Specify the class Sorter giving the details of the constructor and the functions void
displaylist(), int indexofmin(int startindex), void selectionsort(). You may assume that the
other functions are written for you. You do not need to write the main function.

SOURCE CODE:

// A program to display the sorted integers using selection sort


import java.util.*;
class Sorter
{
int ar[] = new int[100];
int n,i;
Sorter() // Initialising the array
{
for(i=0;i<100;i++)
ar[i]=0;
}
Sorter(int nx) // to define array size
{
n=nx;
}
void read_list() // Method to input the elements of the array
{
Scanner in = new Scanner(System.in);
for(i=0;i<n;i++)
{
System.out.println("Enter a number");
ar[i]=in.nextInt();
}
}
void displaylist() // Method to display the sorted list
{
System.out.println("The sorted list: ");
for(i=0;i<n;i++)

99
{
System.out.print(ar[i]);
System.out.println();
}
}
int indexofmin(int startindex) // Method to calculate the smallest integer
{
int min=startindex;
int j;
for(j=startindex+1;j<n;j++)
{
if(ar[j]<ar[min])
min=j;
}
return(min);
}
void selectionsort() // Method to sort the elements of the array in ascending order
{
int temp,m;
for(i=0;i<n-1;i++)
{
m=indexofmin(i);
temp=ar[i];
ar[i]=ar[m];
ar[m]=temp;
} // end of i loop
}
}

OUTPUT:

100
101
PROGRAM 4

QUESTION:

A class Myarray contains an array of n integers (n<=100) that are already arranged in
ascending order. The subscripts of the array elements vary from 0 to n-1. Some of the
member functions/methods of Myarray are given below:
Class name: Myarray
Data members/instance variables:
arr : An array of n integers.
n : Size of the array.
Member functions/methods:
Myarray(): Constructor to initialize 0 in each memory location of the array arr[].
void readarray(): Read n integers that are arranged in ascending order.
void displayarray(): Display n integers.
int binarysearch(int value): Searches for the ‘value’ in the array using the binary search
technique. It returns the subscript of the array element if the value is found, otherwise it
returns -999.
Specify the class Myarray giving the details of the void displayarray() and int binary
search(int value) only. You may assume that the other functions/methods are written for you.
You do not need to write the main function.

SOURCE CODE:

// A program to perform Binary Search on a set of integers


import java.util.*;
class Myarray
{
int ar[] = new int[100];
int n,i;
Myarray(int nm) // to define the size of array
{
n=nm;
for(i=0;i<100;i++)
ar[i]=0;
}
void readarray() // to input the values of the elements
{
Scanner in = new Scanner(System.in);
for(i=0;i<n;i++)
{
System.out.println("Enter a number");
ar[i]=in.nextInt();
}
}
void displayarray() // to display the array
{

102
System.out.println("Elements of the array are: ");
for(i=0;i<n;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
int binary_search(int value) // arranging the elements in ascending order using binary
search
{
// Data variables
int lb,ub,mid,found=0,ret;
lb=0;
ub=n-1;
mid=0;
while(found==0&&lb<=ub)
{
mid=(lb+ub)/2;
if(value<ar[mid])
ub=mid-1;
if(value>ar[mid])
lb=mid+1;
if(value==ar[mid])
found=1;
}
if(found==1)
ret=value;
else
ret=-999;
return(ret);
}
}

OUTPUT:

103
104
PROGRAM 5

QUESTION:

An integer number is said to be a magic number, if the eventual sum of digits of the number
is 1.
For example, let the number be 289.
By adding 2+8+9 gives 19,
then add 1+9, it gives 10,
then add 1+0, it gives result 1.
So, 289 is a magic number.
A class Magic is declared with the following details:
Class name: Magic
Data members/instance variables:
ar[] : A single dimensional array of long integers of maximum
size <=150.
n : (integer) To store actual size of array.
Member functions/methods:
Magic(): A constructor to store 0 in each memory location of array num[]
Magic(int nx): A constructor to assign nx to n as actual size of array.
void input_numbers(): To enter integers in the array num[] of size n.
void find_print_magic(): To read the numbers one by one from num[] and print only those
numbers which are magic numbers along with suitable message.
Specify the class Magic by giving details of constructor and all functions. You don’t need to
write main() method.

SOURCE CODE:

// A program to display the magic numbers


import java.util.*;
class Magic
{
int ar[] = new int[150];
int n,i;
Magic() // Initialising the array
{
for(i=0;i<150;i++)
ar[i]=0;
}
Magic(int nx) // to define array size
{
n=nx;
}
void input_numbers() // to input the elements of the array
{
Scanner in = new Scanner(System.in);
for(i=0;i<n;i++)
{

105
System.out.println("Enter a number");
ar[i]=in.nextInt();
}
}
void find_print_magic() // to check whether the number is a magic number or not
{
int p,s=0,d;
for(i=0;i<n;i++)
{
p=ar[i];
while(p>9)
{
s=0; // flag variable
while(p>0)
{
d=p%10;
s=s+d;
p=p/10;
}
p=s;
}
if(s==1)
{
System.out.println(ar[i]+" is a magic number");
}
} // end of i loop
} // end of print_magic()
}

OUTPUT:

106
PROGRAM 6

QUESTION:

A class Sum_rowcol is declared as follows:


Class name: Sum_rowcol
Data members/instance variables:
mat[20][20] : Double dimensional integer array.
m, n : (integers) Number of rows and number of columns
mat[][].
Member functions/methods:
void row_col(int mx,int nx): To assign mx to m and nx to n.
void raedrow_col(): To read matrix mat[][] of m × n.
void display_mat(): To print the matrix of m × n order row-wise.
void sum_mat(): To store sum of all the rows and columns in the matrix mat[][] and Print the
newly created matrix.

10 15 16 18 10 15 16 18 59

15 14 12 11 15 14 12 11 52

11 12 16 17 11 12 16 17 56

12 10 14 16 12 10 14 16 52

Sample Input 48 51 58 62

Sample Output

Specify the class Sum_rowcol giving the details of the functions void row_col(int mx, int nx),
void readrow_col(), void display_mat() and void sum_mat(). The main function need not to
be written.

SOURCE CODE:

// A program to display the sum of rows and column elements in a Double Dimensional Array
import java.util.*;
class Sum_rowcol
{
int mat[][] = new int[20][20];
int m,n,i,j;
Sum_rowcol() // Initialising the array
{
for(i=0;i<20;i++)
for(j=0;j<20;j++)
{
mat[i][j]=0;
}

107
}
void row_col(int mx,int nx) // to define array size
{
m=mx;
n=nx;
}
void read_row_col() // method to accept the values of the elements
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number one by one in a matrix: ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
mat[i][j]=in.nextInt();
}
}
void display_mat() // method to display the array elements
{
System.out.println("Elements of the matrix are: ");
for(i=0;i<=m;i++)
{
for(j=0;j<=n;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
void sum_mat() // method to calculate the sum of rows and columns
{
int c,r;
for(i=0;i<m;i++)
{
r=0;
for(j=0;j<n;j++)
{
r=r+mat[i][j];
}
mat[i][n]=r;
}
for(i=0;i<n;i++)
{
c=0;
for(j=0;j<m;j++)
{
c=c+mat[j][i];
}
mat[m][i]=c;
}
}

108
}

OUTPUT:

109
PROGRAM 7

QUESTION:

Design a class called Change to convert a decimal number into its equivalent number in base
16 and vice-versa.
For example, (i) The decimal number 35 is 23 in base 16.
(ii) The decimal number 107 is 6B in base 16.
Some of the members of the class Change are as follows:
Class name: Change
Data members/instance variables:
a[] : An integer array.
n : Integer to be convert to base 16.
Member functions/methods:
Change(): Constructor to initialize 0 to instance variables.
void input(): To accept an integer to be converted to base 16.
void hexadeci(String str): To convert hexadecimal number back to decimal form.
void decihexa(): To convert decimal integer ‘n’ to hexadecimal form.
Specify the class Change giving the details of the constructor and functions void input(), void
hexadeci(String str) and void decihexa(). The main function need not to be written.

SOURCE CODE:

// A program to convert a decimal number to an equivalent hexadecimal number and vice-


versa
import java.util.*;
class Change
{
// Creating an array
int a[] = new int[50];
int n,i;
Change() // Intialising an array
{
for(i=0;i<50;i++)
{
a[i]=0;
}
n=0;
}
void input() // Accepting the values of the array elements
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a decimal number ");
n=in.nextInt();
}
void decihexa(String str) // to convert hexadecimal number back to decimal form
{
int a=0,len,p=0,k=0;

110
double d=0.0,s=0.0;
String str1="";
char ch;
len=str.length();
p=len;
for(i=0;i<len;i++)
{
ch=str.charAt(i);
if(ch>='A')
{
k=(int)ch-55;
}
else
{
str1=str1+ch;
k=Integer.parseInt(str1);
str1="";
}
d=Math.pow(16,(p-1))*k;
s=s+d;
p--;
}
System.out.print("The decimal equivalent of Hexadecimal Number: "+str+" is ");
System.out.print((int)s);
}
void hexadeci() // to convert decimal integer tp hexadecimal form
{
int i=0,c=0,r,t;
String str2="";
System.out.print("The Hexadecimal equivalent of Decimal Number: "+n+" is ");
while(n>0)
{
r=n%16;
a[i]=r;
n=n/16;
i++;
c++;
}
for(i=c-1;i>=0;i--)
{
if(a[i]>=10)
{
t=a[i]-10;
t=65+t;
str2=str2+(char)t;
}
else
str2=str2+(char)(48+a[i]);
}
System.out.print(str2);

111
System.out.println();
decihexa(str2);
}
}

OUTPUT:

112
PROGRAM 8

QUESTION:

Write a program to use a class with the following specifications:


Class name: StringOP
Data members/instance variables:
str, rev : Variables to store strings
Member methods/functions:
StringOP(): Constructor to initialize the variables.
void input(): To store a sentence in str.
void process(): To reverse string str and store the reversed string in rev. Also print both the
strings.
void find(): Make use of StringTokenizer class to find the number of words and blanks
available in the string input from the console.
Use a main class to call the functions shown above.

SOURCE CODE:

// A program to display String Operations


import java.util.*;
class StringOP
{
String str,rev;
StringOP() // Initialising data variables
{
str="";
rev="";
}
void input() // Accepting the value of String
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence");
str=in.nextLine();
}
void process() // Calculating the reverse of the String
{
char b;
int i,p;
p=str.length();
for(i=p-1;i>=0;i--)
{
b=str.charAt(i);
rev=rev+b;
}
System.out.println("The reverse sentence: "+rev);
}
void find() // Finding the number of words and spaces in the sentences
{

113
int w;
StringTokenizer st = new StringTokenizer(str);
w=st.countTokens();
System.out.println("Number of words in sentence: "+w);
System.out.println("Number of spaces in sentence: "+(w-1));
}
public static void main(String args[]) // Execution begins
{
StringOP ob = new StringOP();
ob.input();
ob.process();
ob.find();
}
}

OUTPUT:

114
PROGRAM 9

QUESTION:

Design a class Exchange to accept a sentence and interchange the first letter with the last
letter of each word in the sentence, the word with single letter will remain unchanged. The
words in the input sentence are separated by a single blank space and terminated by a full
stop.
Example: Input : It is a warm day.
Output : t Isi a marw yad
Some of the members of the class are given below:
Class name: Exchange
Data members/instance variables:
sent : stores the sentence
rev : stores the new sentence
size : stores the length of the sentence
Member functions/methods:
Exchange(): default constructor
void readsentence(): to accept the sentence
void exfirstlast(): extract each word and interchange its first and last letters. From a new
sentence rev using the changed words
void display(): display the original sentence along with the new changed sentence
Specify the class Exchange giving the details of the constructor(), void readsentence(), void
exfirstlast() and void display(). Define the main() function to create an object and call the
functions accordingly to enable the task.
SOURCE CODE:
// A program to exchange the first and last letters of each word of a sentence
import java.util.*;
class Exchange
{
String sent,rev;
int size;
Exchange() // Initialsing the data variables
{
sent="";
rev="";
size=0;
}
void readsentence() // Accepting the value of String
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence to reverse the words: ");

115
sent=in.nextLine();
}
void exfirstlast() // Interchanging the first and last character of each String
{
String s="",st;
int l;
char c;
size=sent.length();
for(int i=0;i<size;i++)
{
c=sent.charAt(i);
if(c!=' '&&c!='.')
s=s+c;
else
{
l=s.length();
if(l>1)
{
st=s.charAt(l-1)+s.substring(1,l-1)+s.charAt(0);
rev=rev+' '+st;
}
else
rev=rev+' '+s;
s="";
}
}
}
void display() // Displaying the Original String along with the Reversed String
{
System.out.println("Original String:");
System.out.println(sent);
System.out.println("Reversed String:");
System.out.println(rev);
}
public static void main(String args[]) // Execution begins

116
{
Exchange ob = new Exchange();
ob.readsentence();
ob.exfirstlast();
ob.display();
}
}
OUTPUT:

117
PROGRAM 10

QUESTION:

A class Mixer has been defined to merge two sorted integer arrays in ascending order. Some
of the details of the class are given below:
Class name: 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/method:
Mixer(int nm): Constructor to assign n=nm
void accept(): to accept the elements of the array in ascending order without any duplicates
Mixer mix(Mixer A): to merge the current object’s array elements with the parametrized
array elements and return the resultant object
void display(): to display the elements of the array.
Specify the class Mixer, giving details of constructor(int), void accept(), Mixermix(Mixer)
and void display(). Define the main() function to create an object and call the function
accordingly to enable the task.

SOURCE CODE:

// A program to merge two sorted integer arrays in ascending order


import java.util.*;
class Mixer
{
// Creating an array
int arr[];
int n;
Scanner in = new Scanner(System.in);
Mixer(int nn) // to define array size
{
n=nn;
arr=new int[n];
}
void accept() // to accept the value of the elements of the array
{
System.out.println("Enter elements of both the arrays one by one in ascending order:");
for(int i=0;i<n;i++)
arr[i]=in.nextInt();
}
Mixer mix(Mixer A) // to merge the arrays
{
Mixer t = new Mixer(n+A.n);
for(int i=0;i<A.n;i++)
t.arr[i]=A.arr[i];
for(int j=0;j<n;j++)
t.arr[A.n+j]=arr[j];
return(t);

118
}
void display() // to display the merged arrays
{
System.out.println("Merged elements:");
for(int i=0;i<n;i++)
System.out.println(arr[i]);
}
public static void main(String args[]) // Execution begins
{
Mixer ob1 = new Mixer(3);
Mixer ob2 = new Mixer(4);
Mixer ob3 = new Mixer(7);
// Calling on the methods
ob1.accept();
ob2.accept();
ob3=ob2.mix(ob1);
ob3.display();
}
}

OUTPUT:

119
SET 6: Recursion

120
PROGRAM 1

QUESTION:

Write a program to input a number and reverse the digits of the number by using recursive
function. Display the new number.

SOURCE CODE:

// A program to reverse a number by using Recursive function


import java.util.*;
class Reverse
{
public static int rev(int n,int r)
{
if(n==0)
return(r);
else
{
r=r*10+n%10;
return(rev(n/10,r));
}
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to be reversed");
int num=in.nextInt();
int res=rev(num,0);
System.out.println("Number after reversing the digits\t" +res);
}
}

OUTPUT:

121
PROGRAM 2

QUESTION:

Write a program to input a decimal number (base 10) and convert it into its binary
equivalent by using recursive function. Display the binary number.

SOURCE CODE:

// A program to convert a decimal number into its binary equivalent by using Recursive
function
import java.util.*;
class Binary
{
public static int recbin(int n,String s)
{
if(n==0)
return(Integer.parseInt(s));
else
{
s=Integer.toString(n%2)+s;
return(recbin(n/2,s));
}
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a decimal number to be converted into binary");
int num=in.nextInt();
int res=recbin(num,"");
System.out.println("Binary equivalent of decimal number\t" +res);
}
}

OUTPUT:

122
PROGRAM 3

QUESTION:

Array. Enter a number and search whether the number is present among the set of numbers or
not by using Binary search technique. If the number is present then display a message
“Element is found” otherwise, display “Element is not found”. Perform the task by using
Recursive technique.

SOURCE CODE:

// A program to perform Binary search by using Recursive function


import java.util.*;
class B_Search
{
public static int bsearch(int x[],int l,int h,int ele,int f)
{
//x[] Array containing elements
//ele is element to be searched
//l and h are lower and upper boundary correspondingly
//f is the flag to set 1 if number is found
int mid;
mid=(l+h)/2;
if(l>h||f==1)
return(f);
else
{
if(ele==x[mid])
f=1;
if(ele<x[mid])
h=mid-1;
if(ele>x[mid])
l=mid+1;
return(bsearch(x,l,h,ele,f));
}
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter size of array");
int n=in.nextInt();
int a[] = new int[n];
System.out.println("Enter array elements");
for(int i=0;i<n;i++)
a[i]=in.nextInt();
System.out.println("Enter element to be searched");
int k=in.nextInt();
int l=0,h=n-1;

123
int f=0;
int res=bsearch(a,l,h,k,f);
if(res==1)
System.out.println("Element is found");
else
System.out.println("Element is not found");
}
}

OUTPUT:

124
PROGRAM 4

QUESTION:

The factorial of a number ‘n’ is calculated as:


n! = n*(n-1)*(n-2)*(n-3)*--------------------------------------*1.
A class Factorial is declared with the following details:
Class name: Factorial
Data members/instance variables:
n : to store a number (integer type) greater than zero
f : to store the factorial of a number entered by the user
Member functions/methods:
Factorial(): a constructor to assign 0 to n
int fact(int num): to find and return the factorial of num (num>0) using recursive technique
otherwise, it should return 1 if num=0
void get(int x): to assign x to n and by invoking function fact() store the factorial of n into f.
Display the result with a suitable message. Write the main() method to create an object to
class Factorial and call the function get(int).

SOURCE CODE:

// A program to display the factorial of a number


import java.util.*;
class Factorial
{
int n,f;
Factorial()
{
int n=0;
f=0;
}
int fact(int num)
{
n=num;
if(n==0)
return(1);
else
return(n*fact(n-1));
}
void get(int x)
{
n=x;
f=fact(n);
System.out.println("The factorial of "+x+" is "+f);
}
public static void main(String args[])
{
int m;
Scanner in = new Scanner(System.in);

125
System.out.println("Enter a number for its factorial");
m=in.nextInt();
Factorial ob = new Factorial();
ob.get(m);
}
}

OUTPUT:

126
PROGRAM 5

QUESTION:

A class Prime_Series defines a recursive function to find the prime numbers from a list of
data. The details of the class are given below:
Class name: Prime_Series
Data members/instance variables:
limit : to store the limit of the integers
arr[] : to create an integer array (maximum size 150)
Member functions/methods:
Prime_Series(): constructor to assign() to limit and arr[]
void readlist(): to accept the limit and input the integers in array arr[] up to the limit.
int(IsPrime, int q): to check n is prime or not, using Recursive Technique. If prime then the
function returns 1, otherwise 0.
void PrintPrime(): to display prime numbers from the array[] by invoking int IsPrime() up to
the given limit.
Specify the class Prime)_Series giving the details of the constructor, void readList(), int
IsPrime(int num, int j, int f) and void PrintPrime(). The main function need not to be written.

SOURCE CODE:

// A program to display prime numbers from a list of data


import java.util.*;
public class Prime_Series
{
Scanner in = new Scanner(System.in);
int limit;
int arr[] = new int[150];
Prime_Series()
{
int i;
for(i=0;i<150;i++)
{
arr[i]=0;
}
}
void readList()
{
int j;
System.out.println("Enter the number of elements to store:");
limit=in.nextInt();
System.out.println("Enter the elements:");
for(j=0;j<limit;j++)
{
arr[j]=in.nextInt();
}
}
int Isprime(int num,int j,int f)

127
{
if(j==num)
return(f);
else
{
if(num%j==0)
f=0;
return(Isprime(num,++j,f));
}
}
void PrintPrime()
{
int v;
for(int i=0;i<limit;i++)
{
v=Isprime(arr[i],2,1);
if(v==1)
System.out.println("Number "+arr[i]+" is prime");
}
}
}

OUTPUT:

128
PROGRAM 6

QUESTION:

A class Admission uses an array to contain admission numbers of 10 students. Some of the
data members/member functions are given below:
Class name: admission
Data members/instance variables:
admno[] : integer array to store admission numbers of 10 students
Member functions/methods:
admission(): constructor to initialize the array elements
void fillArray(): to accept the elements of the array in ascending order
int binSearch(int l, int u, int y): to search for a particular admission number (v) using binary
search and recursive technique returns 1 if found otherwise returns -1.
Specify the class admission giving details of the constructor, void fillArray() and int
binSearch(int l, int u, int y). Define the main() function to create the object and call the
functions accordingly to enable the task.

SOURCE CODE:

// A program to make binary search a particular admission number by using recursive


technique
import java.util.*;
class admission
{
int admno[] = new int[10];
Scanner in = new Scanner(System.in);
admission()
{
for(int i=0;i<10;i++)
admno[i]=0;
}
void fillArray()
{
System.out.println("Enter array elements in ascending order");
for(int i=0;i<10;i++)
admno[i]=in.nextInt();
}
int binSearch(int l,int u,int y)
{
int i=(l+u)/2;
if(l>u)
return -1;
else
{
if(y<admno[i])
return binSearch(l,i-1,y);

129
else if(y>admno[i])
return binSearch(i+1,u,y);
else return 1;
}
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
admission ob = new admission();
ob.fillArray();
System.out.println("Enter year to be searched");
int val=in.nextInt();
int k=ob.binSearch(0,9,val);
if(k==1)
System.out.println("Admission number Found");
else
System.out.println("Admission number not Found");
}
}

OUTPUT:

130
PROGRAM 7

QUESTION:

A disarium number is a number in which the sum of digits to the power of their respect
position is equal to the number itself.
Example: 135 = 11 + 32 + 53
Hence, 135 is a disarium number.
Design a class Disarium to check if a given number is a disarium number or not. Some of the
details of the class are given below:
Class name: Disarium
Data members/instance variables:
int num : stores the number
int size : stores the size of the number
Member methods/functions:
Disarium(int nn): Parametrized constructor to initialize the data members n=nn and size=0
void countdigit(): counts the total number of digits and assigns it to size
int sumofdigits(int n, int p): returns the sum of the digits of the number (n) to the power of
their respective positions (p) using recursive technique.
void check(): checks whether the number is a disarium number and displays the result with
an appropriate message.
Specify the class Disarium giving the details of the constructor(), void countDigit(), int
sumofdigits(int, int) and void check(). Define the main function to create an object and call
the functions accordingly to enable the task.

SOURCE CODE:

// A program to display Disarium number


import java.util.*;
class Disarium
{
int num;
int size;
Disarium(int nm)
{
num=nm;
size=0;
}
void countdigit()
{
int p=num;
while(p>0)
{
p=p/10;
size++;
}
}
int sumofdigits(int n,int p)
{

131
int d,sum=0;
for(int i=p-1;i>=0;i--)
{
d=n/(int)(Math.pow(10,i));
sum=sum+(int)(Math.pow(d,p-i));
n=n%(int)(Math.pow(10,i));
}
return sum;
}
void check()
{
if(sumofdigits(num,size)==num)
System.out.println("Disarium Number");
else
System.out.println("Not a Disarium Number");
}
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int no=in.nextInt();
Disarium ob = new Disarium(no);
ob.countdigit();
ob.check();
}
}

OUTPUT:

132
PROGRAM 8

QUESTION:

A class Palin has been defined to check whether a positive number is a palindrome number or
not.
The number ‘N’ is palindrome if the original number and its reverse are same.
Some of the details of the class are given below:
Class name: Palin
Data members/instance variables:
num : Integer to store the number
revnum : Integer to store the reverse of the number
Methods/Member functions:
Palin(): constructor to initialize data members with legal initial values
void accept(): to accept the number
int reverse(int y): reverses the parametrized argument ‘y’ and stores it in ‘revnum’ using
recursive technique.
void check(): checks whether the number is a palindrome or not by invoking the function
reverse() and display the result with an appropriate message.
Specify the class Palin giving details of the constructor(), void accept(), int reverse(int) and
void check(). Define the main() function to create an object and call the functions accordingly
to enable the task.

SOURCE CODE:

// A program to reverse a number by using recursive technique


import java.util.*;
class Palin
{
int num;
int revnum;
Scanner in = new Scanner(System.in);
Palin()
{
num=0;
revnum=0;
}
void accept()
{
System.out.println("Enter a number");
num=in.nextInt();
}
int reverse(int y)
{
if(y==0)
return revnum;
else
{
revnum=revnum*10+y%10;

133
return reverse(y/10);
}
}
void check()
{
if(num==reverse(num))
System.out.println(num+" is a palindrome number");
else
System.out.println(num+" is not a palindrom number");
}
public static void main()
{
Palin ob = new Palin();
ob.accept();
ob.check();
}
}

OUTPUT:

134
SET 7: Inheritance, Interfaces
and Polymorphism

135
PROGRAM 1

QUESTION:

Define a class basePro and a derived class dervPro to find the product of two numbers. The
details of both the classes are given below:
Class name: basePro
Data members/instance variables:
n1, n2 : float variables whose product is to be determined.
Member methods/functions:
void enter(): to input values of n1 and n2.
void show(): to display the values of n1 and n2.
Class name: dervPro
Data members/instance variables:
result : float variable to store product.
Member methods/functions:
void prod(): to accept values of n1 and n2 and to calculate their product using concept of
Inheritance.
void disp(): to display the values of n1, n2 and their product.
(a) Specify the class basePro giving details of the function void enter() and void show().
(b) Using Concept of Inheritance, specify the class dervPro by giving details of the
functions void prod() and void disp(). The main function and algorithm need not
to be written

SOURCE CODE:

// base class
import java.util.*; /* This program is based on single inheritance */
public class basePro // declaration of base class
{
float n1,n2; // these are data members of the base class
public void enter() // function definition to input n1, n2
{
Scanner sc = new Scanner(System.in); // making scanner object 'sc'
System.out.println("Input first number: ");
n1=sc.nextFloat(); // input float value in n1
System.out.println("Input second number: ");
n2=sc.nextFloat(); // input float value in n2
} // end of the function enter() of the base class
public void show() // function definition to print values
{
System.out.println("Number 1 = "+n1);
System.out.println("Number 2 = "+n2);
} // end of the function show() of the base class
} // end of the base class or super class

136
// derived class
import java.util.*;
class dervPro extends basePro // making the Derived or subclass to inherit base Pro
{
float result; // this is the data member of the derived class
public void prod() // function definition of derived class
{
enter(); // calling function enter() from base class to input n1, n2 inside function prod()
result=n1*n2; // finding the product of n1, n2
} // end of the function prod() of the derived class
public void disp() // function definition of derived class
{
show(); // calling function show() from base class to print n1, n2 inside function disp()
System.out.println("The product = "+result);
} // end of the function disp() of the derived class
// main function within the derived class
public static void main(String args[])
{
dervPro obj = new dervPro(); // creation of object 'obj' of derived class 'dervPro'. This
object
// is able to execute members of derived class and base class due to concept of
inheritance
obj.prod(); // call function prod() from derived class that inherits enter() from base class
System.out.println("OUTPUT "); // printing message or heading
obj.disp(); // call function disp() from derived class that also inherits function show()
from base class
} // end of main() function
} // end of the derived class dervPro

OUTPUT:

137
PROGRAM 2

QUESTION:

Define a super class Info and a sub-class Salary to find the total salary of an employee. The
details of both the classes are given below:
Class name: Info
Data members/instance variables:
name : to store the name of the employee.
sal : to store the salary of the employee in decimals.
Member methods/functions:
void Accept(): to input name and salary of the employee.
void show(): to display the data members.
Class name: Salary
Data members/instance variables:
allowance : to store the allowance in decimals.
total : to store the total salary in decimals.
Member methods/functions:
void compute(): to calculate allowance as 11% of the salary (sal) if salary is less than
20000.00 otherwise no allowance. Also calculate the total salary including allowance.
void display(): to print name, salary along with allowance and total salary.
Using Concept of Inheritance, specify the class Salary by giving details of the functions
void compute() and void display(). The main function and algorithm need not to be
written

SOURCE CODE:

// base class
import java.util.*;
public class Info
{
String name;
double sal;
public void Accept()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the employee");
name=sc.next();
System.out.println("Enter the salary of the employee");
sal=sc.nextDouble();
}
public void show()
{
System.out.println("Name of the employee: "+name);
System.out.println("Salary of the employee: "+sal);
}
}

138
// derived class
import java.util.*;
class Salary extends Info // making the Derived class using details of base class & its own
{
double allowance,total; // these are data members of the derived class
void compute() // definition of derived class function
{
if(sal<20000.00)
allowance=sal*0.11; // calculation of 11% allowance from sal
else
allowance = 0.0;
total=sal+allowance; // calculation of total salary
} // end of the function compute() of the derived class
void display() // definition of derived class function
{
show(); // calling function show() from base class to print name and salary
System.out.println("The allowance = "+allowance);
System.out.println("The total salary = "+total);
} // end of function display() of the derived class
public static void main(String args[])
{
Salary obj = new Salary();
obj.compute();
obj.display();
}
}

OUTPUT:

139
PROGRAM 3

QUESTION:

A super class Bank contains details account holder, such as name and account number while
a sub-class Deposit defines amount to make a fixed deposit. The details of both the classes
are given below:
Class name: Bank
Data members/instance variables:
nam : String to store the name of the account holder.
AccNo :long integer data to store the account number.
Member methods/functions:
Bank(long x, String na): parametrized constructor to assign AccNo=x and nam=na.
void display(): to print the details of the instance variables.
Class name: Deposit
Data members/instance variables:
amt : double type variable to store the amount for fixed
deposit.
Member methods/functions:
Deposit(double q): parametrized constructor to invoke super class constructor and initializes
the data member amt = q.
void showDetails(): to display the data members of both the classes.
(a) Specify the class Bank giving details of constructors and function void display().
(b) Using Concept of Inheritance, specify the class Deposit by giving details of the
constructors and function void showDetails(). Write a main() function to create a
suitable object and call the functions accordingly.

SOURCE CODE:

// base class
import java.io.*;
class Bank // definition of base or super class
{
// instance variables of super or base class
String nam;
long AccNo;
Bank(long x,String na) // parametrized constructor of super class
{
// assign value of 'na' to 'nam' and assign value of 'x' to 'AccNo'
nam=na;
AccNo=x;
} // end of the parametrized constructor of the base class Bank
void display() // function definition to print data
{
System.out.println("Name of account holder\t: "+nam);
System.out.println("Account number\t: "+AccNo);
} // end of the function display() of the base class

140
} // end of the base class

// derived class
import java.io.*;
class Deposit extends Bank // making Derived or sub class that inherits super class Bank
{
double amt; // instance variable of derived class
Deposit(long x,String na,double q) // parametrized constructor of derived class
{
super(x,na); // this statment inherits parametrized constructor of base class and passes
// values of 'x' to 'AccNo' and 'na' to 'nam'. This is constructor inheritance.
amt=q; // assign value of 'q' to 'amt' i.e. to data member of derived class Deposit
} // end of the parametrized constructor of derived class
void showDetails() // function definition to print data
{
display(); // call or inherit the function from base class to print the data members
System.out.println("Fixed deposit amount\t: "+amt);
} // end of the function showDetails() of the derived class
} // end of the derived class Deposit
class result // this is a separate class to create main() function and to invoke functions
{
public static void main(String args[]) // main() function definition
{
Deposit obj = new Deposit(12243,"Mr. XYZ",75000.0); // creation of object of derived
class by
// passing 12243 to 'x', "Mr. XYZ" to 'na' and 75000.0 to 'q'
System.out.println("Account details: ");
obj.showDetails(); // call function of derived class to print data of both the classes
} // end of main() functiom
} // end of the class result

OUTPUT:

141
PROGRAM 4

QUESTION:

A super class Override defines an integer variable while a sub-class Derive defines a double
precision variable. The details of both the classes are given below:
Class name: Override
Data members/instance variables:
x : integer variable
Member methods/functions:
Override(int q): parametrized constructor to assign x = q.
void Display(): to display the value of the data member with suitable message.
Class name: Derive
Data members/instance variables:
h : double precision variable.
Member methods/functions:
Derive(….): parametrized constructor to assign values to the instance variables of both the
classes.
void Display(): to display values of h and x by invoking suitable function.
(a) Specify the class Override giving details of constructors and function void
Display().
(b) Using Concept of Inheritance, specify the class Derive by giving details of the
constructors and function void Display(). Write a main() function to create a suitable
object and call the functions accordingly.

SOURCE CODE:

// base class
import java.util.*;
class Override // this is base class
{
int x; // data member of base class
Override(int q) // parametrized constructor present in base class
{
x=q; // assign 'q' to 'x'
} // end of the parametrized constructor
void Display() // function definition of base class
{
System.out.println("The value of base class X = "+x);
} // end of the function Display() of the base class
} // end of the base class

// derived class
import java.io.*;
public class Derive extends Override // defining the derived class that inherits Override
{
double h; // data member of derived class

142
Derive(int q,double p) // paramterized constructor of derived class
{
super(q); // this statement inherits or invokes the parametrized constructor of base class
h=p; // assign 'p' to data member of derived class 'h'
} // end of parametrized constructor of derived class
void Display()
{
// function definition of derived class, see that the same function is defined
// in the super or base class also. This is function overriding
super.Display(); // this statement invokes function of base class using keyword super
// this is the process to overcome function overriding
System.out.println("The value of derived class H = "+h);
} // end of the function Display()
} // end of the derived class
class Test // making a separate class to define main() function
{
public static void main(String args[]) // main() function starts here
{
Derive mat = new Derive(81,56.2); // creation of object 'mat' of derived class and
// passes 81 to q and 56.2 to p
mat.Display(); // This invokes function of derived class as well as the function of base
class
} // end of the main() function
} // end of the class Test

OUTPUT:

143
PROGRAM 5

QUESTION:

A super class FindMax is defined to find largest from two integers and a sub-class
FindGreat is defined to find the largest from three integers. The details of both the classes
are given below:
Class name: FindMax
Data members/instance variables:
m, n : integers to store numbers.
Member methods/functions:
FindMax(int nx, int ny): constructor to assign m = nx and n = ny.
int GetMax(int x, int y): to find and return the greatest integer from x and y.
Class name: FindGreat
Data members/instance variables:
z : integer to store a number.
Member methods/functions:
FindGreat(….): parametrized constructor to assign the actual values to the data members of
both the classes.
int GetMax(int q, int r, int s): to find and return greatest integer from q, r, and s.
void Show(): by invoking overloaded functions GetMax(..), print the greatest from the two
and three integers using data members m,n and z.
(a) Specify the class FindMax giving details of constructors and function int
GetMax(int,int).
(b) Using Concept of Inheritance, specify the class FindGreat by giving details of the
constructors and function int GetMax(int, int, int) and void Show(). Write a main()
function to create a suitable object and call the functions accordingly to print the
greatest from the two and three integers.

SOURCE CODE:

// base class
import java.util.*;
public class FindMax{ int m, n;
FindMax(){ m = 0;
n = 0;
}
int GetMax(int x, int y){ m = x; n = y;
return Math.max(m, n);
}
}

// derived class
import java.io.*;
public class FindGreat extends FindMax
{ int x, y, z;
FindGreat()

144
{
x = 0; y = 0; z = 0;
}
int GetMax(int q, int r, int s)
{
x = q; y = r; z = s;
if (x>y&&x>z) return x; else if (y>x&&y>z) return y; else return z;
}
public static void main(){
FindGreat obj = new FindGreat();
int n1 = 2, n2 = 5, n3 = 15;
int p = obj.GetMax(n1, n2);
int d = obj.GetMax(n1, n2, n3);
System.out.println("Greatest from " + n1 + " and " + n2 + " is " + p);
System.out.println("Greatest from " + n1 + ", " + n2 + " and " + n3 + " is " + d);
}
}

OUTPUT:

145
PROGRAM 6

QUESTION:

Define an abstract type super class Sphere and a sub-class Area with details given below:
Class name: Sphere (Abstract type)
Data members/instance variables:
radius : to store radius in decimals.
Member methods/functions:
Sphere(double r): parametrized constructor to initialize data member radius = r.
abstract void ComputeArea(): an abstract function declaration.
abstract void ComputeVolume(): an abstract function declaration.
Class name: Area
Data members/instance variables:
area : to store area of sphere.
vol : to store volume of sphere.
Member methods/functions:
Area(….): parametrized constructor to assign data members of both classes.
abstract void ComputeArea(): to find and print the area of sphere using area = 4𝝿r2.
abstract void ComputeVolume(): to find and print the volume of sphere using area = 4/3𝝿r3
(a) Specify the class Sphere giving details of constructors and abstract methods.
(b) Using Concept of Inheritance, specify the class Area by giving details of the
constructors and abstract methods void ComputeArea() and void
ComputeVolume(). Write a main() function to create an object and call methods.

SOURCE CODE:

// base class
import java.io.*;
abstract class Sphere // defining abstract type super or base class
{
double radius; // data members of super class
Sphere(double r) // parametrized constructor of super or base class
{
radius=r; // assign actual value to the data members of super class
} // end of the parametrized constructor of base class
abstract void ComputeArea(); // declaration of abstract function terminated by semicolon
abstract void ComputeVolume(); // declaration of abstract function terminated by
semicolon
} // end of the abstract base class

// derived class
import java.io.*;
class Area extends Sphere // making Derived class that inherits abstract class Sphere
{
double area,vol; // data member of the derived class

146
Area(double r) // parametrized constructor of derived class
{
super(r); // calling parametrized constructor of super class or base class
area=0.0;
vol=0.0;
} // end of the parametrized constructor of the derived class
void ComputeArea() // first abstract function definition
{
area=4*3.141*(radius*radius);
System.out.println("Area of sphere = "+area);
} // end of the abstract function ComputeArea()
void ComputeVolume() // second abstract function definition
{
vol=(4/3)*3.141*(radius*radius*radius);
System.out.println("Volume of sphere = "+vol);
} // end of the abstract function ComputeVolume()
} // end of the derived class
class Result // separate class to create main() and the object of derived class
{
public static void main(String args[])
{
Area obj = new Area(6.5); // making object of the derived class and also calls
constructor
System.out.println("Output");
obj.ComputeArea(); // calling abstract function declared in super and defined in sub
class
obj.ComputeVolume(); // calling abstract function declared in super and defined in sub
class
} // end of the main() function
} // end of the class Result

OUTPUT:

147
PROGRAM 7

QUESTION:

An interface Marks is defined which initializes marks of three subjects of mid-term


examination (Hm1, Hm2, Hm3) and marks of three subjects of final examination (Fm1,
Fm2, Fm3) and a method void GetTotal() to find and print the total marks of respective
examinations.
Create the classes MidTerm and Final which implement the interface Marks. These have
attributes which reflects total marks term wise.
The details of the members of the interface and both the classes are given below:
Interface name: Marks
Data members/instance variables:
Hm1, Hm2, Hm3 : to store marks of three subjects in mid-term examination.
Fm1, Fm2, Fm3 : to store marks of three subjects in final examination.
Member methods/functions:
void GetTotal(): to calculate the total marks of mid-term examination.
Class name: MidTerm
Data members/instance variables:
total_mid_term : to store the total marks of mid-term examination.
Member methods/functions:
void GetTotal(): to find and print the total marks of mid-term examination.
Class name: Final
Data members/instance variables:
total_final : to store the total marks of final examination.
Member methods/functions:
void GetTotal(): to find and print the toal marks of final examination
(a) Specify the interface Marks giving details of the data members and abstract method
void GetTotal().
(b) Using Concept of Inheritance, specify the classes MidTerm and Final giving the
details of the abstract method void GetTotal().
Also define a main() function to create an object and call the methods accordingly to enable
the task.

SOURCE CODE:

// base class
import java.io.*;
interface Marks // defining interface class
{
int Hm1=86,Hm2=90,Hm3=75; // initializes marks of mid term examintaion
int Fm1=79,Fm2=96,Fm3=80; // intializes marks of final examination
void GetTotal(); // declaration of abstract method within interface
} // end of interface class

// derived class
import java.io.*;

148
abstract class MidTerm implements Marks // Super class MidTerm that implements interface
Marks
{
int total_mid_term; // data members of the super class
public void GetTotal() // abstract function definition within super class
{
total_mid_term=Hm1+Hm2+Hm3; // finding total of mid term examination
System.out.println("Total marks of mid-term examination = "+total_mid_term);
} // end of the function GetTotal of super class
} // end of the super class MidTerm

// derived class
import java.io.*;
class Final extends MidTerm implements Marks // making sub-class which extends super
// class MidTerm and implements interface Marks
{
int total_final; // data members of the sub class
public void GetTotal() // abstract function definition within super class
{
total_final=Fm1+Fm2+Fm3; //finding total of final examination
super.GetTotal(); // calling super class function using super keyword
System.out.println("Total marks of final examination = "+total_final);
} // end of the function GetTotal() of sub class
} // end of the sub class Final
// separate class to make main() function and call the functions
class output
{
public static void main(String args[])
{
Final obj = new Final(); // making of object of sub-class Final that extends super class
// MidTerm and both implements interface Marks
obj.GetTotal(); // calling function of sub-class Final which also links with other classes
} // end of the main() function
} // end of the class output

OUTPUT:

149
SET 8: Data Structures

150
PROGRAM 1

QUESTION:

A stack is a linear data structure which enables the user to add and remove integers from one
end only i.e. on the TOP, using the concept of LIFO (Last In First Out). Define a class Stack
with the following details:
Class name: Stack
Data members/instance variables:
stk[] : integer array to hold maximum 50 elements.
cap : integer to store the maximum size of the array/stack.
top : integer to point the index of the topmost element of the
stack.
Member functions/methods:
Stack(int nm): parametrized constructor to initialize cap = nm and top = -1.
void Push(int num): to push or insert argument num at the top location, if possible, otherwise
display a message “Stack overflow”.
void Pop(): to pop or remove an integer from the top of the stack, if possible, otherwise
display a message “Stack underflow”.
Specify the class Stack giving details of the constructor the functions void Push(int), void
Pop() and void display(). Write a main() function to create an object and call the functions
accordingly to enable the task.

SOURCE CODE:

import java.io.*;
class Stack
{
int stk[] = new int[50],cap,top;
Stack(int nn)
{
cap=nn;
top=-1;
}
void Push(int num)
{
if(top==cap)
System.out.println("Stack Overflow, element cannot be pushed....");
else
{
top++;
stk[top]=num;
}
}
void Pop()
{
if(top==-1)
System.out.println("Stack Underflow, element cannot be popped.... ");
else

151
{
int temp=stk[top];
top--;
System.out.println("The Popped or deleted integer is = "+temp);
}
}
void display()
{
if(top==-1)
System.out.println("Stack Underflow, element cannot be printed.... ");
else
{
System.out.println("The elements in the stack are as below: ");
for(int j=top;j>=0;j--)
System.out.println(stk[j]);
}
}
public static void main(String args[])
{
Stack obj = new Stack(4);
obj.Push(12);
obj.Push(56);
obj.Push(7);
obj.display();
obj.Pop();
obj.display();
}
}

OUTPUT:

152
PROGRAM 2

QUESTION:

An interface StackOperations is defined with methods void Push(int num) to push integer
num at the top index and void Pop() to remove the element from the top i.e. uses LIFO or
FIFO principle.
Create a class Stack which implements interface StackOperations. This class contains data
members, constructors and methods to perform push and pop operations and print the
elements of the stack.
The details members of interface and class are given below:
Interface name: StackOperations
Member functions/methods:
void Push(int num): to push or insert argument num at the top index
void Pop(): to pop or remove an integer from the top of the stack.
Class name: Stack
Data members/instance variables:
stk[] : integer array to hold maximum 50 elements.
cap : integer to store the maximum size of the array/stack.
top : integer to point the index of the topmost element of the
stack.
Member functions/methods:
Stack(int nm): parametrized constructor to initialize cap = nm and top = -1.
void Push(int num): to push or insert argument num at the top location, if possible, otherwise
display a message “Stack overflow”.
void Pop(): to pop or remove an integer from the top of the stack, if possible, otherwise
display a message “Stack underflow”.
Specify the interface StackOperations giving declaration of methods void Push(int num)
and void Pop(). Using the concept of inheritance, specify the class stack giving details of the
constructor the functions void Push(int), void Pop() and void display(). Write a main()
function to create an object and call the functions accordingly to enable the task.

SOURCE CODE:

import java.io.*;
interface StackOperations
{
void Push(int num);
void Pop();
}
import java.io.*;
class Stack implements StackOperations
{
int stk[] = new int[50],cap,top;
Stack(int nn)
{
cap=nn;
top=-1;

153
}
public void Push(int num)
{
if(top==cap)
System.out.println("Stack Overflow, element cannot be pushed....");
else
{
top++;
stk[top]=num;
}
}
public void Pop()
{
if(top==-1)
System.out.println("Stack Underflow, element cannot be popped.... ");
else
{
int temp=stk[top];
top--;
System.out.println("The Popped or deleted integer is = "+temp);
}
}
void display()
{
if(top==-1)
System.out.println("Stack Underflow, element cannot be printed.... ");
else
{
System.out.println("The elements in the stack are as below: ");
for(int j=top;j>=0;j--)
System.out.println(stk[j]);
}
}
public static void main(String args[])
{
Stack obj = new Stack(4);
obj.Push(12);
obj.Push(56);
obj.Push(7);
obj.display();
obj.Pop();
obj.display();
}
}

154
OUTPUT:

155
PROGRAM 3

QUESTION:

Queue is a linear data structure which enables the user to add integers from rear end and
remove integers from the front end, using FIFO (First In First Out) principle. Define a class
Queue with the following details:
Class name: Queue
Data members/instance variables:
arr[] : integer array to hold maximum 50 elements.
cap : integer to store the maximum size of the array/queue.
front : integer to point the index of the front end.
rear : integer to point the index of the rear end.
Member functions/methods:
Queue(int nx): parametrized constructor to initialize cap = nm, front = 0 and rear = -1.
void Push(int num): to push or insert argument num at the rear location, if possible,
otherwise display a message “Queue overflow”.
void Pop(): to pop an integer from the front of the queue, if possible, otherwise display a
message “Queue underflow”.
void show(): to print the elements present in the queue, if possible, otherwise display a
message “Queue Underflow”.
Specify the class Queue giving details of the constructor the functions void Push(int), void
Pop() and void show(). Write a main() function to create an object and call the functions
accordingly to enable the task.

SOURCE CODE:

import java.io.*;
class Queue
{
int arr[] = new int[50];
int cap,front,rear;
Queue(int nx)
{
cap=nx;
front=0;
rear=-1;
}
void Push(int num)
{
if(rear==cap)
System.out.println("Queue Overflow, element cannot be pushed.... ");
else
{
rear++;
arr[rear]=num;
}
}
void Pop()

156
{
if(rear==-1||front>rear)
System.out.println("Queue Underflow, element cannot be popped.... ");
else
{
int temp = arr[front];
front++;
System.out.println("\nThe Popped or deleted integer is = "+temp);
}
}
void show()
{
if(rear==-1||front>rear)
System.out.println("Queue Underflow, element cannot be printed.... ");
else
{
System.out.println("The elements in the queue are as below: ");
for(int j=front;j<=rear;j++)
System.out.print(arr[j]+"\t");
}
}
public static void main(String args[])
{
Queue obj = new Queue(4);
obj.Pop();
obj.show();
obj.Push(24);
obj.Push(13);
obj.Push(9);
obj.show();
obj.Pop();
obj.show();
}
}

OUTPUT:

157
PROGRAM 4

QUESTION:

An interface QueueOperations is defined with methods void Push(int num) to push integer
num at the top index and void Pop() to remove the element from the front index i.e. uses
FIFO principle.
Create a class Queue which implements interface QueueOperations. This class contains data
members, constructors, and methods to perform push and pop operations and print the
elements of the queue.
The details members of interface and class are given below:
Interface name: QueueOperations
Member functions/methods:
void Push(int num): to push or insert argument num at the rear index
void Pop(): to pop or remove an integer from the front of the queue.
Class name: Queue
Data members/instance variables:
arr[] : integer array to hold maximum 50 elements.
cap : integer to store the maximum size of the array/queue.
front : integer to point the index of the front end.
rear : integer to point the index of the rear end.
Member functions/methods:
Queue(int nx): parametrized constructor to initialize cap = nm, front = 0 and rear = -1.
void Push(int num): to push or insert argument num at the rear location, if possible,
otherwise display a message “Queue overflow”.
void Pop(): to pop an integer from the front of the queue, if possible, otherwise display a
message “Queue underflow”.
void show(): to print the elements present in the queue, if possible, otherwise display a
message “Queue Underflow”.
Specify the interface QueueOperations giving declaration of methods void Push(int num)
and void Pop(). Using the concept of inheritance, specify the class Queue giving details of
the constructor the functions void Push(int), void Pop() and void show(). Write a main()
function to create an object and call the functions accordingly to enable the task.

SOURCE CODE:

import java.io.*;
interface QueueOperations
{
void Push(int num);
void Pop();
}
class Queue implements QueueOperations
{
int arr[] = new int[50];
int cap,front,rear;
Queue(int nx)
{

158
cap=nx;
front=0;
rear=-1;
}
public void Push(int num)
{
if(rear==cap)
System.out.println("Queue Overflow, element cannot be pushed.... ");
else
{
rear++;
arr[rear]=num;
}
}
public void Pop()
{
if(rear==-1||front>rear)
System.out.println("Queue Underflow, element cannot be popped.... ");
else
{
int temp = arr[front];
front++;
System.out.println("\nThe Popped or deleted integer is = "+temp);
}
}
void show()
{
if(rear==-1||front>rear)
System.out.println("Queue Underflow, element cannot be printed.... ");
else
{
System.out.println("The elements in the queue are as below: ");
for(int j=front;j<=rear;j++)
System.out.print(arr[j]+"\t");
}
}
public static void main(String args[])
{
Queue obj = new Queue(4);
obj.Pop();
obj.show();
obj.Push(24);
obj.Push(13);
obj.Push(9);
obj.show();
obj.Pop();
obj.show();
}
}

159
OUTPUT:

160
PROGRAM 5

QUESTION:

A doubly queue is a linear data structure which enables the user to add and remove integers
from either ends i.e. from front or rear. Define a class Dequeue with the following details:
Class name: Dequeue
Data members/instance variables:
arr[] : integer array to hold up to 100 elements.
limit : stores the limit of the dequeue.
front : integer to point the index of the front end.
rear : integer to point the index of the rear end.
Member functions/methods:
Dequeue(int L): constructor to initialize lim = L, front = 0 and rear = 0.
void addfront(int val): to add integer ‘val’ from the front if possible otherwise display the
message “Overflow From Front”.
void addrear(int val): to add integer ‘val’ from the rear if possible otherwise display the
message “Overflow From Rear”.
int popfront(): to remove and return an integer from front, if possible otherwise display
“Underflow From Front” and returns -9999.
int poprear(): to remove and return an integer from rear, if possible otherwise display
“Underflow From Rear” and returns -9999.
void display(): to print integers currently in the dequeue, if possible, otherwise display the
message “Underflow DeQueue”.
Specify the class Dequeue giving details of the constructor the functions void addfront(int),
void addrear(int), int popfront(), int poprear() and void display(). Write a main() function
to create an object and call the functions accordingly to enable the task. DO NOT WRITE
THE ALGORITHM.

SOURCE CODE:

import java.io.*;
class Dequeue
{
int arr[] = new int[100];
int lim,front,rear;
Dequeue(int L)
{
lim=L;
front=0;
rear=0;
}
void addrear(int val)
{
if(rear==lim)
System.out.println("\nOverflow From Rear");
else
{
if(rear==-1)

161
rear=0;
arr[rear]=val;
rear++;
}
}
void addfront(int val)
{
if(rear!=-1&&front>0&&front<=rear)
{
front--;
arr[front]=val;
}
else
System.out.println("\nOverflow From Front");
}
int popfront()
{
if(rear==-1||front>rear||arr[front]==0)
{
System.out.println("Underflow From Front");
return(-9999);
}
else
{
int temp=arr[front];
front++;
return temp;
}
}
int poprear()
{
if(rear>=0&&rear<lim-1)
{
int temp=arr[rear];
rear--;
return temp;
}
else
{
System.out.println("Underflow From Rear");
return(-9999);
}
}
void display()
{
if(rear==-1||front>rear)
System.out.println("Underflow DeQueue");
else
{
System.out.println("\nThe elements in the dequeue are as: ");

162
for(int j=front;j<=rear;j++)
System.out.print(arr[j]+" ");
}
}
public static void main(String args[])
{
Dequeue obj = new Dequeue(5);
int y=obj.popfront();
int z=obj.poprear();
obj.display();
obj.addrear(12);
obj.addrear(56);
obj.addrear(7);
obj.display();
obj.addfront(74);
obj.display();
int x=obj.popfront();
obj.display();
int r=obj.poprear();
obj.display();
}
}

OUTPUT:

163
PROGRAM 6

QUESTION:

Circular Queue is a linear data structure in which elements are added and removed using
FIFO (First In First Out) principle and last position (rear) is connected back to the first
position (front) to make a circle.
Define a class CQueue with the following details:
Class name: CQueue
Data members/instance variables:
CQ[] : array to store integer elements.
cap : integer to store the maximum size of the circular queue.
front : integer to point the index of the front end.
rear : integer to point the index of the rear end.
Member functions/methods:
CQqueue(int nx): constructor to initialize cap = nx, front = 0 and rear = 0.
void Push(int num): to push or insert argument num at the rear, if possible, otherwise display
a message “Circular Queue Full from Rear”.
void Pop(): to pop an integer from the front of the queue, if possible, otherwise display a
message “Circular Queue Empty”.
void show(): to print the elements present in the queue, if possible, otherwise display a
message “Circular Queue Empty”.
Specify the class CQueue giving details of the constructor the functions void Push(int),
void Pop() and void show(). Write a main() function to create an object and call the
functions accordingly to enable the task.

SOURCE CODE:

import java.io.*;
class CQueue
{
int CQ[];
int cap,front,rear;
CQueue(int nx)
{
cap=nx;
front=0;
rear=0;
CQ = new int[cap];
}
void Push(int num)
{
if((rear+1)%cap!=front)
{
rear=(rear+1)%cap;
CQ[rear]=num;
}
else

164
System.out.println("Circular Queue Full from Rear");
}
void Pop()
{
if(front!=rear)
{
front=(front+1)%cap;
int temp=CQ[front];
System.out.println("\nThe Popped or deleted integer is = "+temp);
}
else
System.out.println("Circular Queue Empty");
}
void show()
{
int start;
if(front!=rear)
{
start=(front+1)%cap;
System.out.println("The elements in the circular queue are as: ");
while(start!=rear)
{
System.out.print(CQ[start]+"\t");
start=(start+1)%cap;
}
}
else
System.out.println("Circular Queue Empty");
}
public static void main(String args[])
{
CQueue obj = new CQueue(4);
obj.Pop();
obj.show();
obj.Push(31);
obj.Push(18);
obj.Push(6);
obj.show();
obj.Pop();
obj.show();
}
}

165
OUTPUT:

166

You might also like