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

compFinalProject

Uploaded by

shubhnanda474
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

compFinalProject

Uploaded by

shubhnanda474
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

1 of 120

INDEX
S. NO. PROGRAMS Page no.
1. To shift the original character. 3-5
2. To check a bouncy number. 6-8
3. To check a Disarium no. 9-11
4. To check an Automorphic no. 12-
5. To swap the diagonals of a matrix. 17
6. To sort an array using selection sort and remove all duplicate 20
elements.
7. To check whether a string is palindrome or not. 24
8. To display the number of words and frequency of each word. 27
9. To swap the first and last letter of a word and sort the word 31
alphabetically.
10. To sort the boundary elements of a matrix. 34
11. To check no. of prime-adam numbers within a limit. 37
12. To find the decimal equivalent of each element in a matrix. 40
13. To arrange words according to their length. 44
14. To input the day number and year to find the future date entered by 47
the user.
15. To sort the elements of a matrix in ascending order. 50
16. To find the saddle point in a matrix. 53
17. To perform stack. 57
18. To merge two sorted arrays. 60
19. To print time in words. 63
20. To create a magic square. 66
21. To encode string by shifting characters. 69
22. To compare two dates. 72
23. To perform bubble sort placed inside a method. 75
24. To perform selection sort placed inside a method. 78
25. To find GCD placed inside a method placed inside a method. 81
26. To print all the divisors of a number placed inside a method. 84
27. To perform matrix addition. 87
28. To compute the transpose of a matrix placed inside a method. 91
29. To encode a string using Caesar Cipher method. 95
30. To count the number of vowels, reverse the string, check whether it 99
is palindrome, placed inside a method.
31. To add two 3*3 Matrices.
32. To demonstrate method overriding.
33. To check whether a matrix is Doubly Markov matrix or not.

1
2 of 120

34. To check whether a number is hamming number or not.


35. To generate the output of the frequency of vowels and consonants
present in a string in the form of a bar graph.
36. To encode each vowel to it’s next vowel in a word.
37. To store an element with the restriction that element can be added
from the rear end and removed from the front end only through data
structure
38. To merge the current object array elements with the parameterized
array elements and return the resultant object.
39. To shift each row of a matrix upwards in a cyclic manner.
40. To calculate and display the volume in cubic inches and the area in
square inches through multiple objects.

2
3 of 120

Q.1 A class encryption is shifting the original character according to cn. If cn=2, a
becomes c, z becomes b, and if cn=3, a becomes d and so on. (cn<=25)
CLASS NAME : encryption
DATA MEMBERS : txt (String), cn (int)

MEMBER METHODS: -
encryption (int nc) : parameterized constructor
char encryptedChar (char ch) : to encrypt char ch
void settext (String text) : to assign value to txt
void encrypt () : to encrypt the text according to cn
void display () : to display the text

PROGRAM
import java.util.*;
class encryption
{
int cn;
static String txt;
encryption(int nc)
{
cn=nc;
}
char encryptedChar(char ch)
{
if (Character.isLetter(ch))
{
ch += cn;
if (ch>'Z')
ch -= 26;
}
return (ch);
}
static void settext(String text)
{
txt=text;
}
void encrypt()
{
int l=txt.length();
String s = txt;

3
4 of 120

txt = "";
for(int i=0;i<l;i++)
{
char ch=s.charAt(i);
ch=encryptedChar(ch);
txt += ch;
}
}
void display()
{
System.out.println("Encrypted array : " + txt);
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a shifting coefficient");
int nc=sc.nextInt();
if (nc>25)
{
System.out.println("Invalid Input");
System.exit(0);
}
System.out.println("Enter a word");
String s=sc.next().toUpperCase();
encryption ob=new encryption(nc);
settext(s);
ob.encrypt();
ob.display();
}
}
OUTPUT

ALGORITHM

4
5 of 120

1. Start
2. Input value of cn in main and initialize it in parameterized constructor (cn<=25).
3. Accept word from the user.
4. Extract letters from the word.
5. Encrypt the letters.
6. Display the string.
7. Create object to call the member methods.
8. End.
VARIABLE DESCRIPTION
Variable Name Data Type Description
cn int to store adjustment factor
txt String to accept string from user
ch char to encrypt the letters
i int to control for loop
l int To store length of the string

Q.2 Write a program to check if a given no. (n>100) is bouncy or not (digits are
not sorted).
Ex :- 2845, 489 etc.

5
6 of 120

CLASS NAME : Bouncy


DATA MEMBERS : n (int)

MEMBER METHODS: -
Bouncy () : default constructor
void accept () : to accept a no.
int check () : to check if the no. is bouncy or not
void display () : to print if the no. is bouncy or not

PROGRAM
import java.util.*;
class Bouncy
{
int n;
Bouncy()
{
n=0;
}
void accept()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
n = sc.nextInt();
if (n<100)
{
System.out.println("Invalid Input");
System.exit(0);
}
}
int check()
{
String s = Integer.toString(n);
String s1 = "";
String s2 = "";
for (char ch='0';ch <='9';ch++)
{
for(int i = 0;i<s.length();i++)
{
char ch1 = s.charAt(i);
if (ch1 == ch)
s1 = s1 + ch;
}
}
//System.out.println(s1);
for (char ch='9';ch >='0';ch--)

6
7 of 120

{
for(int i = 0;i<s.length();i++)
{
char ch1 = s.charAt(i);
if (ch1 == ch)
s2 = s2 + ch;
}
}
//System.out.println(s2);
if (s.equals(s1) || s.equals(s2))
return 0;
else
return 1;
}
void display()
{
int w = check();
if (w==0)
System.out.println("Not bouncy");
else
System.out.println("Bouncy");
}
public static void main()
{
Bouncy ob = new Bouncy();
ob.accept();
ob.display();
}
}

OUTPUT

7
8 of 120

ALGORITHM
1. Start
2. Accept no. from the user (n>100).
3. Convert int into string.
4. Arrange in ascending and descending order.
5. Check if the no. is bouncy
6. Return 1 if true and 0 if false.
7. Display if bouncy or not.
8. Create object to call the member methods.
9. End.

VARIABLE DESCRIPTION
Variable Name Data Type Description
n Int to store no. to be checked
s String to store number in string form
s1 String ascending order
s2 String descending order
i Int to control for loop

Q.3 Write a program to input a no. and check if it is a Disarium no. or not (sum of
digits raised to the power of its relative position is equal to the number). Ex :- 135
= 1 1 + 32 + 53

8
9 of 120

CLASS NAME : Disarium


DATA MEMBERS : n (int), size (int)

MEMBER METHODS: -
Disarium (int nn) : parameterized constructor
void countDigits () : to count no. of digits
int sumofDigits () : to store sum of digits raised to the power of relative
position
void check () : to check if the no. is disarium or not

PROGRAM
import java.util.Scanner;
public class Disarium
{
int num,size;
Disarium(int nn)
{
num=nn;
size=0;
}
void countDigits()
{
int a=num;
while(a!=0)
{
a=a/10;
size++;
}
}
int sumofDigits(int n, int p)
{
int a;
if (n==0)
return 0;
else
a = sumofDigits(n/10,p-1) + (int)Math.pow(n%10,p);
return a;
}
void check()
{
if(num==sumofDigits(num,size))

9
10 of 120

System.out.println(num+" is a Disarium Number");


else
System.out.println(num+" is not a Disarium Number");
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Input a Number");
int m=sc.nextInt();
Disarium x= new Disarium(m);
x.countDigits();
x.check();
}
}
OUTPUT

ALGORITHM
1. Start
2. Accept no. from the user in main and initialize it in parameterized constructor (n>100).
3. Count no. of digits in the number.
4. Calculate sum of digits raised to the power of their relative position.
5. Check and display if the no. is disarium or not
6. Create object to call the member methods.
7. End.

VARIABLE DESCRIPTION
Variable Name Data Type Description
num int to store no. to be checked

10
11 of 120

i int to control for loop


size int to store no. of digits
n and p int Temporary variable to store sum of digits

Q.4 Write a program to input a no. and check if it is an automorphic no. or not (no.
is present in its square at last). Ex: - 252 = 125
CLASS NAME : automorphic
DATA MEMBERS : n (int)

11
12 of 120

MEMBER METHODS: -
automorphic () : default constructor
automorphic (int n1) : parameterized constructor
boolean isAutomorphic : to check if the no. is automorphic or not
void display () : to print if the no. is automorphic or not

PROGRAM
import java.util.*;
class automorphic
{
int n;
automorphic()
{
n=0;
}
automorphic(int n1)
{
n=n1;
}
boolean isAutomorphic()
{
int c=0,sq=n*n;
for(int i= n;i>0;i/=10)
c++;
if(sq % (int)Math.pow(10,c) == n)
return true;
else
return false;
}
void display()
{
System.out.println("n = "+n);
if (isAutomorphic())
System.out.println(n + " is Automorphic");
else
System.out.println(n + " is not Automorphic");
}
public static void main()
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter a number");

12
13 of 120

int x = sc.nextInt();
automorphic ob = new automorphic(x);
ob.display();
}
}
OUTPUT

ALGORITHM
1. Start
2. Accept no. from the user in main and initialize it in parameterized constructor (n>100).
3. Count no. of digits in the number.
4. Check if the no. is automorphic or not
5. Display if the no. is automorphic or not
6. Create object to call the member methods.
7. End.
VARIABLE DESCRIPTION
Variable Name Data Type Description
n int to store no. to be checked
i int to control for loop
c int to store no. of digits
sq int to store square of the number
Q.5 Write a program to input an N2 matrix.
CLASS NAME : Matrix
DATA MEMBERS : a[][] (int), n (int)

MEMBER METHODS: -
Matrix (int n) : to initialize data memebers
Void accept () : to accept integers in a[][]
void sort () : to sort a[][] row wise
void swapDiagonals () : to swap diagonals
void display () : to display matrix a[][]

13
14 of 120

PROGRAM
import java.util.*;
class Matrix
{
int a[][];
int n;
Matrix(int n)
{
this.n = n;
a = new int [n][n];
}
void accept()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter (n*n) elements");
for(int i=0;i<n;i++)
{
for (int j =0;j<n;j++)
a[i][j] = sc.nextInt();
}
}
void sort()
{
for(int r=0;r<n;r++)
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[r][j] > a[r][j+1])
{
int temp = a[r][j];
a[r][j] = a[r][j+1];
a[r][j+1] = temp;
}
}
} //i
} //r
}
void swapDiagonals()

14
15 of 120

{
for (int i=0,j=n-1;i<n;i++)
{
int temp = a[i][i];
a[i][i] = a[i][j];
a[i][j] = temp;
j--;
}
}
void display()
{
System.out.println("Array after sorting and swapping: -");
for(int i=0;i<n;i++)
{
for (int j =0;j<n;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of n*n matrix where n is even");
int a = sc.nextInt();
if (a%2==0)
{
Matrix ob = new Matrix(a);
ob.accept();
ob.sort();
ob.swapDiagonals();
ob.display();
}
else
{
System.out.println("Invalid Input");
System.exit(0);
}
}
}
OUTPUT

15
16 of 120

ALGORITHM
1. Start
2. Accept size of matrix from the user in main and initialize it in parameterized constructor
(n is even).
3. Input n2 matrix elements.
4. Sort the matrix row wise.
5. Swap the diagonals of matrix.
6. Display the matrix.
7. Create object to call the member methods.
8. End.

VARIABLE DESCRIPTION
Variable Name Data Type Description
n int to store no. of rows and columns
a array to store the elements of matrix
i and j int to control the for loop
temp int Temporary variable used for sorting

16
17 of 120

Q.6 Write a program to input an array, sort and pack it.


CLASS NAME : duplicate
DATA MEMBERS : arr[][] (int), size (int)

MEMBER METHODS: -
duplicate (int n) : to initialize data members
void readList () : to accept integers in arr[]
void selectionSort () : to sort arr[] using selection sort
void packList : to remove all duplicate elements
void displist () : to display arr[]

PROGRAM
import java.util.*;
class duplicate
{
int arr[];
int size;
duplicate(int n)
{

17
18 of 120

size = n;
arr = new int[size];
}
void readList()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter array elements");
for(int i=0;i<size;i++)
{
arr[i] = sc.nextInt();
}
}
void selectionSort()
{
int min,pos;
for(int i = 0;i<size-1;i++)
{
min = arr[i];
pos = i;
for(int j=i+1;j<size;j++)
{
if(arr[j]<min)
{
min = arr[j];
pos = j;
}
}
arr[pos] = arr[i];
arr[i] = min;
}
}
void packList()
{
int p=0;
for(int i=0;i<size-1;i++)
{
if(arr[i]!=arr[i+1])
arr[p++] = arr[i];
else
continue;
}
arr[p++] = arr[size-1];
size = p;
}

18
19 of 120

void dispList()
{
System.out.println("Packed array :-");
for(int i = 0;i<size;i++)
System.out.println(arr[i]);
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of elements");
int a = sc.nextInt();
duplicate ob = new duplicate(a);
ob.readList();
ob.selectionSort();
ob.packList();
ob.dispList();
}
}

OUTPUT

ALGORITHM
1. Start
2. Accept size of array from the user in main and initialize it in parameterized constructor.
3. Input n array elements.
4. Sort the array using selection sort.
5. Pack the array.

19
20 of 120

6. Display the array.


7. Create object to call the member methods.
8. End.

VARIABLE DESCRIPTION
Variable Name Data Type Description
size int to store no. of elements
arr array to store the elements of array
i int to control the for loop
pos int Temporary variable used for sorting

Q.7 Implement a Linear Queue using an Array in Java. The program should allow the following
operations:
1. Enqueue: Add an element to the rear of the queue.
2. Dequeue: Remove an element from the front of the queue.
3. Display: Show all elements in the queue.

Algorithm
1. Enqueue:
- Check if the queue is full.
- If not full, add the element at the `rear` position and update the `rear`.
2. Dequeue:
- Check if the queue is empty.
- If not empty, remove the element from the `front` and update the `front`.
3. Display:
- Traverse from `front` to `rear` and display elements.

Java Program (BlueJ)

public class LinearQueue {


int size = 5;
int[] queue = new int[size];
int front = -1, rear = -1;

// Method to add element to the queue


public void enqueue(int element) {
if (rear == size - 1) {

20
21 of 120

System.out.println("Queue is full");
} else {
if (front == -1) {
front = 0;
}
rear++;
queue[rear] = element;
System.out.println("Enqueued: " + element);
}
}

// Method to remove element from the queue


public void dequeue() {
if (front == -1 || front > rear) {
System.out.println("Queue is empty");
} else {
System.out.println("Dequeued: " + queue[front]);
front++;
}
}

// Method to display elements in the queue


public void display() {
if (front == -1 || front > rear) {
System.out.println("Queue is empty");
} else {
System.out.print("Queue: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}
}

// Main method to demonstrate functionality


public static void main(String[] args) {
LinearQueue q = new LinearQueue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.display();
q.dequeue();
q.display();
q.enqueue(40);
q.display();
}

21
22 of 120

Variable Description
Variable Data Type Description

size int The maximum size of the


queue.

queue int[] Array to store the elements


of the queue.

front int Index of the front element


of the queue.

rear int Index of the rear element of


the queue.

element int Element to be added to the


queue.

Expected Output

Enqueued: 10
Enqueued: 20
Enqueued: 30
Queue: 10 20 30
Dequeued: 10
Queue: 20 30
Enqueued: 40
Queue: 20 30 40

Q.8 Write a program according to the given data.

22
23 of 120

CLASS NAME : Stringfun


DATA MEMBERS : String str

MEMBER METHODS: -
Stringfun () : default constructor
void input () : enter the string
void words () : to display the no. of words
void frequency () : to display the frequency of letters

PROGRAM
import java.util.*;
class Stringfun
{
String str;
Stringfun()
{
str="";
}
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a String");
str=sc.nextLine();
}
void words()
{
StringTokenizer ob=new StringTokenizer(str);
String a[] = str.split("[?! .]");
System.out.println("No. Of words : " + a.length);
}
void frequency()
{
for(char ch='A';ch<='Z';ch++)
{
char ch1 = '\u0000';
int f=0;
int l = str.length();
for(int i=0;i<l;i++)
{
ch1=str.charAt(i);
if(ch==ch1)
f++;
}
if(f>0)
System.out.println("Frequency of "+ch+" : "+f);

23
24 of 120

}
}
public static void main()
{
Stringfun ob=new Stringfun();
ob.input();
ob.words();
ob.frequency();
}
}
OUTPUT

ALGORITHM
1. Start
2. Accept a sentence from the user.
3. Count no. of words and display it.
4. Count the frequency of each letter.
5. Display the frequency.
6. Create object to call the member methods.
7. End.

VARIABLE DESCRIPTION
Variable Name Data Type Description
str String to store inputted sentence
a array to store the words
i int to control the for loop
F int to store frequency of each letter

24
25 of 120

Q.9 Write a program to input a word and swap the first and last letter. Also, sort the
word alphabetically.
CLASS NAME : SwapSort
DATA MEMBERS : String wrd, String snapwrd, String sortwrd

MEMBER METHODS: -
SwapSort () : default constructor
void readword () : accept the string from the user
void swapchar () : to swap first and last letter
void sortword () : to sort the word alphabetically

25
26 of 120

void display () : to print the sorted and swapped word

PROGRAM
import java.util.*;
class SwapSort
{
String wrd,swapwrd,sortwrd;
int len;
SwapSort()
{
wrd = "";
swapwrd = "";
sortwrd = "";
len = 0;
}
void readword()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter word in Upper case");
wrd=sc.next();
len=wrd.length();
}
void swapchar()
{
swapwrd=wrd.charAt(len-1) + wrd.substring(1,len-1) + wrd.charAt(0);
}
void sortword()
{
for(int i=65;i<=90;i++)
{
for(int j=0;j<len;j++)
{
char c=wrd.charAt(j);
if(c==i)
sortwrd += c;
}
}
}
void display()
{
System.out.println("Original word = " + wrd);
System.out.println("Swapped word = " + swapwrd);
System.out.println("Sorted word = " + sortwrd);
}

26
27 of 120

public static void main()


{
SwapSort x=new SwapSort();
x.readword();
x.swapchar();
x.sortword();
x.display();
}
}
OUTPUT

ALGORITHM
1. Start
2. Accept a sentence from the user.
3. Swap the first and last letter.
4. Sort the word alphabetically.
5. Display the sorted and swapped word.
6. Create object to call the member methods.
7. End.

VARIABLE DESCRIPTION

27
28 of 120

Variable Name Data Type Description


wrd String to store inputted word
snapwrd String to store the swapped word
sortwrd String to store the sorted word
len int to store length of the word
i int to control the for loop

Q.10 Write a program to input a matrix of size (m*n) and sort the boundary
elements.
CLASS NAME : Boundary
DATA MEMBERS : int a[][], int m, int n

MEMBER METHODS: -
Boundary (int d, int e) : parameterized constructor to accept size
void accept () : accept the matrix elements from the user and print the original
matrix
void boundarySort () : to extract and place back the boundary elements
void Sort (int b[]) : to sort the boundary elements
void display () : to print the matrix after sorting

PROGRAM

import java.util.*;
class Boundary
{
int a[][];
int m,n;
Boundary (int d,int e)
{
m=d;
n=e;
a = new int [m][n];
}
void accept()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter "+(m*n)+" matrix elements");
for(int i = 0;i<m;i++)
{
for(int j=0;j<n;j++)
a[i][j] = sc.nextInt();
}

28
29 of 120

System.out.println("Original Matrix: -");


for(int i = 0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
void boundarySort()
{
int b[] = new int[2*(m+n)-4];
int p=0;
for(int i = 0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||j==0||i==m-1||j==n-1)
b[p++] = a[i][j];
}
}
Sort(b);
int r=0,c=0;
p=0;
for(int i=0;i<n-1;i++)
a[r][c++] = b[p++];
for(int i=0;i<m-1;i++)
a[r++][c] = b[p++];
for(int i=0;i<n-1;i++)
a[r][c--] = b[p++];
for(int i=0;i<m-1;i++)
a[r--][c] = b[p++];
}
void display()
{
System.out.println("Matrix after sorting:-");
for(int i = 0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();

29
30 of 120

}
}
void Sort(int b[])
{
for(int i=0;i<b.length-1;i++)
{
for (int j=0;j<b.length-1-i;j++)
{
if (b[j]>b[j+1])
{
int temp = b[j];
b[j] = b[j+1];
b[j+1] = temp;
}
}
}
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of matrix");
int r=sc.nextInt();
int c = sc.nextInt();
Boundary ob = new Boundary(r,c);
ob.accept();
ob.boundarySort();
ob.display();
}
}

OUTPUT

30
31 of 120

ALGORITHM
1. Start
2. Accept size of array from the user in main and initialize it in parameterized constructor.
3. Input (m*n) matrix elements and print the original matrix.
4. Extract the boundary elements.
5. Sort the boundary elements.
6. Place the boundary elements back.
7. Print the matrix after sorting
8. Create object to call the member methods.
9. End.

VARIABLE DESCRIPTION
Variable Name Data Type Description
m int to store no. of rows
n int to store no. of columns
a array to store the elements of matrix
i and j int to control the for loop
b array to store and sort the boundary elements

Q-11- A Prime-Adam integer is a positive integer (without leading zeros) which is a prime as
well as an Adam number. Prime number: A number which has only two factors, i.e., 1 and the
number itself. Example: 2, 3, 5, 7 ... etc.Adam number: The square of a number and the square
of its reverse arereverse to each other. Example: If n = 13 and reverse of 'n' = 31, then, (13)^2 =
169 (31)^2 = 961 which is reverse of 169 thus 13, is an Adam number. Accept two positive
integers m and n, where m is less than n as user input. Display all Prime-Adam integers that are
in the range between m and n (both inclusive) and output them along with the frequency, in the
format given below: Test your program with the following data and some random data:
Example 1
INPUT:
m=5
n = 100
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
11 13 31
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 2

31
32 of 120

INPUT:
m = 100
n = 200
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
101 103 113
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 3
INPUT:
m = 50
n = 70
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
NIL
FREQUENCY OF PRIME-ADAM INTEGERS IS: 0
Example 4
INPUT:
m = 700
n = 450
OUTPUT:
INVALID INPUT
Solution
import java.util.*;
public class ISC20Q01
{
public static int reverse(int num)
{
int rev = 0;
while (num != 0)
{

32
33 of 120

int d = num % 10;


rev = rev * 10 + d;
num /= 10;
}return rev;
}
public static boolean isAdam(int num)
{
int sqNum = num * num;
int revNum = reverse(num);
int sqRevNum = revNum * revNum;
int rev = reverse(sqNum);
return rev == sqRevNum;
}
public static boolean isPrime(int num)
{
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
c++}
return c == 2;
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of m: ");
int m = sc.nextInt();
System.out.print("Enter the value of n: ");
int n = sc.nextInt();
int count = 0;

33
34 of 120

if (m >= n)
{
System.out.println("INVALID INPUT");
return;
}
System.out.println("THE PRIME‐ADAM INTEGERS ARE:");

for (int i = m; i <= n; i++)


{
boolean adam = isAdam(i);
if (adam)
{
boolean prime = isPrime(i);
if (prime)
{
System.out.print(i + " ");
count++;}}}
if (count == 0)
System.out.print("NIL");
System.out.println();
System.out.println("FREQUENCY OF PRIME‐ADAM INTEGERS IS: " +

count);
}}

34
35 of 120

Output:

Algorithm:
1. Start
2. Input two integers m and n.

35
36 of 120

3. Check Validity: If m >= n, output "INVALID INPUT" and terminate.


4. Initialize a counter count to 0 to keep track of Prime-Adam numbers.
5. Loop through numbers from m to n (both inclusive):
1. For each number i, check if it is an Adam number:
▪ Reverse the number.
▪ Square the number.
▪ Reverse the squared result.
▪ Square the reversed number.
▪ If the square of the number's reverse is the reverse of the square of the
original number, the number is an Adam number.
2. If i is an Adam number, check if it is also a prime number:
▪ Count how many divisors i has. If there are exactly two divisors (1 and the
number itself), then i is prime.
3. If i is both a Prime and an Adam number, display it and increment the counter
count.
6. Check Counter: If no Prime-Adam integers are found, print "NIL". Otherwise, display the
found integers.
7. Output the frequency of Prime-Adam integers by printing count.
8. End.
Variable Descriptions:
m: (Integer) - The lower bound of the range, provided by the user.
n: (Integer) - The upper bound of the range, provided by the user.
count: (Integer) - A counter that tracks how many Prime-Adam integers are found in the range
[m, n].
i: (Integer) - The current number in the loop being checked for Prime-Adam properties.
rev: (Integer) - Stores the reverse of a number during reversal operations.
sqNum: (Integer) - The square of a number being checked for Adam properties.
revNum: (Integer) - The reverse of the number i.
sqRevNum: (Integer) - The square of the reversed number revNum.
adam: (Boolean) - A flag that indicates whether the current number is an Adam number.
prime: (Boolean) - A flag that indicates whether the current number is a prime number.
c: (Integer) - A counter used to check how many divisors a number has (for prime checking).

36
37 of 120

Q-12: Write a program to declare a matrix A[][] of order (M x N) where 'M' is the number of rows
and 'N' is the number of columns such that the value of 'M' must be greater than 0 and less than
10 and the value of 'N' must be greater than 2 and less than 6. Allow the user to input digits (0 -
7) only at each location, such that each row represents an octal number.
Example:

2 3 1 (decimal equivalent of 1 st row=153 i.e. 2*8^2+3*8^1+1*8^0)

4 0 5 (decimal equivalent of 2nd row=261 i.e. 4*8^2+0*8^1+5*8^0)

1 5 6 (decimal equivalent of 3 rd row=110 i.e.1*8^2+5*8^1+6*8^0)

Perform the following tasks on the matrix: 1. Display the original matrix. 2. Calculate the decimal
equivalent for each row and display as per the format given below. Test your program for the
following data and some random data:
Example 1:
INPUT:
M=1
N=3
ENTER ELEMENTS FOR ROW 1: 1 4 4
OUTPUT:

FILLED MATRIX DECIAML EQUIVALENT

1 4 4 100

Example 2:
INPUT:
M=3
N=4
ENTER ELEMENTS FOR ROW 1: 1 1 3 7
ENTER ELEMENTS FOR ROW 2: 2 1 0 6
ENTER ELEMENTS FOR ROW 3: 0 2 4 5
OUTPUT:

FILLED MATRIX DECIMAL EQUIVALENT

37
38 of 120

1 1 3 7 607

2 1 0 6 1094

0 2 4 5 165

Example 3:
INPUT:
M=3
N=3
ENTER ELEMENTS FOR ROW 1: 2 4 8
OUTPUT:
INVALID INPUT
Example 4:
INPUT:
M=4
N=6
OUTPUT:
OUT OF RANGE
Solution
import java.util.*;
public class ISC20Q02
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows (M): ");
int m = sc.nextInt();
System.out.print("Enter the number of columns (N): ");
int n = sc.nextInt();
if (m <= 0 || m >= 10 || n <= 2 || n >= 6)
{

38
39 of 120

System.out.println("OUT OF RANGE");
return;
}
int a[][] = new int[m][n];
for (int i = 0; i < m; i++)
{
System.out.println("ENTER ELEMENTS FOR ROW "+(i + 1) + ": ");
for (int j = 0; j < n; j++)
{
a[i][j] = sc.nextInt();
if (a[i][j] < 0 || a[i][j] > 7)
{
System.out.println("INVALID INPUT");
return;}}}
System.out.println("FILLED MATRIX\tDECIMAL EQUIVALENT");
for (int i = 0; i < m; i++)
{
int decNum = 0;
for (int j = 0; j < n; j++)
{
decNum += a[i][j] * Math.pow(8, n ‐ j ‐ 1 );
System.out.print(a[i][j] + " ");
}
System.out.print("\t\t" + decNum);
System.out.println();}}}
Output:

39
40 of 120

40
41 of 120

Algorithm:
1. Start
2. Input the number of rows M and the number of columns N.
3. Check Input Range:
o If M is not between 1 and 9 (inclusive), or N is not between 3 and 5 (inclusive),
output "OUT OF RANGE" and terminate.
4. Initialize a matrix A[M][N].
5. Loop through each row (from 0 to M-1):
o For each row, prompt the user to enter N elements (digits between 0 and 7).
o Validate input: If any element is outside the range 0 to 7, print "INVALID INPUT"
and terminate the program.
6. Display the Filled Matrix and Decimal Equivalent:
o For each row, display the elements.
o Calculate the decimal equivalent of each row as follows:
▪ Initialize decNum = 0.

41
42 of 120

▪ For each element A[i][j], update decNum as:


▪ decNum += A[i][j] * (8^(N-j-1))
▪ Print the calculated decNum.
7. End
Variable Descriptions:
M: (Integer) - The number of rows in the matrix, provided by the user.
N: (Integer) - The number of columns in the matrix, provided by the user.
A[][]: (2D Integer Array) - A matrix of size M x N that holds the octal digits entered by the user.
i: (Integer) - A loop counter for traversing rows of the matrix.
j: (Integer) - A loop counter for traversing columns of the matrix.
decNum: (Integer) - Stores the decimal equivalent of each row, calculated based on the octal
number formed by the digits of the row.
sc: (Scanner Object) - Used for taking user input.
A[i][j]: (Integer) - Represents each element of the matrix, corresponding to the octal digit entered
by the user.
Math.pow(8, N - j - 1): (Double) - Calculates the positional value for the octal conversion (i.e.,
8^position), where position decreases from left to right across the row.
Q-13: Write a program to accept a sentence which may be terminated by either '.', '?' or '!' only.
The words are to be separated by a single blank space and are in UPPER CASE. Perform the
following tasks: 1. Check for the validity of the accepted sentence only for the terminating
character. 2. Arrange the words in ascending order of their length. If two or more words have
the same length, then sort them alphabetically. 3. Display the original sentence along with the
converted sentence. Test your program for the following data and some random data:
Example 1:
INPUT:
AS YOU SOW SO SHALL YOU REAP.
OUTPUT:
AS YOU SOW SO SHALL YOU REAP.
AS SO SOW YOU YOU REAP SHALL
Example 2:
INPUT:
SELF HELP IS THE BEST HELP.
OUTPUT:

42
43 of 120

SELF HELP IS THE BEST HELP.


IS THE BEST HELP HELP SELF
Example 3:
INPUT:
BE KIND TO OTHERS.
OUTPUT:
BE KIND TO OTHERS.
BE TO KIND OTHERS
Example 4:
INPUT:
NOTHING IS IMPOSSIBLE#
OUTPUT:
INVALID INPUT
Solution
import java.util.*;
public class ISC20Q03
{
public static String sortString(String ipStr)
{
StringTokenizer st = new StringTokenizer(ipStr);
int wordCount = st.countTokens();
String strArr[] = new String[wordCount];
for (int i = 0; i < wordCount; i++)
strArr[i] = st.nextToken();
for (int i = 0; i < wordCount ‐ 1; i++)

{
for (int j = 0; j < wordCount ‐ i ‐ 1; j++)
{
if (strArr[j].length() > strArr[j + 1].length())
{

43
44 of 120

String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
}
if (strArr[j].length() == strArr[j + 1].length()
&&(strArr[j].compareTo(strArr[j+1]) > 0))
{
String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
}}}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < wordCount; i++)
{
sb.append(strArr[i]);
sb.append(" ");
}
return sb.toString().trim();
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = sc.nextLine();
int len = str.length();
System.out.println();
if (str.charAt(len ‐ 1) != '.'
&& str.charAt(len ‐ 1) != '?'

&& str.charAt(len ‐ 1) != '!')

44
45 of 120

System.out.println("INVALID INPUT");
return;
}
String sortedStr = sortString(str.substring(0, len ‐ 1));
System.out.println(str);
System.out.println(sortedStr);}}
Output:

45
46 of 120

46
47 of 120

Q-14- Design a program to accept a day number (between 1 and 366),


year (in 4 digits) from the user to generate and display the corresponding date. Also, accept 'N'
(1 <= N <= 100) from the user to compute and display the future date corresponding to 'N' days
after the generated date. Display an error message if the value of the day number, year and N
are not within the limit or not according to the condition specified. Test your program with the
following data and some random data:
Example 1
INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019
Example 3
INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33
OUTPUT:
DAY NUMBER OUT OF RANGE
Example 4
INPUT:

47
48 of 120

DAY NUMBER: 150


YEAR: 2018
DATE AFTER (N DAYS): 330
OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE
Solution
import java.util.*;
class ISC19Q1
{
public static void main()
{
int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
String mn[]={"","JANUARY","FEBRUARY","MARCH","APRIL",
"MAY","JUNE","JULY","AUGUST","SEPTEMBER",
"OCTOBER","NOVEMBER","DECEMBER"};
int mm=1,m,n,yy,dd;
Scanner sc=new Scanner(System.in);
System.out.print("INPUT:\tDAY NUMBER:\t");
n=sc.nextInt();
System.out.print(" \tYEAR:\t\t");
yy=sc.nextInt();
System.out.print(" \tDATE AFTER(N DAYS):\t");
m=sc.nextInt();
if(n>=1 && n<=366)
{if(yy>=1000 && yy<=9999)
{if(m>=1 && m<=100)
{if((yy%400==0 || (yy%100!=0 && yy%4==0)))
days[2]=29;
while(n>days[mm])
{n=n‐days[mm];

48
49 of 120

mm++;}
dd=n;
System.out.println("OUTPUT:\tDATE\t\t"+dd+"TH "+mn[mm]+" "+yy);
dd+=m;
while(dd>days[mm])
{
dd=dd‐days[mm];
mm++;
if(mm==13)
{
yy++;
mm=1;
if(yy%400==0 ||
(yy%100!=0 && yy%4==0))
days[2]=29;
else
days[2]=28;
}}
System.out.println(" \tDATE AFTER "+m+"DAYS:\t"+dd+"TH "+mn[mm]+" "+yy);
}
else
System.out.println("OUTPUT:\t DATE AFTER (N DAYS) OUT OF RANGE.");
}
else
System.out.println("OUTPUT:\tYEAR OUT OF RANGE.");
}
else
System.out.println("OUTPUT:\tDAY NUMBER OUT OF RANGE.");}}
Output:

49
50 of 120

Algorithm:
1. Start

50
51 of 120

2. Input the day number n (between 1 and 366), year yy (4-digit format), and m (number of
days after the given date, where 1 ≤ m ≤ 100).
3. Check Input Validity:
o If n is outside the range of 1 to 366, output "DAY NUMBER OUT OF RANGE"
and terminate.
o If yy is outside the range of 1000 to 9999, output "YEAR OUT OF RANGE" and
terminate.
o If m is outside the range of 1 to 100, output "DATE AFTER (N DAYS) OUT OF
RANGE" and terminate.
4. Check for Leap Year:
o If the year yy is a leap year (yy % 400 == 0 or (yy % 100 != 0 and yy % 4 == 0)),
set February's days to 29 in the array days[].
5. Find the Corresponding Date:
o Initialize mm = 1 (month index) and loop through the days[] array to determine
the month and day corresponding to the day number n.
o Subtract the number of days in each month from n until the appropriate month is
found.
6. Display the Generated Date in the format dd TH month, yy.
7. Calculate the Future Date:
o Add m days to the found date (dd += m).
o Adjust the month and year accordingly if the new day exceeds the number of
days in the current month.
o If the month exceeds December, increment the year and reset the month to
January.
o Adjust Leap Year for the new year when necessary.
8. Display the Future Date in the format dd TH month, yy.
9. End
Variable Descriptions:
1. days[]: (Integer Array) - Stores the number of days in each month. For a leap year, the
value for February (index 2) is set to 29; otherwise, it remains 28.
2. mn[]: (String Array) - Stores the names of the months corresponding to each index. E.g.,
mn[1] is "JANUARY".
3. mm: (Integer) - Represents the current month index (from 1 to 12).
4. m: (Integer) - The number of days after the generated date that is to be calculated.

51
52 of 120

5. yy: (Integer) - The year provided by the user.


6. n: (Integer) - The day number input by the user (between 1 and 366).
7. dd: (Integer) - The day of the month that corresponds to the day number n.
8. sc: (Scanner Object) - Used to take user input.
9. Leap Year Check: (yy % 400 == 0 || (yy % 100 != 0 && yy % 4 == 0)) - A condition that
checks if a year is a leap year.
10. dd += m: (Expression) - Adds the number of days m to the current day dd to calculate
the future date.
11. Month and Year Adjustments: If the value of dd exceeds the number of days in the
current month, it is reset, and the month (mm) is incremented. If mm exceeds 12
(December), the year is incremented.
Q-15- Write a program to declare a single-dimensional array a[] and a
square matrix b[][] of size N, where N > 2 and N < 10. Allow the user to input positive integers
into the single dimensional array. Perform the following tasks on the matrix: 1. Sort the elements
of the single-dimensional array in ascending order using any standard sorting technique and
display the sorted elements. 2. Fill the square matrix b[][] in the following format: If the array a[]
= {5, 2, 8, 1} then, after sorting a[] = {1, 2, 5, 8} .Then, the matrix b[][] would fill as below:
1258
1251
1212
1125
3. Display the filled matrix in the above format. Test your program for the following data and
some random data:
Example 1
INPUT:
N=3
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 3 1 7
OUTPUT:
SORTED ARRAY: 1 3 7
FILLED MATRIX
137
131
113

52
53 of 120

Example 2
INPUT:
N = 13
OUTPUT:
MATRIX SIZE OUT OF RANGE
Example 3
INPUT:
N=5
ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: 10 2 5 23 6
OUTPUT:
SORTED ARRAY: 2 5 6 10 23
FILLED MATRIX
2 5 6 10 23
2 5 6 10 2
25625
25256
2 2 5 6 10
Solution
import java.util.*;
class ISC19Q2
{ private static void sort(int a[])
{ int n=a.length,temp; for(int i=1;i<n;i++)
{ for(int j=0;j<n‐i;j++)

{ if(a[j]>a[j+1])
{ temp=a[j]; a[j]=a[j+1];a[j+1]=temp;}}}}
public static void main()
{
int n,i,j,p=0; Scanner sc=new Scanner(System.in);
System.out.print("INPUT N = "); n=sc.nextInt();
if(n>2 && n<10)

53
54 of 120

{int a[]=new int[n];


System.out.print("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY: ");
for(i=0;i<n;i++)
a[i]=sc.nextInt(); sort(a);
System.out.print("OUTPUT:\tSORTED ARRAY: ");
for(i=0;i<n;i++)
System.out.print(a[i]+" "); System.out.println();
int b[][]=new int[n][n];
for( i=0;i<n;i++)
{ p=0;
for(j=0;j<n;j++)
{ if(i+j<=n‐1)
b[i][j]=a[p++];}}
for(i=0;i<n;i++)
{ p=0;
for(j=0;j<n;j++)
{ if(i+j>n‐1)
b[i][j]=a[p++];}}
System.out.println(" \tFILLED MATRIX");
for(i=0;i<n;i++)
{ System.out.print(" \t");
for(j=0;j<n;j++)
System.out.print(b[i][j]+"\t");
System.out.println();}}
else
System.out.println("OUTPUT:\t
MATRIX SIZE OUT OF RANGE");}
Output

54
55 of 120

Algorithm:
1. Start
2. Input the size of the matrix (N), ensuring that N is greater than 2 and less than 10.

55
56 of 120

o If N is outside this range, print "MATRIX SIZE OUT OF RANGE" and terminate
the program.
3. Declare and initialize a single-dimensional array a[] of size N.
4. Input the elements of the array a[], ensuring they are positive integers.
5. Sort the array a[] in ascending order using a standard sorting algorithm (Bubble Sort in
this case).
6. Display the sorted array.
7. Declare a square matrix b[][] of size N x N.
8. Fill the matrix b[][] as follows:
o For the elements on and above the main diagonal (i + j <= N-1), assign values
from the sorted array a[].
o For the elements below the main diagonal (i + j > N-1), assign values from the
sorted array a[].
9. Display the filled matrix b[][] in the required format.
Variable Descriptions:
1. N: (Integer) - Size of the matrix (input by the user). Should be greater than 2 and less
than 10.
2. a[]: (Integer Array) - A single-dimensional array of size N to store the input integers.
3. b[][]: (Integer Matrix) - A square matrix of size N x N that will be filled with elements from
the sorted array a[].
4. i: (Integer) - A loop counter used for iterating through the rows of the matrix.
5. j: (Integer) - A loop counter used for iterating through the columns of the matrix.
6. p: (Integer) - A pointer to access elements from the sorted array a[] when filling the
matrix.
7. temp: (Integer) - A temporary variable used for swapping elements during the sorting
process (Bubble Sort).
8. sc: (Scanner Object) - Used to take user input.
9. sort(a[]): (Function) - A function that sorts the array a[] using the Bubble Sort algorithm.
10. Condition i + j <= N-1: Ensures elements on and above the main diagonal are filled with
sorted array values.
11. Condition i + j > N-1: Ensures elements below the main diagonal are filled with sorted
array values.

Q-16: Saddle Point in a Matrix

56
57 of 120

Algorithm:
1. Accept the order of the matrix and its elements from the user.
2. For each row, find the minimum element and track its column index.
3. Check if this minimum element is the maximum in its column.
4. If such an element exists, it is a saddle point. Print its value.
5. If no saddle point exists, print "No Saddle Point".
PROGRAM:
import java.util.Scanner;
class SaddlePoint {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows:");
int r = sc.nextInt(); // Number of rows
System.out.println("Enter the number of columns:");
int c = sc.nextInt(); // Number of columns
int matrix[][] = new int[r][c]; // Matrix to store elements

System.out.println("Enter the elements:");


for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
matrix[i][j] = sc.nextInt(); // Storing elements in the matrix
}
}

boolean found = false;


for(int i = 0; i < r; i++) {
int min = matrix[i][0]; // Assume the first element is the minimum in the row
int minIndex = 0;

for(int j = 1; j < c; j++) { // Finding the minimum element in the row

57
58 of 120

if(matrix[i][j] < min) {


min = matrix[i][j];
minIndex = j;
}
}

int max = min;


for(int k = 0; k < r; k++) { // Checking if the minimum element is the maximum in
its column
if(matrix[k][minIndex] > max) {
max = matrix[k][minIndex];
}
}

if(min == max) {
System.out.println("Saddle Point is: " + min);
found = true;
break;
}
}

if(!found) {
System.out.println("No Saddle Point");
}
}
}

Variable Description:
• r: Stores the number of rows in the matrix.
• c: Stores the number of columns in the matrix.

58
59 of 120

• matrix[][]: A 2D array to store the elements of the matrix.


• min: Stores the minimum element in the current row.
• minIndex: Stores the column index of the minimum element.
• max: Stores the maximum element in the column of the minimum element.
• i, j, k: Loop control variables used in finding the saddle point.
• found: A boolean flag to check if a saddle point is found.
OUPUT:
Enter the number of rows:
3
Enter the number of columns:
3
Enter the elements:
387
659
421
Saddle Point is: 5

Q17: Implementation of Stack Using Arrays


Algorithm:
1. Initialize an array to represent the stack and a variable to track the top of the stack.
2. Implement push operation to add elements to the stack by incrementing the top variable.
3. Implement pop operation to remove elements from the stack by decrementing the top
variable.
4. Implement peek operation to view the top element without removing it.
5. Display appropriate messages for stack overflow or underflow situations.

PROGRAM:
import java.util.Scanner;
class StackArray {

59
60 of 120

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the stack:");
int size = sc.nextInt(); // Size of the stack
int stack[] = new int[size]; // Array to store stack elements
int top = -1; // Initialize the top of the stack
while(true) {
System.out.println("\n1. Push\n2. Pop\n3. Peek\n4. Exit");
System.out.println("Enter your choice:");
int choice = sc.nextInt();
switch(choice) {
case 1:
if(top == size - 1) {
System.out.println("Stack Overflow!"); // Check for stack overflow
} else {
System.out.println("Enter element to push:");
int element = sc.nextInt();
stack[++top] = element; // Push operation
System.out.println("Element pushed: " + element);
}
break;
case 2:
if(top == -1) {
System.out.println("Stack Underflow!"); // Check for stack underflow
} else {
System.out.println("Element popped: " + stack[top--]); // Pop operation
}
break;
case 3:
if(top == -1) {

60
61 of 120

System.out.println("Stack is empty!"); // Check if stack is empty


} else {
System.out.println("Top element: " + stack[top]); // Peek operation
}
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid choice!");
}
}
}
}
Variable Description:
• size: Stores the size of the stack, input by the user.
• stack[]: An array to store the elements of the stack.
• top: A variable to keep track of the top element in the stack.
• choice: Variable to store the user's choice for stack operations.
• element: Variable to store the element to be pushed onto the stack.

Output:
Enter the size of the stack:
5
1. Push
2. Pop
3. Peek
4. Exit
Enter your choice:
1
Enter element to push:

61
62 of 120

10
Element pushed: 10

1. Push
2. Pop
3. Peek
4. Exit
Enter your choice:
3
Top element: 10

1. Push
2. Pop
3. Peek
4. Exit
Enter your choice:
2
Element popped: 10

Q-18: Merge Two Sorted Arrays


Algorithm:
1. Accept the sizes and elements of the two sorted arrays from the user.
2. Initialize a third array to store the merged result.
3. Use two pointers to traverse both input arrays.
4. Compare elements from both arrays and add the smaller element to the third array.
5. After processing both arrays, add any remaining elements from either array to the third
array.
6. Print the merged array.

PROGRAM:

62
63 of 120

import java.util.Scanner;
class MergeSortedArrays {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// Input for the first sorted array
System.out.println("Enter the size of the first sorted array:");
int size1 = sc.nextInt();
int array1[] = new int[size1];
System.out.println("Enter the elements of the first sorted array:");
for(int i = 0; i < size1; i++) {
array1[i] = sc.nextInt();
}
// Input for the second sorted array
System.out.println("Enter the size of the second sorted array:");
int size2 = sc.nextInt();
int array2[] = new int[size2];
System.out.println("Enter the elements of the second sorted array:");
for(int i = 0; i < size2; i++) {
array2[i] = sc.nextInt();
}
// Merging the arrays
int mergedSize = size1 + size2;
int mergedArray[] = new int[mergedSize];
int i = 0, j = 0, k = 0;
while(i < size1 && j < size2) {
if(array1[i] <= array2[j]) {
mergedArray[k++] = array1[i++];
} else {
mergedArray[k++] = array2[j++];
}

63
64 of 120

}
// Copy remaining elements from array1
while(i < size1) {
mergedArray[k++] = array1[i++];
}
// Copy remaining elements from array2
while(j < size2) {
mergedArray[k++] = array2[j++];
}
// Print the merged array
System.out.println("Merged array:");
for(int element : mergedArray) {
System.out.print(element + " ");
}
}
}

Variable Description:
• size1: Size of the first sorted array.
• size2: Size of the second sorted array.
• array1[]: First sorted array.
• array2[]: Second sorted array.
• mergedSize: Size of the merged array (sum of sizes of the two arrays).
• mergedArray[]: Array to store the merged result.
• i, j, k: Index variables for traversing array1, array2, and mergedArray, respectively.

OUTPUT:
Enter the size of the first sorted array:
3
Enter the elements of the first sorted array:

64
65 of 120

135
Enter the size of the second sorted array:
4
Enter the elements of the second sorted array:
2468
Merged array:
1234568

Program 19: Print Time in Words (Compact Version)


Algorithm:
1. Read hour and minute values.
2. Use inline arrays to map numbers to words.
3. Print the time in words.

PROGRAM:
import java.util.Scanner;
class TimeInWords {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter hour (0-23): ");
int hour = sc.nextInt();
System.out.print("Enter minute (0-59): ");
int minute = sc.nextInt();
String[] words = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen",
"Eighteen", "Nineteen", "Twenty", "Twenty-one", "Twenty-two", "Twenty-
three",
"Twenty-four", "Twenty-five", "Twenty-six", "Twenty-seven", "Twenty-
eight",

65
66 of 120

"Twenty-nine", "Thirty", "Thirty-one", "Thirty-two", "Thirty-three",


"Thirty-four", "Thirty-five", "Thirty-six", "Thirty-seven", "Thirty-eight",
"Thirty-nine", "Forty", "Forty-one", "Forty-two", "Forty-three",
"Forty-four", "Forty-five", "Forty-six", "Forty-seven", "Forty-eight",
"Forty-nine", "Fifty", "Fifty-one", "Fifty-two", "Fifty-three",
"Fifty-four", "Fifty-five", "Fifty-six", "Fifty-seven", "Fifty-eight", "Fifty-
nine"};

if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {


System.out.println("Invalid time.");
return;
}
String hourWord = (hour == 0) ? "Midnight" :
(hour == 12) ? "Noon" :
(hour > 12) ? words[hour - 12] + " PM" :
words[hour] + " AM";
String minuteWord = words[minute];
System.out.println("Time: " + hourWord + " " + minuteWord);
}
}

Variable Description:
• hour: The hour part of the time (0-23).
• minute: The minute part of the time (0-59).
• words[]: Array mapping numbers to their word equivalents.
OUTPUT:
Enter hour (0-23): 14
Enter minute (0-59): 45
Time: Two PM Forty-five

66
67 of 120

Q-19: Create a Magic Square (3x3 Matrix)


Algorithm:
1. Initialize a 3x3 matrix.
2. Use a specific algorithm to fill the matrix with numbers 1 to 9 such that the sum of
each row, column, and diagonal is the same.
3. Print the matrix.

PROGRAM:
class MagicSquare {
public static void main(String[] args) {
int[][] magicSquare = new int[3][3];
int num = 1;
int i = 0, j = 1; // Start position
// Fill the magic square
while (num <= 9) {
magicSquare[i][j] = num++;
i--;
j++;
if (i < 0) i = 2;
if (j > 2) j = 0;
if (magicSquare[i][j] != 0) {
i += 2;
j--;
if (i > 2) i = 0;
if (j < 0) j = 2;
}
}
// Print the magic square
System.out.println("Magic Square:");
for (int x = 0; x < 3; x++) {

67
68 of 120

for (int y = 0; y < 3; y++) {


System.out.print(magicSquare[x][y] + " ");
}
System.out.println();
}
}
}

Variable Description:
• magicSquare[][]: 3x3 matrix to store the magic square.
• num: Number to be placed in the matrix.
• i, j: Indices for matrix placement.

OUTPUT:
Magic Square:
276
951
438

Q-20: Encode String by Shifting Characters


Algorithm:
1. Read the string and shift value from the user.
2. Encode each character of the string by shifting it in the alphabet.
3. Print the encoded string.

PROGRAM:
import java.util.Scanner;
class EncodeString {
public static void main(String[] args) {
Scanner st = new Scanner(System.in);

68
69 of 120

System.out.println("Enter a string:");
String input = st.nextLine(); // Read the string
System.out.println("Enter shift value:");
int shift = st.nextInt(); // Read shift value
String encoded = ""; // Initialize encoded string
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i); // Get each character
if (Character.isLetter(ch)) { // Check if character is a letter
char base = (Character.isUpperCase(ch)) ? 'A' : 'a';
ch = (char) ((ch - base + shift) % 26 + base);
}
encoded += ch; // Append encoded character
}
System.out.println("Encoded string: " + encoded);
}
}

Variable Description:
• input: The string to be encoded.
• shift: The number of positions to shift each character.
• encoded: The resulting encoded string.

OUTPUT:
Enter a string:
Hello World
Enter shift value:
3
Encoded string: Khoor Zruog

Q-21: Compare Two Dates

69
70 of 120

Algorithm:
1. Read two dates from the user.
2. Calculate the difference in years, months, and days between the two dates.
3. Print the differences.

import java.util.Scanner;
class DateDifference {
public static void main(String[] args) {
Scanner st = new Scanner(System.in);
// Read first date
System.out.println("Enter first date (YYYY MM DD):");
int y1 = st.nextInt();
int m1 = st.nextInt();
int d1 = st.nextInt();
// Read second date
System.out.println("Enter second date (YYYY MM DD):");
int y2 = st.nextInt();
int m2 = st.nextInt();
int d2 = st.nextInt();
// Convert dates to days
int days1 = y1 * 365 + m1 * 30 + d1;
int days2 = y2 * 365 + m2 * 30 + d2;
// Calculate difference in days
int totalDays = Math.abs(days2 - days1);
// Calculate difference in years, months, and days
int years = totalDays / 365;
totalDays %= 365;
int months = totalDays / 30;
int days = totalDays % 30;

70
71 of 120

System.out.println("Difference: " + years + " years, " + months + " months, " + days
+ " days");
}
}

Variable Description:
• y1, m1, d1: Year, month, and day of the first date.
• y2, m2, d2: Year, month, and day of the second date.
• days1, days2: Total number of days for the first and second dates.
• totalDays: Difference in total days between the two dates.
• years, months, days: Calculated differences in years, months, and days.

OUTPUT:
Enter first date (YYYY MM DD):
2023 5 15
Enter second date (YYYY MM DD):
2024 8 10
Difference: 1 years, 3 months, 26 days

Q-22:Write a program in Java to sort an array of integers using the Bubble Sort
algorithm, where the sorting logic is placed inside a method. The program should
also have a separate method to display the sorted array.
Java Program:

import java.util.Scanner;
class BubbleSortMethod

71
72 of 120

{
// Method to perform Bubble Sort
public void bubbleSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Method to display the sorted array
public void displayArray(int arr[]) {
System.out.println("Sorted Array:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
BubbleSortMethod obj = new BubbleSortMethod();

System.out.println("Enter the number of elements to sort:");


int n = sc.nextInt();

72
73 of 120

int arr[] = new int[n];


System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

// Call bubble sort


obj.bubbleSort(arr);

// Call display method to show sorted array


obj.displayArray(arr);
}
}

OUTPUT:
Enter the number of elements to sort:
5
Enter the elements:
45
23
78
56
12
Sorted Array:
12 23 45 56 78

Q-23:Write a program in Java to sort an array of integers using the Selection Sort
algorithm, where the sorting logic is placed inside a method. The program should also
have a separate method to display the sorted array.

73
74 of 120

Java Program:

import java.util.Scanner;

class SelectionSortMethod {

// Method to perform Selection Sort


public void selectionSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_idx = i; // Find the minimum element in unsorted array
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

// Method to display the sorted array


public void displayArray(int arr[]) {
System.out.println("Sorted Array:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
SelectionSortMethod obj = new SelectionSortMethod();

System.out.println("Enter the number of elements to sort:");


int n = sc.nextInt();

int arr[] = new int[n];


System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();

74
75 of 120

// Call selection sort


obj.selectionSort(arr);

// Call display method to show sorted array


obj.displayArray(arr);
}
}

Variable Description:

sc (Scanner): Object used to take input from the user.

n (int): The number of elements in the array to be sorted.

arr[] (int[]): Array that stores the input elements to be sorted.

i, j (int): Loop control variables used during the sorting process.

min_idx (int): Index of the minimum element found during each iteration.

temp (int): Temporary variable used to hold values when swapping elements.

obj (SelectionSortMethod): Object of the SelectionSortMethod class used to call its methods.

Output:

Enter the number of elements to sort:


5
Enter the elements:
64
25
12
22
11

75
76 of 120

Sorted Array:
11 12 22 25 64

Q-24:Write a program in Java to find the GCD (Greatest Common Divisor) of two
numbers, where the logic for finding the GCD is placed inside a method. The program
should also have a separate method to display the GCD.

Java Program:

import java.util.Scanner;

class GCDMethod {

// Method to calculate GCD of two numbers


public int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a; // GCD is stored in 'a'
}

// Method to display the GCD


public void displayGCD(int a, int b, int gcd) {
System.out.println("The GCD of " + a + " and " + b + " is: " + gcd);
}

// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
GCDMethod obj = new GCDMethod();

System.out.println("Enter the first number:");


int num1 = sc.nextInt();

System.out.println("Enter the second number:");


int num2 = sc.nextInt();

// Call the method to calculate GCD


int gcd = obj.findGCD(num1, num2);

// Call the method to display the GCD

76
77 of 120

obj.displayGCD(num1, num2, gcd);


}
}

Variable Description:

sc (Scanner): Used to take input from the user.

num1 (int): First number input by the user.

num2 (int): Second number input by the user.

gcd (int): Stores the GCD of num1 and num2.

temp (int): Temporary variable used to store the value of num2 in GCD calculation.

obj (GCDMethod): Object of the GCDMethod class used to call its methods.

Output:

Enter the first number:


56
Enter the second number:
98
The GCD of 56 and 98 is: 14

Q-25:Write a program in Java to print all the divisors of a given number, where the logic
for finding the divisors is placed inside a method. The program should also have a
separate method to display the divisors.

Java Program:
import java.util.Scanner;
class DivisorsMethod {

// Method to find and print divisors of a number


public void findDivisors(int num) {
System.out.println("Divisors of " + num + " are:");
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}

77
78 of 120

}
System.out.println();
}

// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
DivisorsMethod obj = new DivisorsMethod();

System.out.println("Enter a number:");
int number = sc.nextInt();

// Call the method to find divisors


obj.findDivisors(number);
}
}

Variable Description:
Variable Type Description

sc Scanner Used to take input from the


user.

num int The number input by the


user for which divisors are
to be found.

i int Loop control variable used


to check each divisor.

obj DivisorsMethod Object of the class used to


call methods.

Sample Output in BlueJ:

Enter a number:28
Divisors of 28 are:1 2 4 7 14 28

78
79 of 120

Q-26: Write a program in Java to perform matrix addition, where the logic for adding two
matrices is placed inside a method. The program should also have a separate method to display
the resultant matrix.

Java Program:

import java.util.Scanner;

class MatrixAdditionMethod {

// Method to add two matrices


public int[][] addMatrices(int[][] matrix1, int[][] matrix2, int rows, int cols) {
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}

// Method to display the matrix


public void displayMatrix(int[][] matrix, int rows, int cols) {
System.out.println("Resultant Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
MatrixAdditionMethod obj = new MatrixAdditionMethod();

System.out.println("Enter the number of rows:");


int rows = sc.nextInt();
System.out.println("Enter the number of columns:");
int cols = sc.nextInt();

int[][] matrix1 = new int[rows][cols];


int[][] matrix2 = new int[rows][cols];

System.out.println("Enter the elements of the first matrix:");


for (int i = 0; i < rows; i++) {

79
80 of 120

for (int j = 0; j < cols; j++) {


matrix1[i][j] = sc.nextInt();
}
}

System.out.println("Enter the elements of the second matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix2[i][j] = sc.nextInt();
}
}

// Call method to add matrices


int[][] result = obj.addMatrices(matrix1, matrix2, rows, cols);

// Call method to display the result


obj.displayMatrix(result, rows, cols);
}
}

Variable Type Description

sc Scanner Used to take input from the


user.

rows int The number of rows in the


matrices.

cols int The number of columns in


the matrices.

matrix1[][] int[][] The first matrix input by the


user.

matrix2[][] int[][] The second matrix input by


the user.

result[][] int[][] Stores the result of adding


`matrix1` and `matrix2`.

i, j int Loop control variables to


traverse rows and columns.

obj MatrixAdditionMethod Object of the class used to


call methods.

80
81 of 120

Sample Output in BlueJ:

Enter the number of rows:


2
Enter the number of columns:
2
Enter the elements of the first matrix:
12
34
Enter the elements of the second matrix:
56
78
Resultant Matrix:
68
10 12

Q-27: Write a program in Java to compute the transpose of a matrix, where the logic for
transposing is placed inside a method. The program should also have a separate method to
display the transposed matrix.

Java Program:

import java.util.Scanner;

class MatrixTransposeMethod {

// Method to transpose a matrix


public int[][] transposeMatrix(int[][] matrix, int rows, int cols) {
int[][] transpose = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
return transpose;
}

// Method to display the matrix


public void displayMatrix(int[][] matrix, int rows, int cols) {
System.out.println("Transposed Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();

81
82 of 120

}
}

// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
MatrixTransposeMethod obj = new MatrixTransposeMethod();

System.out.println("Enter the number of rows:");


int rows = sc.nextInt();

System.out.println("Enter the number of columns:");


int cols = sc.nextInt();

int[][] matrix = new int[rows][cols];

System.out.println("Enter the elements of the matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}

// Call method to transpose the matrix


int[][] transpose = obj.transposeMatrix(matrix, rows, cols);

// Call method to display the transposed matrix


obj.displayMatrix(transpose, cols, rows);
}
}

Variable Description
Variable Type Description

sc Scanner Used to take input from the


user.

rows int The number of rows in the


matrix.

cols int The number of columns in


the matrix.

matrix[][] int[][] The matrix input by the


user.

82
83 of 120

transpose[][] int[][] Stores the transposed


matrix.

i, j int Loop control variables to


traverse rows and columns.

obj MatrixTransposeMethod Object of the class used to


call methods.

Sample Output in BlueJ:

Enter the number of rows:


2
Enter the number of columns:
3
Enter the elements of the matrix:
123
456
Transposed Matrix:
14
25
36

Q-27:Write a program to encode a string using the Caesar Cipher, where each letter in the
string is shifted by a fixed number of positions down the alphabet. Non-alphabet characters
should remain unchanged.

Algorithm:
1. Take input of a string and the shift value.
2. Initialize an empty string to store the encoded result.
3. Loop through each character of the string.
4. For each letter:
- Shift it by the specified number of positions.
- Ensure that the shifted letter wraps around (from 'z' to 'a' or 'Z' to 'A').
- Append the shifted letter to the encoded string.
5. Print the encoded string.

83
84 of 120

Java Code:

import java.util.Scanner;

public class CaesarCipher {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string to encode: ");
String input = sc.nextLine();

System.out.print("Enter the shift value: ");


int shift = sc.nextInt();

String encodedStr = "";

for (int i = 0; i < input.length(); i++) {


char ch = input.charAt(i);

if (Character.isLetter(ch)) {
char shifted = (char) (ch + shift);

// Check if the shifted character goes beyond 'z' or 'Z' and wrap around
if (Character.isLowerCase(ch)) {
if (shifted > 'z') {
shifted = (char) (shifted - 26);
} else if (shifted < 'a') {
shifted = (char) (shifted + 26);
}
} else if (Character.isUpperCase(ch)) {
if (shifted > 'Z') {
shifted = (char) (shifted - 26);
} else if (shifted < 'A') {
shifted = (char) (shifted + 26);
}
}

encodedStr += shifted;
} else {
encodedStr += ch; // Keep non-alphabet characters unchanged
}
}

System.out.println("Encoded String: " + encodedStr);


}
}

84
85 of 120

Variable Description Table:


Variable Data Type Description

input String Stores the input string

shift int Number of positions to shift


each letter

encodedStr String Encoded version of the


input string

i int Loop counter

ch char Current character from the


input string

shifted char Shifted character after


applying the cipher

Sample output in BlueJ:


Enter a string to encode: Hello World!
Enter the shift value: 3
Encoded String: Khoor Zruog!

Q-28:Write a Java program using methods to perform the following operations on a string:
1. Count the number of vowels in the string.
2. Reverse the string.
3. Check if the string is a palindrome.
The program should use separate methods for each operation.

Algorithm:
1. Input: Read a string from the user.
2. Vowel Counting:
- Convert the string to lowercase.
- Initialize a counter.
- Loop through the string and check if each character is a vowel (a, e, i, o, u).
- Increment the counter for each vowel found.

85
86 of 120

3. Reversing the String:


- Use a method that reads the string and constructs a new string by appending characters in
reverse order.
4. Palindrome Check:
- Convert the string to lowercase.
- Reverse the string and compare it with the original.
- If they are equal, the string is a palindrome; otherwise, it is not.
5. Output: Print the number of vowels, the reversed string, and whether it is a palindrome.

Variable Description Table:


Variable Data Type Description

input String Stores the input string

vowelCount int Number of vowels in the


input string

reversedStr String Stores the reversed


version of the input string

isPalindrome boolean Stores true if the string is a


palindrome, false if not

ch char Current character being


checked in the string

Output:
Example 1:
Enter a string: Level
Number of vowels: 2
Reversed string: leveL
The string is a palindrome.

Example 2:
Enter a string: Hello World
Number of vowels: 3
Reversed string: dlroW olleH
The string is not a palindrome.

86
87 of 120

Q-29: Write a Java program to add two matrices of size 3x3 using methods.

Algorithm:
1. Define a method to input a matrix.
2. Define another method to add two matrices.
3. In the main method, take input for both matrices and display the sum.

Java Code:

import java.util.Scanner;

public class MatrixAddition {


public static int[][] inputMatrix(Scanner sc, int rows, int cols) {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
return matrix;
}

public static int[][] addMatrices(int[][] mat1, int[][] mat2) {


int[][] sum = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = mat1[i][j] + mat2[i][j];
}
}
return sum;
}

public static void displayMatrix(int[][] matrix) {


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter elements of the first 3x3 matrix:");
int[][] matrix1 = inputMatrix(sc, 3, 3);

System.out.println("Enter elements of the second 3x3 matrix:");


int[][] matrix2 = inputMatrix(sc, 3, 3);

87
88 of 120

int[][] sumMatrix = addMatrices(matrix1, matrix2);

System.out.println("Sum of the matrices:");


displayMatrix(sumMatrix);
}
}

Variable Description Table:


Variable Data Type Description

matrix1 int[][] Stores the elements of the


first 3x3 matrix

matrix2 int[][] Stores the elements of the


second 3x3 matrix

sumMatrix int[][] Stores the sum of the two


matrices

rows, cols int Specifies the size of the


matrix (3x3)

sc Scanner Used to take input from the


user

Output:
Enter elements of the first 3x3 matrix:
123
456
789
Enter elements of the second 3x3 matrix:
987
654
321
Sum of the matrices:
10 10 10
10 10 10
10 10 10

88
89 of 120

Q-30: Write a Java program to demonstrate method overriding. Create a base class `Animal`
with a method `sound()`. Create two derived classes `Dog` and `Cat` that override the `sound()`
method.

Algorithm:
1. Define a class `Animal` with a method `sound()`.
2. Create derived classes `Dog` and `Cat` that override `sound()` to provide specific
implementations.
3. In the main method, demonstrate polymorphism by creating objects of `Animal`, `Dog`, and
`Cat`.
4. Call the `sound()` method on each object

Java Code:
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
public void sound() {
System.out.println("Cat meows");
}
}

public class MethodOverridingDemo {


public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

myAnimal.sound();
myDog.sound();
myCat.sound();
}
}

89
90 of 120

Variable Description Table:


Variable Data Type Description

myAnimal Animal Object of the Animal class

myDog Dog Object of the Dog class

myCat Cat Object of the Cat class

Output:
Animal makes a sound
Dog barks
Cat meows

Q-31: Write a program to declare a square matrix M[Il] of order 'N'. Check if the matrix is a
Doubly Markov matrix or not. A matrix which satisfies the following conditions are Doubly
Markov matrix
[i]All elements are greater than or equal to 0
[ii]Sum of each row is equal to 1. (iii) Sum of each column is equal to 1.
Accept 'N' from the user where 3 <= N <= 9. Display an appropriate error message if 'N' is not in
the given range or the entered numbers are negative. Allow the user to create a matrix and
check whether the created matrix is a Doubly Markov matrix or not

Algorithm:

1. Input Matrix Size:


- Input the order N of the matrix, ensuring that 3 <= N <= 9.
- If N is out of this range, display an error message and terminate.
2. Create and Input the Matrix:
- Declare a square matrix M[N][N].
- For each element of the matrix, input its value and check that it is non-negative.
- If any element is negative, display an error message and terminate.
3. Check Row and Column Sums:
- For each row, calculate the sum of its elements.
- If any row's sum is not equal to 1, the matrix is not a Doubly Markov matrix.
- For each column, calculate the sum of its elements.
- If any column's sum is not equal to 1, the matrix is not a Doubly Markov matrix.
4. Determine if Matrix is Doubly Markov:

90
91 of 120

- If all elements are non-negative and the sum of each row and each column is equal to 1,
display that the matrix is a "Doubly Markov Matrix".
- Otherwise, display "Not a Doubly Markov Matrix".

Program:

import java.util.Scanner;

public class DoublyMarkovMatrix {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input size of matrix


System.out.print("Enter the order of the matrix (3 <= N <= 9): ");
int N = sc.nextInt();

// Validate the size of the matrix


if (N < 3 || N > 9) {
System.out.println("Error: Matrix order must be between 3 and 9.");
return;
}

// Declare the matrix


double[][] M = new double[N][N];

// Input matrix elements and check for non-negative values


System.out.println("Enter the elements of the matrix: ");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
M[i][j] = sc.nextDouble();
if (M[i][j] < 0) {
System.out.println("Error: Negative values are not allowed.");
return;
}
}
}

// Check if the matrix is a Doubly Markov Matrix


boolean isDoublyMarkov = true;

// Check row sums


for (int i = 0; i < N; i++) {
double rowSum = 0;
for (int j = 0; j < N; j++) {
rowSum += M[i][j];

91
92 of 120

}
if (rowSum != 1) {
isDoublyMarkov = false;
break;
}
}

// Check column sums


for (int j = 0; j < N; j++) {
double colSum = 0;
for (int i = 0; i < N; i++) {
colSum += M[i][j];
}
if (colSum != 1) {
isDoublyMarkov = false;
break;
}
}

// Output result
if (isDoublyMarkov) {
System.out.println("The matrix is a Doubly Markov Matrix.");
} else {
System.out.println("The matrix is NOT a Doubly Markov Matrix.");
}
}
}
Variable Description Table:
Variable Name Data Type Description

N int Order of the matrix

M double[][] 2D array to store matrix


elements

i, j int Loop counters for rows and


columns

rowSum double Sum of the elements of a


row

colSum double Sum of the elements of a


column

isDoublyMarkov boolean Variable to check if matrix


is Doubly Markov

92
93 of 120

Sample Output:

Example 1:
Enter the order of the matrix (3 <= N <= 9): 3
Enter the elements of the matrix:
0.2 0.4 0.4
0.5 0.3 0.2
0.3 0.3 0.4
The matrix is NOT a Doubly Markov Matrix.

Example 2:
Enter the order of the matrix (3 <= N <= 9): 3
Enter the elements of the matrix:
0.5 0.5 0.0
0.3 0.4 0.3
0.2 0.1 0.7
The matrix is a Doubly Markov Matrix.

Q-32:Hamming numbers are positive integer numbers whose prime factors include 2,3 and 5
only Example: n = 6 is an hamming number as 6 = 2 * 3. So its prime factors are limited to 2, 3
n= 8 is an hamming number as 8 = 2 x 2 x 2 and it has only 2 as its prime factors n = 90 is an
hamming number as 90 = 2 × 3 x 3 x 5 which has only 2, 3, 5 as prime factors n = 14 is not a
hamming number as 14 = 2 x 7.it has 7 as one of its prime factor n = 44 is not a hamming
number as 44 = 2 x 2 x 11. It has 11 as one of its prime factors Design a program to accept any
positive integer number and check if it is a Hamming number or not. Display the result with an
appropriate message in the format specified below. The program should also generate error
message if a negative number is entered. Test your program for the following data and some
random data.

Algorithm:

1. Input Validation:
- Accept the number n from the user.
- If n is negative, display an error message "Error: Negative numbers are not allowed" and
terminate.

2. Prime Factorization Check:


- If n is 0 or 1, it is a Hamming number (since 1 has no prime factors, and we can treat it as
valid).
- For other values of n, continuously divide the number by 2, 3, or 5 as long as it is divisible by
them.
- If after dividing the number becomes 1, it is a Hamming number.
- If any other factor is encountered, the number is not a Hamming number.

3. Display the result:

93
94 of 120

- If the number is a Hamming number, display "n is a Hamming number."


- If the number is not a Hamming number, display "n is NOT a Hamming number."
- Display an error message for negative inputs.

Program (Java in BlueJ):

import java.util.Scanner;

public class HammingNumberCheck {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input number
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();

// Check for negative number


if (n < 0) {
System.out.println("Error: Negative numbers are not allowed.");
return;
}

// Function to check if a number is a Hamming number


if (isHammingNumber(n)) {
System.out.println(n + " is a Hamming number.");
} else {
System.out.println(n + " is NOT a Hamming number.");
}
}

// Method to check if n is a Hamming number


public static boolean isHammingNumber(int n) {
if (n == 1) return true;

while (n % 2 == 0) n /= 2;
while (n % 3 == 0) n /= 3;
while (n % 5 == 0) n /= 5;

return n == 1;
}
}

94
95 of 120

Variable Description Table:


Variable Name Data Type Description

n int The input number to check


if it is a Hamming number

sc Scanner Scanner object to read


user input

isHammingNumber boolean Boolean method to check if


the number is Hamming

Sample Output:

Example 1:
Enter a positive integer: 90
90 is a Hamming number.

Example 2:
Enter a positive integer: 44
44 is NOT a Hamming number.

Example 3:
Enter a positive integer: -5
Error: Negative numbers are not allowed.

Q-33: Write a program to accept a sentence which may be terminated by either'!, '?' or '!' only.
The words may be separated by a single blank spaces and are in UPPER CASE.
Perform the following tasks:
(a) Count number of vowels and consonants present in each word (b)
Generate the output of the frequency in form of a bar graph, where V denotes vowels and C
consonants

Algorithm:

1. Input Sentence:
- Accept a sentence from the user. Ensure it ends with either '.', '!', or '?'.
- If the sentence does not end with any of these, display an error message and terminate.

2. Split Words:
- Split the sentence into individual words using spaces as separators.
- Check that each word is in uppercase.

95
96 of 120

3. Count Vowels and Consonants:


- For each word, count the number of vowels (A, E, I, O, U) and consonants.
- Store the count for each word.

4. Generate Frequency Bar Graph:


- For each word, display a bar graph where 'V' represents vowels and 'C' represents
consonants.
- Display the result word by word.

5. Output the result:


- Display each word followed by its vowel-consonant bar graph.

Program (Java in BlueJ):

import java.util.Scanner;

public class VowelConsonantBarGraph {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input sentence
System.out.print("Enter a sentence ending with '.', '!', or '?': ");
String sentence = sc.nextLine();

// Check if the sentence ends with valid punctuation


if (!sentence.endsWith(".") && !sentence.endsWith("!") && !sentence.endsWith("?")) {
System.out.println("Error: Sentence must end with '.', '!', or '?'.");
return;
}

// Split the sentence into words


String[] words = sentence.trim().split(" ");

// Process each word


for (String word : words) {
word = word.toUpperCase();
int vowelCount = 0, consonantCount = 0;
// Count vowels and consonants
for (char ch : word.toCharArray()) {
if (isVowel(ch)) {
vowelCount++;
} else if (Character.isLetter(ch)) {
consonantCount++;
}

96
97 of 120

// Print the word and bar graph


System.out.print(word + ": ");
printBarGraph(vowelCount, consonantCount);
}
}

// Helper method to check if a character is a vowel


public static boolean isVowel(char ch) {
return "AEIOU".indexOf(ch) != -1;
}

// Method to print the bar graph


public static void printBarGraph(int vowels, int consonants) {
for (int i = 0; i < vowels; i++) {
System.out.print("V");
}
for (int i = 0; i < consonants; i++) {
System.out.print("C");
}
System.out.println();
}
}
Variable Description Table:
Variable Name Data Type Description

sentence String The input sentence

words String[] Array to store individual


words of the sentence

vowelCount int Number of vowels in the


word

consonantCount int Number of consonants in


the word

ch char Character from the word


being checked

sc Scanner Scanner object to read


user input

97
98 of 120

Sample Output:

Example 1:
Enter a sentence ending with '.', '!', or '?': HELLO WORLD!
HELLO: VVCCC
WORLD: VCCCC

Example 2:
Enter a sentence ending with '.', '!', or '?': JAVA IS FUN?
JAVA: VCCV
IS: VC
FUN: VCC
Q-34: A class Encode has been defined to replace only the vowels in a word by the next
corresponding vowel and form a new word. i.e. A → E, E → I, I → O, O → U, U → A and a → e,
e → i, i → o, o → u, and u → a Example: Input: Institution Output: Onstotatoun Some of the
members of the class are given below: Class name Data members/instance variables: word
length new_word Methods / Member functions: Encode( ) void acceptWord( ) void nextVowel( )
void display( ) : : : : : : : : Encode to store a word integer to store the length of the word to store
the encoded word default constructor to initialize data members with legal initial values to
accept a word to replace only the vowels from the word stored in ‘word’ by the next
corresponding vowel and to assign it to ‘newword’, with the remaining alphabets unchanged to
display the original word along with the encrypted word Specify the class Encode giving details
of the constructor( ), void acceptWord( ), void nextVowel( ) and void display( ). Define a main ( )
function to create an object and call the functions accordingly to enable the task.

Algorithm:

1. Input Sentence:
- Accept a sentence from the user. Ensure it ends with either '.', '!', or '?'.
- If the sentence does not end with any of these, display an error message and terminate.

2. Split Words:
- Split the sentence into individual words using spaces as separators.
- Check that each word is in uppercase.

3. Count Vowels and Consonants:


- For each word, count the number of vowels (A, E, I, O, U) and consonants.
- Store the count for each word.

4. Generate Frequency Bar Graph:


- For each word, display a bar graph where 'V' represents vowels and 'C' represents
consonants.
- Display the result word by word.

98
99 of 120

5. Output the result:


- Display each word followed by its vowel-consonant bar graph.

Program (Java in BlueJ):

import java.util.Scanner;

public class VowelConsonantBarGraph {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input sentence
System.out.print("Enter a sentence ending with '.', '!', or '?': ");
String sentence = sc.nextLine();

// Check if the sentence ends with valid punctuation


if (!sentence.endsWith(".") && !sentence.endsWith("!") && !sentence.endsWith("?")) {
System.out.println("Error: Sentence must end with '.', '!', or '?'.");
return;
}

// Split the sentence into words


String[] words = sentence.trim().split(" ");

// Process each word


for (String word : words) {
word = word.toUpperCase();
int vowelCount = 0, consonantCount = 0;

// Count vowels and consonants


for (char ch : word.toCharArray()) {
if (isVowel(ch)) {
vowelCount++;
} else if (Character.isLetter(ch)) {
consonantCount++;
}
}

// Print the word and bar graph


System.out.print(word + ": ");
printBarGraph(vowelCount, consonantCount);
}
}

// Helper method to check if a character is a vowel

99
100 of 120

public static boolean isVowel(char ch) {


return "AEIOU".indexOf(ch) != -1;
}

// Method to print the bar graph


public static void printBarGraph(int vowels, int consonants) {
for (int i = 0; i < vowels; i++) {
System.out.print("V");
}
for (int i = 0; i < consonants; i++) {
System.out.print("C");
}
System.out.println();
}
}

Variable Description Table:


Variable Name Data Type Description

sentence String The input sentence

words String[] Array to store individual


words of the sentence

vowelCount int Number of vowels in the


word

consonantCount int Number of consonants in


the word

ch char Character from the word


being checked

sc Scanner Scanner object to read


user input

Sample Output:

Example 1:
Enter a sentence ending with '.', '!', or '?': HELLO WORLD!
HELLO: VVCCC
WORLD: VCCCC

Example 2:
Enter a sentence ending with '.', '!', or '?': JAVA IS FUN?

100
101 of 120

JAVA: VCCV
IS: VC
FUN: VCC

Algorithm:

1. Start
2. Create a class `Encode` with instance variables to store the original word, the encoded word,
and the length.
3. Define the constructor to initialize the word and the new word as empty and length as 0.
4. In the `acceptWord` method, accept a word from the user and store it in the `word` variable.
Also, calculate its length.
5. In the `nextVowel` method, iterate over each character of the word:
- If the character is a vowel, replace it with the next corresponding vowel.
- Otherwise, leave the character unchanged.
- Store the result in `new_word`.
6. In the `display` method, print both the original word and the encoded word.
7. In the main function, create an object of the `Encode` class, call the `acceptWord`,
`nextVowel`, and `display` methods.
8. Stop

import java.util.Scanner;

public class Encode {


// Instance variables
private String word; // Original word
private int length; // Length of the word
private String new_word; // Encoded word

// Constructor to initialize data members


public Encode() {
word = "";
length = 0;
new_word = "";
}

// Method to accept a word from the user


public void acceptWord() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
word = sc.nextLine();
length = word.length();
}

101
102 of 120

// Method to replace the vowels with the next corresponding vowel


public void nextVowel() {
new_word = ""; // Initialize new_word as empty
for (int i = 0; i < length; i++) {
char ch = word.charAt(i);
switch (ch) {
case 'A': new_word += 'E'; break;
case 'E': new_word += 'I'; break;
case 'I': new_word += 'O'; break;
case 'O': new_word += 'U'; break;
case 'U': new_word += 'A'; break;
case 'a': new_word += 'e'; break;
case 'e': new_word += 'i'; break;
case 'i': new_word += 'o'; break;
case 'o': new_word += 'u'; break;
case 'u': new_word += 'a'; break;
default: new_word += ch; // If not a vowel, leave it unchanged
}
}
}

// Method to display the original word and the encoded word


public void display() {
System.out.println("Original Word: " + word);
System.out.println("Encoded Word: " + new_word);
}

// Main method to test the Encode class


public static void main(String[] args) {
Encode obj = new Encode(); // Create an object of Encode class
obj.acceptWord(); // Accept the word from the user
obj.nextVowel(); // Replace vowels with next corresponding vowel
obj.display(); // Display the original and encoded words
}
}
Variable Description Table:
Variable Name Data Type Description

word String Stores the original word


entered by the user

length int Stores the length of the


original word

102
103 of 120

new_word String Stores the encoded word


after replacing vowels

ch char Character used to iterate


through the word

sc Scanner Scanner object to accept


input from the user

obj Encode Object of the Encode class


used to call methods

Sample Output:

Example 1:
Enter a word: INSTITUTION
Original Word: INSTITUTION
Encoded Word: ONSTOTATOUN

Example 2:
Enter a word: JAVA
Original Word: JAVA
Encoded Word: JEVE

103
104 of 120

Algorithm:

1. Initialize Shelf:
- Set the maximum limit (lim) of the shelf to n.
- Initialize front and rear to 0.
- Create an array ele[] to hold decimal numbers of size lim.

2. pushVal(double v):
- Check if the rear has reached the limit (lim).
- If rear == lim, print "SHELF IS FULL".
- Else, insert the value v at index rear and increment rear.

3. popVal():
- Check if front equals rear (indicating the shelf is empty).

104
105 of 120

- If front == rear, return -999.99 to indicate the shelf is empty.


- Else, return the value at ele[front] and increment front.

4. display():
- Display all the elements from front to rear.

Java Program:

import java.util.Scanner;

class Shelf {
double[] ele; // array to hold decimal numbers
int lim; // maximum limit of the shelf
int front; // index of the front end
int rear; // index of the rear end

// Constructor to initialize lim, front, and rear


Shelf(int n) {
lim = n;
front = 0;
rear = 0;
ele = new double[lim];
}

// Function to push decimal numbers at the rear end


public void pushVal(double v) {
if (rear == lim) {
System.out.println("SHELF IS FULL");
} else {
ele[rear] = v;
rear++;
}
}

// Function to remove and return decimal number from the front end
public double popVal() {
if (front == rear) {
return -999.99; // indicating the shelf is empty
} else {
double val = ele[front];
front++;
return val;
}
}

105
106 of 120

// Function to display elements of the shelf


public void display() {
if (front == rear) {
System.out.println("SHELF IS EMPTY");
} else {
System.out.println("Shelf contents: ");
for (int i = front; i < rear; i++) {
System.out.print(ele[i] + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the shelf: ");
int n = sc.nextInt();
Shelf shelf = new Shelf(n);

while (true) {
System.out.println("\n1. Push Value");
System.out.println("2. Pop Value");
System.out.println("3. Display Shelf");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter value to push: ");
double val = sc.nextDouble();
shelf.pushVal(val);
break;
case 2:
double poppedValue = shelf.popVal();
if (poppedValue == -999.99) {
System.out.println("SHELF IS EMPTY");
} else {
System.out.println("Popped value: " + poppedValue);
}
break;
case 3:
shelf.display();
break;
case 4:
System.out.println("Exiting...");
sc.close();

106
107 of 120

return;
default:
System.out.println("Invalid choice!");
}
}
}
}

Variable Descriptions:
Variable Type Description

ele[] double Array to store the decimal


numbers in the shelf.

lim int Maximum capacity of the


shelf.

front int Points to the index of the


front end of the shelf.

rear int Points to the index of the


rear end of the shelf.

n int Size of the shelf, input by


the user.

v double Decimal number to be


pushed onto the shelf.

val double Decimal number popped


from the front of the shelf.

choice int User's choice for the


operation (push, pop,
display, exit).

Example Output:

Enter the size of the shelf: 3

1. Push Value
2. Pop Value
3. Display Shelf
4. Exit
Enter your choice: 1
Enter value to push: 10.5

107
108 of 120

1. Push Value
2. Pop Value
3. Display Shelf
4. Exit
Enter your choice: 3
Shelf contents:
10.5

1. Push Value
2. Pop Value
3. Display Shelf
4. Exit
Enter your choice: 2
Popped value: 10.5

Q-35: A class Mixer has been defined to merge two sorted integer arrays in ascending order.
Some of the members of the class are given below:
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:
- Mixer(int nn): Constructor to assign n = nn
- void accept(): To accept the elements of the array in ascending order without duplicates
- Mixer mix(Mixer A): To merge the current object array elements with the parameterized array
elements and return the resultant object
- void display(): To display the elements of the array

Algorithm:
1. Start
2. Define the class Mixer with instance variables arr[] to hold the array elements and n for the
size of the array.
3. Define the constructor Mixer(int nn) to initialize the size of the array.
4. In accept(), allow the user to enter elements in ascending order and store them without
duplicates.
5. In mix(Mixer A), merge the two sorted arrays from the current object and the parameterized
Mixer object A.
6. Ensure that the merged array is sorted and contains no duplicates.
7. In display(), print the elements of the array.
8. In main(), create two Mixer objects, accept array elements, merge the two arrays, and display
the resulting array.
9. End

108
109 of 120

Java Program:
import java.util.Scanner;

public class Mixer {


private int arr[];
private int n;

public Mixer(int nn) {


n = nn;
arr = new int[n];
}

public void accept() {


Scanner sc = new Scanner(System.in);
System.out.println("Enter " + n + " elements in ascending order:");
int i = 0;
while (i < n) {
int element = sc.nextInt();
if (i == 0 || element > arr[i - 1]) {
arr[i] = element;
i++;
} else {
System.out.println("Please enter a unique value greater than the previous one.");
}
}
}

public Mixer mix(Mixer A) {


int[] result = new int[this.n + A.n];
int i = 0, j = 0, k = 0;

while (i < this.n && j < A.n) {


if (this.arr[i] < A.arr[j]) {
result[k++] = this.arr[i++];
} else if (this.arr[i] > A.arr[j]) {
result[k++] = A.arr[j++];
} else {
result[k++] = this.arr[i++];
j++;
}
}

while (i < this.n) {


result[k++] = this.arr[i++];
}
while (j < A.n) {
result[k++] = A.arr[j++];

109
110 of 120

Mixer merged = new Mixer(k);


for (int m = 0; m < k; m++) {
merged.arr[m] = result[m];
}
return merged;
}

public void display() {


System.out.print("Array elements: ");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter size of first array: ");
int size1 = sc.nextInt();
Mixer m1 = new Mixer(size1);
m1.accept();

System.out.print("Enter size of second array: ");


int size2 = sc.nextInt();
Mixer m2 = new Mixer(size2);
m2.accept();

Mixer mergedMixer = m1.mix(m2);


System.out.println("Merged Array:");
mergedMixer.display();
}
}

Variable Description Table:


Variable Name Data Type Description

arr[] int[] Array to store the elements


in ascending order

n int Size of the array

element int Element entered by the


user

110
111 of 120

result[] int[] Temporary array to store


merged array elements

i, j, k int Index variables for iteration


during merging

size1, size2 int Size of the first and second


arrays

m1, m2 Mixer Mixer objects representing


arrays to be merged

mergedMixer Mixer Mixer object representing


the merged array

Sample Output:
Enter size of first array: 3
Enter 3 elements in ascending order:
1
3
5
Enter size of second array: 4
Enter 4 elements in ascending order:
2
3
6
7
Merged Array:
Array elements: 1 2 3 5 6 7

Q-36: A class Shift contains a two-dimensional integer array of order (m × n) where the
maximum values of both m and n is 5.
Design the class Shift to shuffle the matrix (i.e. the first row becomes the last, the second row
becomes the first and so on).

The details of the members of the class are given below:


Class name: Shift
Data members/instance variables:
mat[][]: stores the array elements
m: integer to store the number of rows
n: integer to store the number of columns

Member functions/methods:
Shift(int mm, int nn): parameterized constructor to initialize the data members m = mm and n
= nn

111
112 of 120

void input(): enters the elements of the array


void cyclic(Shift p): enables the matrix of the object (p) to shift each row upwards in a cyclic
manner and store the resultant matrix in the current object
void display(): displays the matrix elements

Specify the class Shift giving details of the constructor, void input(), void cyclic(Shift) and void
display(). Define the main() function to create an object and call the methods accordingly to
enable the task of shifting the array elements.

Algorithm:
1. Start.
2. Class definition:
- Define the class `Shift` with the following members:
- A 2D array `mat[][]` to store matrix elements.
- Variables `m` and `n` to store the number of rows and columns, respectively.
- Define the parameterized constructor to initialize the number of rows and columns.
3. Input method:
- Accept elements from the user and store them in the matrix `mat[][]`.
4. Cyclic method:
- Define `cyclic(Shift p)` to cyclically shift rows of matrix `p` upwards and store the result in the
current object's matrix.
5. Display method:
- Define `display()` to display the matrix elements.
6. Main function:
- Create objects of the `Shift` class.
- Input matrix elements and perform the cyclic shift using the method `cyclic()`.
- Display the original and shifted matrices.
7. End.

Java Program:

import java.util.Scanner;

public class Shift {


private int[][] mat;
private int m, n;

// Constructor to initialize m and n


public Shift(int mm, int nn) {
m = mm;
n = nn;
mat = new int[m][n];
}

112
113 of 120

// Method to input elements of the matrix


public void input() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements of the matrix (" + m + " x " + n + "):");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mat[i][j] = sc.nextInt();
}
}
}

// Method to cyclically shift rows upwards from another object matrix


public void cyclic(Shift p) {
for (int i = 0; i < m - 1; i++) {
mat[i] = p.mat[i + 1];
}
mat[m - 1] = p.mat[0]; // First row becomes the last
}

// Method to display the matrix


public void display() {
System.out.println("Matrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}

// Main function to test the class


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of rows (max 5): ");


int rows = sc.nextInt();
System.out.print("Enter the number of columns (max 5): ");
int cols = sc.nextInt();

// Create object p1 to input the matrix


Shift p1 = new Shift(rows, cols);
p1.input();

// Create another object p2 to store the shifted matrix


Shift p2 = new Shift(rows, cols);
p2.cyclic(p1);

113
114 of 120

// Display original matrix


System.out.println("Original Matrix:");
p1.display();

// Display shifted matrix


System.out.println("Shifted Matrix:");
p2.display();
}
}

Variable Description Table:


Variable Name Data Type Description

mat[][] int[][] Array to store matrix


elements

m int Number of rows in the


matrix

n int Number of columns in the


matrix

i, j int Loop control variables

p Shift An object of class Shift


used to pass another
matrix for cyclic shift

rows, cols int Number of rows and


columns entered by the
user

p1, p2 Shift Objects of class Shift

Sample Output:

Enter the number of rows (max 5): 3


Enter the number of columns (max 5): 3
Enter the elements of the matrix (3 x 3):
123
456
789
Original Matrix:
123
456

114
115 of 120

789
Shifted Matrix:
456
789
123

Q-38: Class: Marks


Member data: m as integer
Member functions:
- void readdata(): Inputs the marks of the students.
- void compare(Marks): Displays greater m out of argument object and current object.
WAP to input marks of two students and display greater marks.

Algorithm:

1. Define a class `Marks` with an integer variable `m`.


2. Create a method `readdata()` to input the marks of the student.
3. Implement `compare(Marks obj)` to display the greater of two marks.
4. Create two objects of `Marks` and input the values using `readdata()`.
5. Use `compare()` to determine and display the greater mark.

Java Program:

class Marks {
private int m;

public void readdata() {


Scanner sc = new Scanner(System.in);
System.out.print("Enter marks: ");
m = sc.nextInt();
}

public void compare(Marks obj) {


if (this.m > obj.m) {
System.out.println("Greater marks: " + this.m);
} else {
System.out.println("Greater marks: " + obj.m);
}
}

public static void main(String[] args) {


Marks student1 = new Marks();
Marks student2 = new Marks();

115
116 of 120

student1.readdata();
student2.readdata();

student1.compare(student2);
}
}

Variable Description:
Variable Type Description

m int Stores the marks of the


student

student1 Marks Object of class Marks

student2 Marks Object of class Marks

Expected Output:

Enter marks: 75
Enter marks: 85
Greater marks: 85

Q-39: Class: Marks


Member data: m as integer
Member functions:
- void readdata(): Inputs the marks of the students.
- Marks compare(Marks): Returns the object of the marks which is greater value of m.
- void display(): Display the value of m.
WAP to input marks of two students and display greater marks.

Algorithm:

1. Define a class `Marks` with an integer variable `m`.


2. Create a method `readdata()` to input the marks of the student.
3. Implement `Marks compare(Marks obj)` to return the object which has the greater marks.
4. Create two objects of `Marks` and input the values using `readdata()`.
5. Use `compare()` to determine and return the object with the greater marks.
6. Call `display()` on the returned object to show the greater marks.

116
117 of 120

Java Program:

class Marks {
private int m;

public void readdata() {


Scanner sc = new Scanner(System.in);
System.out.print("Enter marks: ");
m = sc.nextInt();
}

public Marks compare(Marks obj) {


if (this.m > obj.m) {
return this;
} else {
return obj;
}
}

public void display() {


System.out.println("Marks: " + m);
}

public static void main(String[] args) {


Marks student1 = new Marks();
Marks student2 = new Marks();

student1.readdata();
student2.readdata();

Marks greater = student1.compare(student2);


greater.display();
}
}

Variable Description:
Variable Type Description

m int Stores the marks of the


student

student1 Marks Object of class Marks

student2 Marks Object of class Marks

greater Marks Object with the greater


marks

117
118 of 120

Expected Output:

Enter marks: 70
Enter marks: 80
Marks: 80

Q-40: Define a class `Distance` with member functions and member data: `feet` and `inch` as
integers.
Member functions are:
- void readdata(): To input distance in feet and inches.
- int convert(): Returns the distance in inches.
- void volume(Distance, Distance): Calculates and displays the volume in cubic inches.
- void area(Distance): Calculates and displays the area in square inches.
- void display(): Displays the distance in feet and inches.

Use the above class definition to input the dimensions of the room and calculate the volume in
cubic inches and area in square inches.

Algorithm:

1. Define a class `Distance` with two integer variables `feet` and `inch`.
2. Create a method `readdata()` to input the distance in feet and inches.
3. Implement `convert()` to return the total distance in inches.
4. Create `volume(Distance d1, Distance d2)` to calculate the volume in cubic inches.
5. Create `area(Distance d1)` to calculate the area in square inches.
6. Implement `display()` to show the distance in feet and inches format.
7. Input two distances using `readdata()` and display the calculated volume and area.

Java Program:

class Distance {
private int feet, inch;

public void readdata() {


Scanner sc = new Scanner(System.in);
System.out.print("Enter feet: ");
feet = sc.nextInt();
System.out.print("Enter inches: ");
inch = sc.nextInt();
}

public int convert() {


return (feet * 12) + inch;
}

118
119 of 120

public void volume(Distance d1, Distance d2) {


int volume = this.convert() * d1.convert() * d2.convert();
System.out.println("Volume in cubic inches: " + volume);
}

public void area(Distance d1) {


int area = this.convert() * d1.convert();
System.out.println("Area in square inches: " + area);
}

public void display() {


System.out.println("Distance: " + feet + " feet, " + inch + " inches");
}

public static void main(String[] args) {


Distance d1 = new Distance();
Distance d2 = new Distance();
Distance height = new Distance();

d1.readdata();
d2.readdata();
height.readdata();

height.volume(d1, d2);
d1.area(d2);
}
}

Variable Description:
Variable Type Description

feet int Stores the feet part of the


distance

inch int Stores the inch part of the


distance

d1, d2 Distance Objects representing two


distances

height Distance Object representing the


height for volume
calculation

Expected Output:

Enter feet: 5

119
120 of 120

Enter inches: 8
Enter feet: 3
Enter inches: 4
Enter feet: 2
Enter inches: 6
Volume in cubic inches: 13536
Area in square inches: 1248

120

You might also like