0% found this document useful (0 votes)
32 views123 pages

Isc Computer Science Project

The document describes a Java program to accept two single dimensional arrays of lengths specified by the user, merge the two arrays, and display the merged array. The algorithm accepts the length and elements of the first array, then the length and elements of the second array. A merged array is created with the total length of both arrays. Elements from the first and second arrays are added to the merged array in order, and the merged array is displayed as output.

Uploaded by

bibek64m5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views123 pages

Isc Computer Science Project

The document describes a Java program to accept two single dimensional arrays of lengths specified by the user, merge the two arrays, and display the merged array. The algorithm accepts the length and elements of the first array, then the length and elements of the second array. A merged array is created with the total length of both arrays. Elements from the first and second arrays are added to the merged array in order, and the merged array is displayed as output.

Uploaded by

bibek64m5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 123

Write a program in java to accept

inputs in an SDA of the length


desired by the user and display
the array in ascending order
sorted by ‘Bubble Sort’ method.
For example :-
Input :- {10, 9, 8, 7, 6, 5, 4, 3,
2, 1}
Output :- {1, 2, 3, 4, 5, 6, 7, 8,
9, 10}
Algorithm:-
1. Start
2. Import the java.util package
3. Create a class
4. Create a main function
5. Create a scanner object
6. Ask the user to input the number of elements in the
array.
7. Create an array of integers with the size specified by
the user input.
8. Ask the user to input the elements of the array.
9. Iterate through the array using a nested loop.
10. In the outer loop, iterate through the array from the
first element to the second-to-last element.
11. In the inner loop, iterate through the array from the
first element to the element before the current last
element in the outer loop.
12. Compare the current element with the next element in the
array.
13. If the current element is greater than the next element,
swap them.
14. Continue iterating until the end of the array.
15. Print the sorted array.
16. Stop.
Code:-

import java.util.*;

class BubbleSort {

static void main(String args[]){

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of elements in the array");

int arr[] = new int[in.nextInt()];

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

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

arr[i] = in.nextInt();

for (int i = 0; i < arr.length - 1; i++){

for (int j = 0; j < arr.length - i - 1; j++){

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

System.out.println("Sorted array");

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

System.out.print(arr[i] + " ");

}
Output

Variable description
Write a program in java to accept
a binary number and display its
decimal equivalent
Example :-
Input :- 11111
Output :- 31
Algorithm :-
1. Start
2. Create a class
3. Declare a Scanner object named "in" to get the user
input
4. Print a message asking the user to enter a binary number
5. Declare a long variable named "num" and get the binary
number from the user using "in.nextLong()"
6. Declare an integer variable named "decimalNumber" and
initialize it to 0
7. Declare an integer variable named "i" and initialize it
to 0
8. Use a while loop to convert the binary number to decimal
number
9. Inside the loop, calculate the remainder of "num"
divided by 10 and store it in a variable named
"remainder"
10. Divide the "num" by 10 and store the result in "num"
11. Calculate the decimal number by adding the product of
"remainder" and 2 raised to the power of "i" to
"decimalNumber"
12. Increment the value of "i" by 1
13. Continue the loop until "num" becomes 0
14. Print the decimal equivalent of the binary number by
displaying the value of "decimalNumber"
15. Stop
Code:-

import java.util.*;

class Main {

static void main() {

Scanner in = new Scanner(System.in);

System.out.println("Enter the binary number");

long remainder, num = in.nextLong();

int decimalNumber = 0, i = 0;

while (num != 0) {

remainder = num % 10; num /= 10;

decimalNumber += remainder * Math.pow(2, i); ++i;

System.out.println("Decimal Equivalent = " + decimalNumber);

}
Output

Variable Description
Write a program in java to accept
integers in an SDA of the length
desired by the user and find the
element given input by the user in
the array by using ‘Binary Search’
technique.
Example :-
Input array :- 1, 2, 3
Element to be searched :- 4
Output :- Element not found
Input array :- 1, 2, 3, 4, 5.
Element to be searched :- 4
Output :- Element found at index 3
Algorithm:-
1. Start
2. Take input for the length of the array from the user and
store it in a variable 'length'
3. Create an integer array of length 'length'
4. Take input for the elements of the array from the user
and store them in the array using a loop
5. Take input for the element to be searched from the user
and store it in a variable 'searchElement'
6. Set 'left' to 0 and 'right' to length-1
7. Repeat steps 8-14 while 'left' is less than or equal to
'right'
8. Set 'mid' to the floor of the average of 'left' and
'right'
9. If the element at 'mid' is equal to 'searchElement',
print "Element found at index 'mid'" and exit the loop
10. If the element at 'mid' is less than 'searchElement',
set 'left' to mid+1
11. If the element at 'mid' is greater than 'searchElement',
set 'right' to mid-1
12. End the loop
13. If 'left' is greater than 'right', print "Element not
found"
14. Stop
Code:-

import java.util.*;

class BinarySearch {

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the length of the array: ");

int n = in.nextInt();

int[] arr = new int[n];

System.out.println("Enter the array elements in sorted order: ");

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

arr[i] = in.nextInt();

System.out.print("Enter the element to search: ");

int x = in.nextInt();

int low = 0, high = n - 1, mid;

while (low <= high) {

mid = (low + high) / 2;

if (arr[mid] == x) {

System.out.println("Element found at index " + mid);

return;

} else {

high = (arr[mid] > x) ? mid - 1 : high;

low = (arr[mid] < x) ? mid + 1 : low;

System.out.println("Element not found in the array.");

}
Output

Variable description
Write a program in java to accept
a sentence and check whether it is
a valid sentence or not. A valid
sentence is a sentence that starts
with a capital letter, has more
than one word in it, and ends with
either a full stop or a question
mark, or an exclamation mark.
Example :- I am going to school.
Algorithm:-
1. Start
2. Import the java.util package.
3. Define a class and a main method within the class.
4. Declare a Scanner object to read input from the user.
5. Prompt the user to enter a sentence.
6. Read the input sentence using the Scanner object.
7. Initialize a boolean variable to true.
8. Split the sentence into words using the String.split()
method.
9. Check if the first word in the sentence starts with a
capital letter.
10. Check if the sentence has more than one word.
11. Check if the sentence ends with a full stop, question
mark, or exclamation mark.
12. If any of the above conditions fail, set the boolean
variable to false.
13. Print whether the sentence is valid or not based on the
value of the boolean variable.
14. Stop
Code:-

import java.util.*;

class Main {

static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter a sentence: ");

String sentence = in.nextLine();

char firstChar = sentence.charAt(0), lastChar =


sentence.charAt(sentence.length() - 1);

int wordCount = 1;

for (int i = 0; i < sentence.length() - 1; i++) {

if (sentence.charAt(i) == ' ' && sentence.charAt(i + 1) !


= ' ') {

wordCount++;

if (Character.isUpperCase(firstChar) && (lastChar == '.' ||


lastChar == '?' || lastChar == '!') && wordCount > 1) {

System.out.println("Valid sentence");

} else {

System.out.println("Invalid sentence");

}
Output

Variable description
Write a program in java to accept
two Single dimensional arrays of
the length given by the user,
merge both the arrays and display
them.
Example:-
Input array 1:- 1, 2, 3.
Input array 2:- 4, 5, 6, 7.
Output array:- 1, 2, 3, 4, 5, 6, 7
Algorithm:-

1. Start
2. Create a Scanner object to accept user input
3. Accept the length of the first array from the user and
store it in a variable n1
4. Create an array arr1 of size n1 to store elements of the
first array
5. Accept the elements of the first array from the user and
store them in arr1
6. Accept the length of the second array from the user and
store it in a variable n2
7. Create an array arr2 of size n2 to store elements of the
second array
8. Accept the elements of the second array from the user and
store them in arr2
9. Create an array mergedArr of size n1+n2 to store the
merged array
10. Initialize variables i=0, j=0, k=0 to keep track of the
indices of arr1, arr2, and mergedArr respectively
11. Repeat the following steps while i<n1 and j<n2:
a. If arr1[i] is less than or equal to arr2[j], then store
arr1[i] in mergedArr[k] and increment i by 1
b. Else, store arr2[j] in mergedArr[k] and increment j by 1
c. Increment k by 1
12. Repeat the following steps while i<n1:
a. Store arr1[i] in mergedArr[k]
13. Stop
Code :-

import java.util.*;

class Main {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Enter the length of first array: ");

int n1 = in.nextInt();

int[] arr1 = new int[n1];

System.out.print("Enter the elements of first array: ");

for(int i=0; i<n1; i++)

arr1[i] = in.nextInt();

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

int n2 = in.nextInt();

int[] arr2 = new int[n2];

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

for(int i=0; i<n2; i++)

arr2[i] = in.nextInt();

int[] mergedArr = new int[n1 + n2];

int i=0, j=0, k=0;

while(i < n1 && j < n2){

if(arr1[i] <= arr2[j]){

mergedArr[k] = arr1[i];

i++;

}else{

mergedArr[k] = arr2[j];

j++;

k++;

}
while(i < n1){

mergedArr[k] = arr1[i];

i++; k++;

while(j < n2){

mergedArr[k] = arr2[j];

j++; k++;

System.out.print("Merged array: ");

for(i = 0; i< mergedArr.length; i++)

System.out.print(mergedArr[i] + " ");

}
Output

Variable description
Write a program to accept 20
numbers in a single dimensional
array and display the sum of all
the even numbers and that of all
odd numbers in that array
Example :-
Input :- 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20.
Output :-
Sum of Odd numbers :- 100
Sum of Even numbers :- 110.
Algorithm:-
1. Start
2. Import the "java.util" package.
3. Define a public class "sum".
4. Define the main method of the class "sum".
5. Create an object of Scanner class to take user input.
6. Declare an integer array "a" of size 20.
7. Declare two integer variables "odd" and "even" and
initialize both of them to 0.
8. Prompt the user to enter 20 integer inputs.
9. Use a for loop to iterate through the array and accept
each input from the user.
10. Check if the current element of the array is even or odd
using the modulus operator.
11. If the element is even, add it to the variable "even".
12. If the element is odd, add it to the variable "odd".
13. After iterating through the entire array, print the sum
of even numbers using the "even" variable.
14. After iterating through the entire array, print the sum
of odd numbers using the "odd" variable.
15. Close the Scanner object.
16. End the main method.
17. End the class "sum".
18. Compile the program.
19. Run the program.
20. Enter 20 integer inputs.
21. The program will output the sum of even and odd numbers
respectively.
22. End
Code:-

import java.util.*;

public class sum {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int a[] = new int[20];

int i, odd = 0, even = 0;

System.out.println("Enter the inputs");

for (i = 0; i < 20; i++) {

a[i] = sc.nextInt();

if (a[i] % 2 == 0)

even += a[i];

else

odd += a[i];

System.out.println("Sum of even numbers: " + even);

System.out.println("Sum of odd numbers: " + odd);

}
Output

Variable description
Write a program to delete an
element from an array given as
input by the user of the desired
length.
Example :-
Input :- 1, 2, 3, 4, 5, 6, 7, 8, 9
Enter the position to be deleted:-
5.
Output :- 1, 2, 3, 4, 5, 7, 8, 9
Algorithm:-
1. Start
2. Start the program.
3. Create an object of Scanner class to read input from the
user.
4. Display a message asking the user to enter the number of
elements in the array.
5. Read the value entered by the user and store it in an
integer variable n.
6. Create an integer array arr of size n.
7. Display a message asking the user to enter n elements of
the array.
8. Use a for loop to read n elements and store them in the
array arr.
9. Display a message asking the user to enter the position
of the element to be deleted.
10. Read the position entered by the user and store it in an
integer variable pos.
11. Use a for loop to iterate over the array from position
pos+1 to n-1.
12. For each element at position i, copy the value of the
next element (i+1) to the current position i.
13. Decrement the value of n by 1.
14. Display a message informing the user that the element
has been deleted.
15. Use a for loop to display the updated elements of the
array.
16. End the program.
17. Stop
Code:-

import java.util.*;

class deletion {

static void main() {

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of array elements");

int n = in.nextInt();

int arr[] = new int[n];

System.out.println("Enter the inputs");

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

arr[i] = in.nextInt();

System.out.println("Enter the position to be deleted");

int pos = in.nextInt();

for (int i = pos + 1; i < n; i++) {

arr[i - 1] = arr[i];

n--;

System.out.println("Array elements after deletion");

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

System.out.println(arr[i]);

}
Output

Variable description
A double dimensional array is
defined as N[4][4] to store
numbers. Write a program to find
the sum of all even numbers and
product of all odd numbers of the
elements stored in Double
Dimensional Array (DDA).
Example :-
Input :- 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16.
Output:-
Sum of even numbers :- 72
Sum of odd numbers :- 64
Algorithm:-

1. Import the required java.util package.


2. Create a class called DDAEvenOdd.
3. Inside the DDAEvenOdd class, create a static main() method.
4. Create a 2D integer array N of size 4x4.
5. Declare two long variables evenSum and oddSum and initialize
both to zero.
6. Display a message prompting the user to enter the elements of
the 4x4 DDA.
7. Use nested for loops to iterate through the rows and columns of
the array.
8. Inside the inner loop, take input from the user for each element
and add it to the appropriate sum variable based on whether it
is even or odd.
9. After the loops finish executing, print out the sum of all even
numbers and the product of all odd numbers.
10. End the main() method and the DDAEvenOdd class.
11. Compile the program.
12. Execute the program.
13. Enter the elements of the 4x4 DDA when prompted.
14. After all elements are entered, the program will display the sum
of all even numbers and the sum of all odd numbers.
15. End the program.
Code:-

import java.util.*;

class DDAEvenOdd {

static void main() {

Scanner in = new Scanner(System.in);

int N[][] = new int[4][4];

long evenSum = 0, oddProd = 1;

System.out.println("Enter the elements of 4x4 DDA: ");

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

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

N[i][j] = in.nextInt();

if (N[i][j] % 2 == 0)

evenSum += N[i][j];

else

oddProd *= N[i][j];

System.out.println("Sum of all even numbers = " + evenSum);

System.out.println("Product of all odd numbers = " + oddProd);

}
Output

Variable description
Write a program to enter inputs in
a double dimensional array and
display the following
i. Sum of the elements of the left
diagonal
ii. Sum of the elements of the
right diagonal and above it
Example :-
Input :- 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16.
Output:-
Sum of the left diagonal :- 34
Sum of elements in right diagonal
and above:- 34
Algorithm:-
1. Start
2. Import the java.util package
3. Create a class named "diagonal".
4. Inside the class, create a static main method.
5. Inside the main method, create a new Scanner object
named "in" to read user input.
6. Create a new 4x4 integer array named "a" to store the
user input.
7. Initialize two integer variables "ld" and "rd" to 0 to
store the sum of the left diagonal and the right
diagonal, respectively.
8. Print the message "Enter the inputs".
9. Use a nested for loop to fill the array "a" with the
user input, i.e., read 16 integers from the user and
store them in the array.
10. Print the message "The elements in the original matrix".
11. Use a nested for loop to print out the elements of the
array "a".
12. Use a for loop to calculate the sum of the left diagonal
elements of the array "a". For each element, add the
element with the same row and column index to the
variable "ld".
13. Print the message "Sum of the elements of the left
diagonal = " followed by the value of "ld".
14. Use another for loop to calculate the sum of the right
diagonal and above it elements of the array "a". For
each element, add the element with the same row index
and the column index of the opposite end (4 - i - 1) to
the variable "rd".
15. Print the message "Sum of the elements of the right
diagonal and above it = " followed by the value of "rd".
16. Stop
Code:-

import java.util.*;

class diagonal {

static void main() {

Scanner in = new Scanner(System.in);

int a[][] = new int[4][4];

int ld = 0, rd = 0;

System.out.println("Enter the inputs");

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

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

a[i][j] = in.nextInt();

System.out.println("The elements in the original matrix");

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

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

System.out.print(a[i][j] + "\t");

System.out.println();

for (int i = 0; i < 4; i++)

ld = ld + a[i][i];

System.out.println("Sum of the elements of the left diagonal = " + ld);

for (int i = 0; i < 4; i++)

rd = rd + a[i][4 - i - 1];

System.out.println("Sum of the elements of the right diagonal and above it =


" + rd);

}
Output

Variable description
Write a program in Java to create
a matrix of size 3*3 and display
its transpose. Transpose of a
matrix is obtained when we change
the row elements into column and
column elements into rows.
Example :-
Input :- 1 3 4
2 4 3
3 4 5
Output:- 1 2 3
3 4 4
4 3 5
Algorithm:-
1. Import the required package 'java.util'.
2. Define a public class 'Transpose'.
3. Define the 'main' method inside the 'Transpose' class
with the 'static' keyword.
4. Create an object 'in' of the 'Scanner' class to read
inputs from the user.
5. Declare a 2D array 'a' of size 4x4 to store the matrix
elements.
6. Prompt the user to enter the matrix elements using a
nested for loop.
7. Print the original matrix using a nested for loop.
8. Create a new nested for loop to transpose the matrix.
9. Print the transposed matrix using a nested for loop.
10. Close the main method.
11. Implement the 'main' method inside the 'Transpose'
class.
12. Create a new object 'transpose' of the 'Transpose'
class.
13. Call the 'main' method using the 'transpose' object.
14. Compile and execute the program.
15. Enter the inputs for the matrix when prompted.
16. The program will print the original matrix.
17. The program will print the transposed matrix.
18. Verify that the output matches the expected result.
19. Close the program.
20. End of the algorithm.
Code:-

import java.util.*;

public class Transpose {

static void main() {

Scanner in = new Scanner(System.in);

int a[][] = new int[4][4];

System.out.println("Enter the inputs");

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

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

a[i][j] = in.nextInt();

System.out.println("Printing Matrix without transpose:");

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

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

System.out.print(a[i][j] + " ");

System.out.println();

System.out.println("Printing Matrix After Transpose:");

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

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

System.out.print(a[j][i] + " ");

System.out.println();

}
}

Output

Variable description
Write a program in Java to create
a 3*3 square matrix, store numbers
in it and check wether it’s
symmetrical matrix or not. A
symmetrical matrix is a matrix
whose element in the i’th row and
j’th column is equal to the
element in the j’th row and i’th
column.
Example :-
Input :- 1 2 3
2 4 5
3 5 6
Output :- Symmetrical matrix
Algorithm:-
1. Start
2. Import the required package java.util
3. Define a class named Symmetry
4. Define the main function
5. Create a scanner object to read the input values
6. Declare a 2D array of size 3x3
7. Initialize a variable k to 1
8. Prompt the user to enter the elements of the array
9. Use nested for loop to read the elements of the array
10. Use nested for loop to check if the matrix is symmetric
or not
11. If the matrix is symmetric, set the value of k to 0,
otherwise, set it to 1
12. Print "Symmetric matrix" if k is 0, otherwise print "Not
a symmetric matrix"
13. Stop.
Code:-

import java.util.*;

class Symmetry {

static void main() {

Scanner in = new Scanner(System.in);

int N[][] = new int[3][3];

int k = 1;

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

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

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

N[i][j] = in.nextInt();

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

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

k = (N[i][j] == N[j][i]) ? 0 : 1;

System.out.println((k == 0) ? "Symmetric matrix" : "Not a symmetric matrix");

}
Output

Variable description
Write a program to accept a number
and check whether it is a perfect
number or not using recursive
function.
A perfect number is a number which
is the sum of all of its factors.
Example :-
Input :- 6
Output :- Perfect number
Input :- 9
Output :- Not a perfect number
Algorithm:-
1. Start
2. Import the java.util package.
3. Define a public class named Perfect.
4. Declare a method named sum_of_factors that accepts two
integer arguments, i and num, and returns an integer
value.
5. The sum_of_factors function is recursive and returns the
sum of factors of the input number num.
6. In the sum_of_factors function, if i is less than num
and num is divisible by i, then add i to the sum of
factors, and recursively call the sum_of_factors
function with i+1 and num. Otherwise, just recursively
call the sum_of_factors function with i+1 and num.
7. Define another method named main that is void type.
8. Inside the main method, create a new Scanner object to
read user input from the console.
9. Prompt the user to enter a number to be checked.
10. Read the user input number using the Scanner object.
11. Call the sum_of_factors function with the arguments 1
and the user input number and assign the result to a
variable named sum.
12. Check if the input number is equal to the sum of its
factors.
13. If the input number is equal to the sum of its factors,
print "Perfect Number" to the console, otherwise print
"Not a Perfect Number".
14. Stop
Code:-

import java.util.*;

class Perfect {

int sum_of_factors(int i, int num) {

return (i < num) ? ((num % i == 0) ? i + sum_of_factors(++i, num) : 0 +


sum_of_factors(++i, num)) : 0;

void main() {

Scanner in = new Scanner(System.in);

System.out.println("Enter the number to be checked");

int num = in.nextInt();

System.out.println((num == sum_of_factors(1, num)) ? "Perfect Number" : "Not


a Perfect Number");

}
Output

Variable description
Write a program to accept a number
and check whether it is a prime
number or not using recursive
function.
A prime number is a number with
only two factors, 1 and the number
itself.
Example :-
Input :- 5
Output :- Prime number
Input :- 9
Output :- Not a prime number
Algorithm :-
1. Start
2. Start the program.
3. Declare a class named "prime".
4. Define a function named "factors" with two integer
arguments "p" and "i".
5. Inside the "factors" function, check if i is less than
or equal to p.
6. If i is less than or equal to p, then check if p is
divisible by i.
7. If p is divisible by i, then return 1 + factors(p, ++i).
8. If p is not divisible by i, then return 0 + factors(p, +
+i).
9. If i is greater than p, then return 0.
10. Define the "main" function.
11. Inside the "main" function, create a scanner object
"in".
12. Print "Enter the number to be checked".
13. Take an integer input "n" from the user using the
scanner object.
14. Call the "factors" function with arguments "n" and 1.
15. Check if the return value of the "factors" function is
equal to 2.
16. If the return value is equal to 2, then print "Prime
number".
17. If the return value is not equal to 2, then print "Not a
prime number".
18. Stop
Code:-

import java.util.*;

class prime {

int factors(int p, int i) {

return (i <= p) ? ((p % i == 0) ? 1 + factors(p, ++i) : 0 + factors(p, +


+i)) : 0;

void main() {

Scanner in = new Scanner(System.in);

System.out.println("Enter the number to be checked");

int n = in.nextInt();

System.out.println((factors(n, 1) == 2) ? "Prime number" : "Not a prime


number");

}
Output

Variable Description
Write a program to accept a number
and check whether it is a
palindrome number or not using
recursive function.
A palindrome number is a number
which stays the same even if it’s
reversed
Example :-
Input :- 1234321
Output :- Palindrome number
Input :- 1234
Output :- Not a palindrome number
Algorithm :-
1. Start
2. Define a class "palindrome"
3. Define a function "reverse" that takes two parameters,
an integer "n" and an integer "p"
4. If p is greater than 0, perform the following steps:
a. Multiply n by 10 and add the remainder of p divided
by 10
b. Divide p by 10 and pass the result as the second
parameter to the next recursive call of the "reverse"
function
c. Return the value of the recursive call of the
"reverse" function
5. If p is not greater than 0, return the value of "n"
6. Define a function "main"
7. Create a new Scanner object "in"
8. Prompt the user to enter a number to be checked
9. Read the integer input and store it in a variable "i"
10. If the result of the "reverse" function with parameters
0 and "i" is equal to "i", print "Palindrome number"
11. If the result of the "reverse" function with parameters
0 and "i" is not equal to "i", print "Not a palindrome
number"
12. Stop
Code:-

import java.util.*;

class palindrome {

int reverse(int n, int p) {

return (p > 0) ? reverse(n * 10 + p % 10, p / 10) : n;

void main() {

Scanner in = new Scanner(System.in);

System.out.println("Enter the number to be checked");

int i = in.nextInt();

System.out.println((reverse(0, i) == i) ? "Palindrome number" : "Not a


palindrome number");

}
Output

Variable Description
Write a program to accept two
numbers and display the greatest
common factor between the two
using recursive function
Greatest common divisor between
two numbers is the highest number
that can divide both the numbers.
Example :-
Input :- 90
32456
Output :- The greatest common
divisor between the given inputs
is 2
Algorithm :-
1.Start the program.
2.Define a function gcd() that accepts two integer
arguments a and b.
3. If b is 0, return a as the greatest common divisor.
4.Else, recursively call the gcd() function with arguments
b and a%b.
5.Define the main() function.
6.Create an object of the Scanner class to read input from
the user.
7.Prompt the user to enter two numbers and read them using
the Scanner object.
8.Call the gcd() function with the two numbers as
arguments.
9.Print the result as the greatest common divisor.
10. Stop
Code :-

import java.util.*;

class greatest_common_divisor {

int gcd(int a, int b) {

return (b == 0) ? a : gcd(b, a % b);

void main() {

Scanner in = new Scanner(System.in);

System.out.println("Enter the two numbers");

int p = in.nextInt();

int q = in.nextInt();

System.out.println((p > q) ? "Greatest common divisor:" + gcd(p, q) :


"Greatest common divisor:" + gcd(q, p));

}
Output

Variable Description
Write a Program in java to accept
characters in a 2D array and
display the next character
Algorithm:
1. Start the program.
2. Create a 2D array to store the alphabets.
3. Prompt the user to enter alphabets and accept them into
the 2D array.
4. Display a message to indicate that the user should enter
alphabets in a 3x3 format.
5. Use nested loops to iterate over each element of the 2D
array.
6. Within the loops, prompt the user to enter an alphabet and
store it in the corresponding position of the array.
7. Display a message to indicate that the user should enter
the next alphabet.
8. Use nested loops to iterate over each element of the 2D
array.
9. Within the loops, replace each alphabet with the next
alphabet by calling the `getNextAlphabet` helper function.
10. Implement the `getNextAlphabet` function. If the current
alphabet is 'Z', return 'A' to wrap around, otherwise, return
the next alphabet by incrementing the current alphabet by 1.
11. Display a message to indicate that the resultant array
will be shown.
12. Use nested loops to iterate over each element of the 2D
array.
13. Within the loops, display each alphabet of the resultant
array.
14. After displaying all the alphabets, go to a new line to
display the next row of the array.
15. End the program.
Code:
import java.util.*;
public class AlphabetReplace {
public static void main(String[] args) {
char[][] alphabets = new char[3][3];
Scanner scanner = new Scanner(System.in);//Scanner variable to accept
inputs
System.out.println("Enter alphabets (3x3):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
alphabets[i][j] = scanner.next().charAt(0);
}
}
System.out.println("Resultant Array:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(getNextAlphabet(alphabets[i][j]) +
"\t");//Calling the required function.
}
System.out.println();
}
}
public static char getNextAlphabet(char alphabet) {
if (alphabet == 'Z') {//Special case of finding the next alphabet
return 'A';
} else {
return (char) (alphabet + 1);//usual logic
}
}
}
Variable Description

Output Screenshot
Write a Program to merge two
sorted 1-D array.
Algorithm:-

1. Start the program.


2. Declare and initialize two arrays, array1 and array2, with
sorted integer values.
3. Get the lengths of array1 and array2 and store them in
length1 and length2 respectively.
4. Create a new array called mergedArray with a length of
length1 + length2.
5. Print "Original Arrays:".
6. Iterate over array1 and print each element followed by a
tab.
7. Iterate over array2 and print each element followed by a
tab.
8. Print "Merged and Sorted Array:".
9. Iterate over mergedArray and print each element followed
by a tab (currently, it will display all 0's as the array is
not yet merged or sorted).
10. Initialize three variables, i, j, and k, to 0.
11. Copy the elements of array1 into mergedArray starting
from index 0 using a for loop.
12. Copy the elements of array2 into mergedArray starting
from index length1 using a for loop.
13. Get the length of mergedArray and store it in the
variable n.
14. Perform bubble sort on mergedArray using nested for
loops. Outer loop runs from 0 to n-1 and inner loop runs from
0 to n-m-1.
15. Within the inner loop, compare the adjacent elements of
mergedArray and swap them if they are in the wrong order.
16. After the inner loop completes, the largest element in
the unsorted portion will be moved to its correct position at
the end of the array.
17. Repeat steps 14-16 for each iteration of the outer loop
until the array is fully sorted.
18. Print "Merged and Sorted Array:".
19. Iterate over mergedArray and print each element followed
by a tab.
20. End the program.
Code:

import java.util.*;
public class MergeSortArrays {
static void main() {
int[] array1 = {1, 3, 5, 7, 9};
int[] array2 = {2, 4, 6, 8, 10};
int length1 = array1.length;//length of the first array
int length2 = array2.length;//length of the second array
int[] mergedArray = new int[length1 + length2];//adding the lengths
System.out.println("Original Arrays:");
for(int i = 0; i<length1; i++)
System.out.print(array1[i] + "\t");
for(int i = 0; i<length2; i++)
System.out.print(array2[i] + "\t");
int i = 0, j = 0, k = 0;
for(i = 0; i<length1; i++)
mergedArray[i] = array1[i];//Adding the first element
for(i = 0; i<length2; i++)
mergedArray[length1+i] = array2[i];//adding the second element
int n = mergedArray.length;
for (int m = 0; m < n - 1; m++)
for (int p = 0; p < n - m - 1; p++)
if (mergedArray[p] > mergedArray[p + 1]) {
// Swap elements
int temp = mergedArray[p];
mergedArray[p] = mergedArray[p + 1];
mergedArray[p + 1] = temp;
}
System.out.println("Merged and Sorted Array: ");
for(i = 0; i<mergedArray.length; i++)
System.out.print(mergedArray[i] + "\t");
}
}
Variable Description

Output Screenshot
Write a recursive program in java
to check whether a number is odd
or even
Algorithm:
1. Start the program.
2. Accept a number from the user.
3. Check if the number is even or odd using indirect
recursion.
4. If the number is zero, return true for even and false for
odd.
5. If the number is not zero, call the isOdd method with the
number decremented by 1 if checking for even, or call the
isEven method with the number decremented by 1 if checking
for odd.
6. In the isOdd method, check if the number is zero and
return false.
7. If the number is not zero, call the isEven method with the
number decremented by 1.
8. In the isEven method, check if the number is zero and
return true.
9. If the number is not zero, call the isOdd method with the
number decremented by 1.
10. Display the result indicating whether the number is even
or odd.
11. End the program.
Code:
import java.util.*;
public class EvenOddRecursion {
static void main() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
System.out.println(number + " is " + (isEven(number) ?
"even." : "odd."));
}
static boolean isEven(int number) {
return number == 0 ? true : isOdd(number - 1);//Recursion for
even number
}
static boolean isOdd(int number) {
return number == 0 ? false : isEven(number - 1);//Recursion
for odd number
}
}
Variable Description

Output Screenshot
Write a program to sort the words
in a sentence lexicographically
Algorithm for the program:

1. Start the program.


2. Initialize a string variable `sentence` with the input sentence.
3. Count the number of words in the `sentence` by initializing an
integer variable `count` to 1.
4. Iterate through each character in the `sentence` using a loop.
5. Inside the loop, check if the current character is a space.
6. If a space is found, increment the `count` variable by 1.
7. Create a string array `words` with a size equal to the value of
`count`.
8. Initialize an integer variable `startIndex` to 0 to keep track of
the start index of each word.
9. Initialize an integer variable `endIndex` to store the end index
of each word.
10. Initialize an integer variable `index` to 0 to keep track of the
index of each word in the `words` array.
11. Iterate through each character in the `sentence` using a loop.
12. Inside the loop, check if the current character is a space.
13. If a space is found, assign the current word to the `words` array
by using the `substring` method with `startIndex` and `endIndex`.
14. Update the `startIndex` to the next character position after the
space.
15. Increment the `index` by 1.
16. After the loop, assign the last word to the `words` array by
using the `substring` method with `startIndex`.
17. Use the bubble sort algorithm to sort the `words` array in
ascending order.
18. Start an outer loop to iterate through each word in the `words`
array.
19. Inside the outer loop, start an inner loop to compare each word
with the adjacent word.
20. Inside the inner loop, check if the current word is
lexicographically greater than the adjacent word using the
`compareToIgnoreCase` method.
21. If true, swap the positions of the two words in the `words`
array.
22. After the inner loop completes, increment the outer loop by 1.
23. Repeat steps 18 to 22 until all the words are sorted in ascending
order.
24. Print the sorted words using a loop.
25. End the program.
Source Code:

public class WordSorter {


public static void main(String[] args) {
String sentence = "This is a sample sentence"; int count = 1;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ') {
count++;
}
}
String[] words = new String[count];
int startIndex = 0, endIndex, index = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ') {
endIndex = i;
words[index] = sentence.substring(startIndex,
endIndex);//extracting words
startIndex = endIndex + 1;//updating the ‘startIndex’
variable
index++;
}
}
words[index] = sentence.substring(startIndex);//Adding the
final word.
for (int i = 0; i < words.length - 1; i++) {
for (int j = 0; j < words.length - i - 1; j++) {
if (words[j].compareToIgnoreCase(words[j + 1]) > 0) {
// Swap words[j] and words[j+1]
String temp = words[j];
words[j] = words[j + 1];
words[j + 1] = temp;
}
}
}
System.out.println("Sorted words:");
for (int i = 0; i<words.length; i++) {
System.out.println(words[i] + " ");
}
}
}
Variable description

Output screenshot
Write a program to print the
frequency of each word in a
sentence.
Algorithm:

1. Start the program.


2. Initialize a variable 'count' to 1.
3. Initialize a String variable 'sentence' with the input sentence.
4. Iterate over each character in the sentence using a loop.
5. Inside the loop, check if the current character is a space (' ').
6. If it is a space, increment the 'count' variable.
7. Create a String array 'words' with the size of 'count'.
8. Initialize variables 'startIndex', 'endIndex', and 'index' to 0.
9. Iterate over each character in the sentence again.
10. Inside the loop, check if the current character is a space (' ').
11. If it is a space, assign the 'endIndex' to the current index.
12. Extract the word from the 'sentence' using the 'startIndex' and
'endIndex' positions, and store it in the 'words' array at the
'index'.
13. Update the 'startIndex' to 'endIndex + 1' and increment 'index'.
14. Extract the last word from the 'sentence' using the 'startIndex'
position, and store it in the 'words' array at the 'index'.
15. Create an integer array 'frequency' with the size of
'words.length'.
16. Reset the 'count' variable to 1.
17. Iterate over the 'words' array, excluding the last element.
18. Inside the loop, check if the current word is the same as the
next word.
19. If they are the same, increment the 'count' variable.
20. If they are different, assign the 'count' to the 'frequency'
array at the 'index', reset the 'count' to 1, and increment 'index'.
21. Assign the last 'count' value to the 'frequency' array at the
last 'index'.
22. Print "Word Frequency:".
23. Iterate over the 'words' and 'frequency' arrays simultaneously.
24. Inside the loop, print each word followed by its corresponding
frequency.
25. End the program.
Code:

import java.util.*;
public class WordFrequency {
public static void main(String[] args) {
int count = 1; String sentence = "The quick brown fox jumps
over the lazy dog";
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ') {
count++;
}
}
String[] words = new String[count]; int startIndex = 0,
endIndex, index = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ') {
endIndex = i;
words[index] = sentence.substring(startIndex,
endIndex);//extracting words
startIndex = endIndex + 1;//Updating the value
index++;
}
}
words[index] = sentence.substring(startIndex); //Adding the
last word
int[] frequency = new int[words.length]; count = 1; index =
0;
for (int i = 0; i < words.length - 1; i++) {
if (words[i].equals(words[i + 1])) {
count++;
} else {
frequency[index] = count;
count = 1;
index++;
}
}
frequency[index] = count;
System.out.println("Word Frequency:");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i] + ": " + frequency[i]);
}
}
}
Variable description

Output screenshot
Write a program in Java to enter
words in a 1D array and print
those words which are starting and
ending with vowel.
ALGORITHM
Step 1: Start.
Step 2: Take input to enter the size of the array.
Step 3: Enter the size of the array in a String array.
Step 4: Take another variable to count the words.
Step 5: Take input to enter the elements of the array using for loop.
Step 6: Print a statement stating the words which are starting and
ending with vowels.
Step 7: Construct a for loop in which the iteration starts from 0
till the size of the array.
Step 8: Initialize a String variable to store the words of the array.
Step 9: Initialize a character variable to store the first letter of
the word.
Step 10: Initialize another character variable to store the last
letter of the word.
Step 11: Construct an if statement.
Step 12: In the if statement, check whether the index of the first
and last letter of the word is equal to (-1) or not.

Step 13: If it is, then print the word.

Step 14: Outside the for loop, check if the count is equal to 0 or
not.

Step 15: If it is, print none.

Step 16: Stop.


Code:-
importjava.util.*;

public class SingleD_Array{

public static void main(){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of


the array:");

int n = sc.nextInt();

String a[]=new String[n];


int count = 0;

System.out.println("Enter words in the size of


the array:");

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

a[i]=sc.next();

System.out.println("The words which are starting and ending


with vowels are:");

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

Stringword=a[i];

charf=word.charAt(0);

char l = word.charAt(word.length()-1);

if(("aeiouAEIOU".indexOf(f)!=-1)&&
("aeiouAEIOU".indexOf(l)!=-1))

System.out.println(word);
count++;

if(count==0)

System.out.println("None");

Variable description :-
Output
Write a program in Java to enter
elements in a 2D array from the
user, swap the diagonal elements
and display it.
Algorithm:-
Step 1: Start.

Step 2: Take the size of the matrix from the user in an integer variable n.

Step 3: Initialize a 2D array of size nxn.

Step 4: Print the statement of entering the elements from the user.

Step 5: Construct the first for loop in which the iteration starts from 0,
continues till n and increases by 1.

Step 6: Construct a nested for loop in which the iteration starts from 0,
continues till n and increases by 1.

Step 7: In the nested for loop, enter the matrix elements from the user.

Step 8: End the nested and main for loop.

Step 9: Print the statement stating the square matrix and use a next line escape
sequence to create a space.

Step 10: Repeat step 5 and 6.

Step 11: In the nested for loop, print the elements using tab escape sequence.

Step 12: After exiting from the nested for loop, write an empty printing
statement to move to the next line.

Step 13: End the man for loop.

Step 14: Initialize an int variable to store the elements temporarily.

Step 15: Repeat step 5.

Step 16: Store the element at that index in the temporary int variable.

Step 17: Swap the elements of the same row and column with the element of row
having the index of the iteration and the column having the formula(n-i-1).

Step 18: Then swap that element with the temporary element.

Step 19: End the for loop.

Step 20: Print the statement stating the interchange of the diagonal of the
elements.

Step 21: Repeat step 10, 11 and 12.

Step 22: Stop.


Code:-
import java.util.*;

public class DoubleD_Array {

public static void main() {

Scanner sc = new Scanner(System.in);

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

int n = sc.nextInt();

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

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

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

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

a[i][j]=sc.nextInt();

System.out.println("\n Square Matrix");

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

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

System.out.print(a[i][j]+"\t");

System.out.println();

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

int temp = a[i][i]; a[i][i]=a[i][n-i-1]; a[i][n-i-1]= temp;

System.out.println("\nInterchange of diagonalsmatrix");

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

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

System.out.print(a[i][j]+"\t");

System.out.println();

}
Variable description:-

Output:-
A disarium number is a number in
which the sum of the digits to the
power of their respective position
is equal to the number itself.
Example: 135 = 1^1 + 3^2 + 5^3
Hence, 135 is a disarium number.
Design a class Disarium to check
if a given number is a disarium
number or not.
Algorithm :-
1. Start
2. Define a function `calculateLength(num)` to calculate the number
of digits in the given number `num`.
3.If `num` is 0, return 0. Otherwise, return
`1 + calculateLength(num / 10)` to count digits recursively.
4. Define a function `isDisarium(num, originalNum, length)` to check
if the number is a Disarium number.
5.If `num` is 0, return `originalNum == 0`.
6. Calculate the power of the last digit of `num` raised to `length`
using `Math.pow(num % 10, length)`.
7. Recursively sum this value with `isDisarium(num / 10, originalNum,
length - 1)`.
8. Define a function `checkDisarium(number)` to initiate the Disarium
number checking process.
9. Calculate the length of `number` using `calculateLength(number)`
and store it.
10. Invoke `isDisarium(number, number, length)` to get the sum of the
digits raised to their respective positions.
11. Check if the calculated sum is equal to the original number.
12. Return `true` if the sum equals the original number, indicating
it's a Disarium number; otherwise, return `false`.
13. In the `main` method follow steps 14 to 16.
14. Initialize a test number (`num`) to check for Disarium property.
15. Call `checkDisarium(num)` to determine if it's a Disarium number.
16. If the number is a Disarium number, go to step 17 otherwise go to
step 18.
17. Print `"num is a Disarium number."`and go to step 19.
18. Print `"num is not a Disarium number."`.
19. Stop.
Code:-
public class DisariumChecker {

static int calculateLength(int num) {

return (num < 10) ? 1 : 1 + calculateLength(num / 10);

static int power(int base, int exponent) {

return (exponent == 0) ? 1 : base * power(base, exponent - 1);

static boolean isDisarium(int num, int length) {

return (num == 0) ? true : (power(num % 10, length) + isDisarium(num /


10, length - 1));

static boolean checkDisarium(int number) {

int length = calculateLength(number);

return isDisarium(number, length) == number;

public static void main(String[] args) {

int num = 89; // Change this number to test different values

boolean isDisarium = checkDisarium(num);

if (isDisarium) {

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

} else {

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

}
Variable description:-

Output:-
Write a program in java to print
the factorial of a number using
recursive function.
Algorithm:-
1. Start
2. Declare a class `FactorialUsingRecursion`.
3. Define a recursive method `factorial` that takes an integer `n` as
a parameter.
4. Inside the `factorial` method, check if `n` is equal to 0 or 1.
5. If `n` is equal to 0 or 1:
6. Return 1 as the factorial of 0 and 1 is 1.
7. If `n` is not 0 or 1:
8. Use the ternary operator to return `n * factorial(n - 1)`.
9. End of the `factorial` method.
10. In the `main` method:
11. Initialize an integer variable `number` with the value for which
the factorial needs to be calculated.
12. Call the `factorial` method with the value of `number` as an
argument.
13. Store the result of the factorial computation in an integer
variable `result`.
14. Display a message indicating the number whose factorial is being
calculated.
15. Output the calculated factorial value.
16. End of the `main` method.
17. Instantiate an object of the class `FactorialUsingRecursion`.
18. Call the `main` method from this object.
19. Stop
Code:-
public class FactorialUsingRecursion {
public static int factorial(int n) {
return (n == 0 || n == 1) ? 1 : n * factorial(n - 1);
}

public static void main(String[] args) {


int number = 5; // Change this to calculate factorial
of a different number
int result = factorial(number);
System.out.println("Factorial of " + number + " is: "
+ result);
}
}
Variable description:-

Output:-
Write a program in java to
implement stack using array
Algorithm:-
1. Define a class Stack with the following instance variables: maxSize: maximum size of the
stack, stackArray: an integer array to store stack elements, top: pointer to the top of the
stack, initialized to -1.

2. Define a constructor Stack(int size) to initialize the stack:

3. Set maxSize to the given size.

4. Initialize stackArray with size maxSize.

5. Initialize top to -1.

6. Define a method isEmpty() to check if the stack is empty:

7. Return true if top is -1, indicating an empty stack; otherwise, return false.

8. Define a method isFull() to check if the stack is full:

9. Return true if top is equal to maxSize - 1, indicating a full stack; otherwise, return false.

10. Define a method push(int value) to push an element onto the stack:

11. Check if the stack is full using isFull().

12. If the stack is not full:

13. Increment top by 1.

14. Assign the value to stackArray[top].

15. Optionally, print a message indicating the successful push.

16. Define a method pop() to pop an element from the stack:

17. Check if the stack is empty using isEmpty().

18. If the stack is not empty:

19. Retrieve the element at stackArray[top].

20. Decrement top by 1.

21 Return the retrieved element.

22. Optionally, print a message indicating the popped element.

23. Define a method display() to display the elements in the stack:

24. Check if the stack is empty using isEmpty().

25. If the stack is not empty:

26. Iterate through the stackArray from top to 0:

27. Print each element.

28. Create an instance of the Stack class in the main method.

29. Perform operations like pushing elements onto the stack, displaying elements, and popping
elements from the stack.

30. Test the implementation by adding elements, displaying the stack, and popping elements as
needed.

31. Stop.
Code:-
public class Stack {

private int maxSize;

private int[] stackArray;

private int top;

public Stack(int size) {

maxSize = size;

stackArray = new int[maxSize];

top = -1;

public void push(int value) {

if (top == maxSize - 1) {

System.out.println("Stack is full. Cannot push element.");

return;

stackArray[++top] = value;

System.out.println(value + " pushed to the stack.");

public int pop() {

if (top == -1) {

System.out.println("Stack is empty. Cannot pop element.");

return -1;

int value = stackArray[top--];

System.out.println(value + " popped from the stack.");

return value;

public void display() {

if (top == -1) {

System.out.println("Stack is empty. Nothing to display.");

return;

System.out.println("Elements in the stack:");

for (int i = top; i >= 0; i--) {

System.out.println(stackArray[i]);
}

public static void main(String[] args) {

Stack stack = new Stack(5); // Creating a stack with a maximum size of 5

stack.push(5);

stack.push(10);

stack.push(15);

stack.display();

stack.pop();

stack.pop();

stack.display();

}
Variable description:-

Output:-
Write a program in java to
implement queue using array
Algorithm:-
1. Start the program.

2. Define a class Queue with instance variables: maxSize: maximum size of the queue, queueArray:
an integer array to store queue elements, front: index for the front of the queue, rear: index
for the rear of the queue, currentSize: current number of elements in the queue

3. Define a constructor Queue(int size) to initialize the queue:

4. Set maxSize to the given size.

5. Initialize queueArray with size maxSize.

6. Initialize front to 0, rear to -1, and currentSize to 0.

7. Define a method isEmpty() to check if the queue is empty:

8. Return true if currentSize is 0; otherwise, return false.

9. Define a method isFull() to check if the queue is full:

10. Return true if currentSize is equal to maxSize; otherwise, return false.

11. Define a method enqueue(int value) to add an element to the rear of the queue:

12. Check if the queue is full using isFull().

13. If the queue is not full:

14. Increment rear by 1 using modulo operation with maxSize.

15. Assign the value to queueArray[rear].

16. Increment currentSize.

17. Optionally, print a message indicating the successful enqueue.

18. Define a method dequeue() to remove an element from the front of the queue:

19. Check if the queue is empty using isEmpty().

20. If the queue is not empty:

21. Retrieve the value at queueArray[front].

22. Increment front by 1 using modulo operation with maxSize.

23. Decrement currentSize.

24. Optionally, print a message indicating the successful dequeue and return the retrieved value.

25. Define a method display() to display the elements in the queue:

26. Check if the queue is empty using isEmpty().

27. If the queue is not empty:

28. Initialize count to 0 and index to front.

29. While count is less than currentSize:

30. Print queueArray[index].

31. Update index by incrementing it with modulo operation with maxSize.

32. Increment count by 1.

33. End the program.


Code:-
public class Queue {

private int maxSize; // Maximum size of the queue

private int[] queueArray;

private int front, rear, currentSize; // Index for the front of the queue

public Queue(int size) {

maxSize = size;

queueArray = new int[maxSize];

front = 0;

rear = -1;

currentSize = 0;

public void enqueue(int value) {

if (currentSize == maxSize) {

System.out.println("Queue is full. Cannot enqueue element.");

return;

rear = (rear + 1) % maxSize;

queueArray[rear] = value;

currentSize++;

System.out.println(value + " enqueued to the queue.");

public int dequeue() {

if (currentSize == 0) {

System.out.println("Queue is empty. Cannot dequeue element.");

return -1;

int dequeued = queueArray[front];

front = (front + 1) % maxSize;

currentSize--;

System.out.println(dequeued + " dequeued from the queue.");

return dequeued;

public void display() {

if (currentSize == 0) {
System.out.println("Queue is empty. Nothing to display.");

return;

System.out.println("Elements in the queue:");

int count = 0;

int index = front;

while (count < currentSize) {

System.out.println(queueArray[index]);

index = (index + 1) % maxSize;

count++;

public static void main(String[] args) {

Queue queue = new Queue(5); // Creating a queue with a maximum size of 5

queue.enqueue(5);

queue.enqueue(10);

queue.enqueue(15);

queue.display();

queue.dequeue();

queue.dequeue();

queue.display();

}
Variable Description:-

Output:-
A superclass Product has been defined to store the details of
a product sold by a wholesaler to a retailer. Define a
subclass Sales to compute the total amount paid by the
retailer with or without fine along with service tax.
Some of the members of both classes are given below:
Class name: Product
Data members/instance variables:
name: stores the name of the product
code: integer to store the product code
amount: stores the total sale amount of the product (in
decimals)
Member functions/methods:
Product (String n, int c, double p): parameterized
constructor to assign data members: name = n, code = c and
amount = p
void show(): displays the details of the data members
Class name: Sales
Data members/instance variables:
day: stores number of days taken to pay the sale amount
tax: to store the sen ice tax (in decimals)
totamt: to store the total amount (in decimals)
Member functions/methods:
Sales(….): parameterized constructor to assign values to data
members of both the classes
void compute(): calculates the service tax @ 12.4% of the
actual sale amount
calculates the fine @ 2.5% of the actual sale amount only if
the amount paid by the retailer to the wholesaler exceeds 30
days calculates the total amount paid by the retailer as
(actual sale amount + service tax + fine)
void show (): displays the data members of the superclass and
the total amount
Assume that the superclass Product has been defined. Using
the concept of inheritance, specify the class Sales giving
the details of the constructor (…), void compute() ) and void
show(). The superclass, main function and algorithm need NOT
be written.
Algorithm:-
1. Define a class `Product`.
2. Declare instance variables: `name` (String), `code` (int),
`amount` (double).
3. Define a constructor `Product(String n, int c, double p)` to
initialize the product details.
4. Define a method `show()` to display product details.
5. Define a class `Sales` extending `Product`.
6. Declare additional instance variables: `day` (int), `tax`
(double), `totamt` (double), `fine` (double initialized to 0.0).
7. Define a constructor `Sales(String n, int c, double p, int d)` to
initialize product details and days.
8. Define a method `compute()` to calculate the total amount based on
the days since sale and tax.
9. Override the `show()` method to display the total amount to be
paid.
10. Inside `Product` class:
- Initialize instance variables in the constructor.
- Implement `show()` method to display name, code, and total sale
amount.
11. Inside `Sales` class:
- In the `compute()` method, check the number of days since sale.
- If days < 30, calculate tax as 12.4% of the amount.
- If days > 30, calculate tax as 12.4% of the amount and fine as
2.5% of the amount.
- Calculate total amount to be paid as amount + tax + fine.
- Override `show()` method to display product details and total
amount to be paid.
12. Stop.
Code:-
class Product
{
String name;
int code;
double amount;
Product(String n, int c, double p) {
name = n;
code = c;
amount = p;
}
void show() {
System.out.println("Name is :"+ name);
System.out.println("Code is :" + code);
System.out.println("Total Sale Amount:" + amount);
}
}
class Sales extends Product {
int day;
double tax;
double totamt;
double fine = 0.0;
Sales(String n, int c, double p, int d) {
super(n, c, p);
day = d;
}
void compute() {
if(day < 30){ tax = 12.4 * amount /100; totamt = amount + tax; }
if(day > 30) {
tax= 12.4 * amount /100;
fine = 2.5 * amount /100;
totamt = amount + tax + fine;
}
}
void show () {
show();
System.out.println("Total amount to be paid::"+ totamt);
}
}
Variable description:-

Output:-
Tower of Hanoi
Algorithm:-
1. Start.
2. Define a method towerOfHanoi(discs, source, auxiliary,
destination).
3. If discs equals 1, execute the following:
4. Display the move of the top disc from the source peg to the
destination peg.
5. Return from the method.
6. Recursively call towerOfHanoi with discs - 1, source, destination,
and auxiliary pegs.
7. Display the move of the current disc from the source peg to the
destination peg.
8. Recursively call towerOfHanoi with discs - 1, auxiliary, source,
destination pegs.
9. End the method.
10. In the main program, define the number of discs to be solved.
11. Call towerOfHanoi with the number of discs, the source peg ('A'),
auxiliary peg ('B'), and destination peg ('C').
12. End the program.
Code:-
public class Tower {
public static void towerOfHanoi(int discs, char source, char
auxiliary, char destination) {
if (discs == 1) {
System.out.println("Move disc 1 from " + source + " to "
+ destination);
return;
}
towerOfHanoi(discs - 1, source, destination, auxiliary);
System.out.println("Move disc " + discs + " from " + source +
" to " + destination);
towerOfHanoi(discs - 1, auxiliary, source, destination);
}

public static void main(String[] args) {


int discs = 3; // Number of discs
towerOfHanoi(discs, 'A', 'B', 'C');
}
}
Variable description:-

Output:-
Write a program to perform
selection sort in One
Dimensional array
Algorithm:-
1. Start the selection sort algorithm.
2. Define a method selectionSort(arr) that takes an array of integers
as input.
3. Get the length of the array and store it in a variable 'n'.
4. Loop from 'i' = 0 to 'n - 1':
5. Set 'minIndex' = 'i'.
6. Start an inner loop from 'j' = 'i + 1' to 'n':
7. Check if arr[j] is less than arr[minIndex]:
8. If true, update 'minIndex' to 'j'.
9. Swap the element at 'minIndex' with the element at 'i'.
10. End the outer loop.
11. Define the main method.
12. Create an array 'arrayToSort' containing unsorted integers.
13. Display "Array before sorting:" followed by the contents of
'arrayToSort'.
14. Call selectionSort(arrayToSort).
15. Display "Array after selection sort:" followed by the contents of
'arrayToSort'.
16. Define the selectionSort method:
17. Accept an array 'arr' as input.
18. Get the length of 'arr' and store it in 'n'.
19. Start an outer loop from 'i' = 0 to 'n - 1':
20. Set 'minIndex' = 'i'.
21. Start an inner loop from 'j' = 'i + 1' to 'n':
22. Check if arr[j] is less than arr[minIndex]:
23. If true, update 'minIndex' to 'j'.
24. Swap the element at 'minIndex' with the element at 'i'.
25. End the outer loop.
26. End the program.
Code:-
public class SelectionSort {

public static void selectionSort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

int minIndex = i;

// Find the index of the minimum element in the unsorted part of the array

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the found minimum element with the first element

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

public static void main(String[] args) {

int[] arrayToSort = {64, 25, 12, 22, 11};

System.out.println("Array before sorting:");

printArray(arrayToSort);

selectionSort(arrayToSort);

System.out.println("Array after selection sort:");

printArray(arrayToSort);

public static void printArray(int[] arr) {

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

System.out.print(i + " ");

System.out.println();

}
Variable description:-

Output:-
Write a program to perform
insertion sort in java
Algorithm:-
1. Start the insertion sort algorithm.

2. Define a method insertionSort(arr) that takes an array of integers as input.

3. Get the length of the array and store it in a variable 'n'.

4. Loop from 'i' = 1 to 'n - 1':

5. Set 'key' = arr[i].

6. Set 'j' = 'i - 1'.

7. Start an inner loop while 'j' is greater than or equal to 0 and arr[j] >
'key':

8. Move elements of arr[0..i-1] that are greater than 'key' to one position ahead
of their current position.

9. Decrement 'j' by 1.

10. Place 'key' at the appropriate position in the sorted part of the array.

11. End the outer loop.

12. Define the main method.

13. Create an array 'arrayToSort' containing unsorted integers.

14. Display "Array before sorting:" followed by the contents of 'arrayToSort'.

15. Call insertionSort(arrayToSort).

16. Display "Array after insertion sort:" followed by the contents of


'arrayToSort'.

17. Define the insertionSort method:

18. Accept an array 'arr' as input.

19. Get the length of 'arr' and store it in 'n'.

20. Start an outer loop from 'i' = 1 to 'n - 1':

21. Set 'key' = arr[i].

22. Set 'j' = 'i - 1'.

23. Start an inner loop while 'j' is greater than or equal to 0 and arr[j] >
'key':

24. Move elements of arr[0..i-1] that are greater than 'key' to one position
ahead of their current position.

25. Decrement 'j' by 1.

26. Place 'key' at the appropriate position in the sorted part of the array.

27. End the outer loop.

28. End the program.


Code:-

public class InsertionSort {

public static void insertionSort(int[] arr) {

int n = arr.length;

for (int i = 1; i < n; ++i) {

int key = arr[i];

int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key, to one


position ahead of their current position

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

public static void main(String[] args) {

int[] arrayToSort = {12, 11, 13, 5, 6};

System.out.println("Array before sorting:");

printArray(arrayToSort);

insertionSort(arrayToSort);

System.out.println("Array after insertion sort:");

printArray(arrayToSort);

public static void printArray(int[] arr) {

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

System.out.print(arr[i] + " ");

System.out.println();

}
Variable Description:-

Output:-

You might also like