Isc Computer Science Project
Isc Computer Science Project
import java.util.*;
class BubbleSort {
arr[i] = in.nextInt();
arr[j + 1] = temp;
System.out.println("Sorted array");
}
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 {
int decimalNumber = 0, i = 0;
while (num != 0) {
}
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 {
int n = in.nextInt();
arr[i] = in.nextInt();
int x = in.nextInt();
if (arr[mid] == x) {
return;
} else {
}
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 {
int wordCount = 1;
wordCount++;
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 {
int n1 = in.nextInt();
arr1[i] = in.nextInt();
int n2 = in.nextInt();
arr2[i] = in.nextInt();
mergedArr[k] = arr1[i];
i++;
}else{
mergedArr[k] = arr2[j];
j++;
k++;
}
while(i < n1){
mergedArr[k] = arr1[i];
i++; k++;
mergedArr[k] = arr2[j];
j++; k++;
}
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.*;
a[i] = sc.nextInt();
if (a[i] % 2 == 0)
even += a[i];
else
odd += a[i];
}
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 {
int n = in.nextInt();
arr[i] = in.nextInt();
arr[i - 1] = arr[i];
n--;
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:-
import java.util.*;
class DDAEvenOdd {
N[i][j] = in.nextInt();
if (N[i][j] % 2 == 0)
evenSum += N[i][j];
else
oddProd *= N[i][j];
}
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 {
int ld = 0, rd = 0;
a[i][j] = in.nextInt();
System.out.print(a[i][j] + "\t");
System.out.println();
ld = ld + a[i][i];
rd = rd + a[i][4 - i - 1];
}
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.*;
a[i][j] = in.nextInt();
System.out.println();
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 {
int k = 1;
N[i][j] = in.nextInt();
k = (N[i][j] == N[j][i]) ? 0 : 1;
}
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 {
void main() {
}
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 {
void main() {
int n = in.nextInt();
}
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 {
void main() {
int i = in.nextInt();
}
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 {
void main() {
int p = in.nextInt();
int q = in.nextInt();
}
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:-
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:
Output screenshot
Write a program to print the
frequency of each word in a
sentence.
Algorithm:
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 14: Outside the for loop, check if the count is equal to 0 or
not.
int n = sc.nextInt();
a[i]=sc.next();
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 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 9: Print the statement stating the square matrix and use a next line escape
sequence to create a space.
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 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 20: Print the statement stating the interchange of the diagonal of the
elements.
int n = sc.nextInt();
for(int j=0;j<n;j++){
a[i][j]=sc.nextInt();
for(int j=0;j<n;j++){
System.out.print(a[i][j]+"\t");
System.out.println();
for(int i=0;i<n;i++){
System.out.println("\nInterchange of diagonalsmatrix");
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 {
if (isDisarium) {
} else {
}
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);
}
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.
7. Return true if top is -1, indicating an empty stack; otherwise, return false.
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:
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 {
maxSize = size;
top = -1;
if (top == maxSize - 1) {
return;
stackArray[++top] = value;
if (top == -1) {
return -1;
return value;
if (top == -1) {
return;
System.out.println(stackArray[i]);
}
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
11. Define a method enqueue(int value) to add an element to the rear of the queue:
18. Define a method dequeue() to remove an element from the front of the queue:
24. Optionally, print a message indicating the successful dequeue and return the retrieved value.
private int front, rear, currentSize; // Index for the front of the queue
maxSize = size;
front = 0;
rear = -1;
currentSize = 0;
if (currentSize == maxSize) {
return;
queueArray[rear] = value;
currentSize++;
if (currentSize == 0) {
return -1;
currentSize--;
return dequeued;
if (currentSize == 0) {
System.out.println("Queue is empty. Nothing to display.");
return;
int count = 0;
System.out.println(queueArray[index]);
count++;
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);
}
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 {
int n = arr.length;
int minIndex = i;
// Find the index of the minimum element in the unsorted part of the array
minIndex = j;
arr[minIndex] = arr[i];
arr[i] = temp;
printArray(arrayToSort);
selectionSort(arrayToSort);
printArray(arrayToSort);
System.out.println();
}
Variable description:-
Output:-
Write a program to perform
insertion sort in java
Algorithm:-
1. Start the insertion sort algorithm.
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.
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.
26. Place 'key' at the appropriate position in the sorted part of the array.
int n = arr.length;
int j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
printArray(arrayToSort);
insertionSort(arrayToSort);
printArray(arrayToSort);
System.out.println();
}
Variable Description:-
Output:-