compFinalProject
compFinalProject
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
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
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
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
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
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
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
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.
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);
}
}
21
22 of 120
Variable Description
Variable Data Type Description
Expected Output
Enqueued: 10
Enqueued: 20
Enqueued: 30
Queue: 10 20 30
Dequeued: 10
Queue: 20 30
Enqueued: 40
Queue: 20 30 40
22
23 of 120
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
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
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
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
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
33
34 of 120
if (m >= n)
{
System.out.println("INVALID INPUT");
return;
}
System.out.println("THE PRIME‐ADAM INTEGERS ARE:");
count);
}}
34
35 of 120
Output:
Algorithm:
1. Start
2. Input two integers m and n.
35
36 of 120
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:
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:
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:
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
42
43 of 120
{
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) != '?'
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
47
48 of 120
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
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
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.
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
57
58 of 120
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
PROGRAM:
import java.util.Scanner;
class StackArray {
59
60 of 120
60
61 of 120
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
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:
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
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
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
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
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
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();
72
73 of 120
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 {
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
SelectionSortMethod obj = new SelectionSortMethod();
74
75 of 120
Variable Description:
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:
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 {
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
GCDMethod obj = new GCDMethod();
76
77 of 120
Variable Description:
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:
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 {
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();
Variable Description:
Variable Type Description
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 {
79
80 of 120
80
81 of 120
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 {
81
82 of 120
}
}
// Main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
MatrixTransposeMethod obj = new MatrixTransposeMethod();
Variable Description
Variable Type Description
82
83 of 120
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;
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
}
}
84
85 of 120
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
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;
87
88 of 120
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");
}
}
myAnimal.sound();
myDog.sound();
myCat.sound();
}
}
89
90 of 120
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:
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;
91
92 of 120
}
if (rowSum != 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
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.
93
94 of 120
import java.util.Scanner;
// Input number
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
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
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
import java.util.Scanner;
// Input sentence
System.out.print("Enter a sentence ending with '.', '!', or '?': ");
String sentence = sc.nextLine();
96
97 of 120
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.
98
99 of 120
import java.util.Scanner;
// Input sentence
System.out.print("Enter a sentence ending with '.', '!', or '?': ");
String sentence = sc.nextLine();
99
100 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?
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;
101
102 of 120
102
103 of 120
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
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
// 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
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
Example Output:
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;
109
110 of 120
110
111 of 120
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).
Member functions/methods:
Shift(int mm, int nn): parameterized constructor to initialize the data members m = mm and n
= nn
111
112 of 120
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;
112
113 of 120
113
114 of 120
Sample Output:
114
115 of 120
789
Shifted Matrix:
456
789
123
Algorithm:
Java Program:
class Marks {
private int m;
115
116 of 120
student1.readdata();
student2.readdata();
student1.compare(student2);
}
}
Variable Description:
Variable Type Description
Expected Output:
Enter marks: 75
Enter marks: 85
Greater marks: 85
Algorithm:
116
117 of 120
Java Program:
class Marks {
private int m;
student1.readdata();
student2.readdata();
Variable Description:
Variable Type Description
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;
118
119 of 120
d1.readdata();
d2.readdata();
height.readdata();
height.volume(d1, d2);
d1.area(d2);
}
}
Variable Description:
Variable Type Description
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