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

Computer Project

ISC computer project on 25 Java programs.

Uploaded by

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

Computer Project

ISC computer project on 25 Java programs.

Uploaded by

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

Acknowledgement

I would like to express my greatest gratitude to all those who directly or indirectly helped

and supported me throughout the project.

Firstly, I am highly indebted to my computer teacher Mr. Siddharth Mishra sir for his

guidance and constant supervision as well as for providing necessary information

regarding the project.

I also acknowledge the endless contribution of my parents and friends who always

encouraged me and support me and their wistful cooperation in my studies and to complete

this project within the limited time frame.


INDEX

S.No. Topic Remark


1. Magic Number (using Recursion).
2. Calculate HCF (using Recursion).
3. Armstrong Number (using Recursion).
4. Decimal to Binary conversion (using Recursion).
5. Fibonacci Series (using Recursion).
6. Factorial of a number (using Recursion).
7. Arrange elements of each row of a 2D array in ascending order using
Bubble Sort technique.
8. Check if a 2D array is Symmetric or not.
9. Product of 2 matrix.
10. Arrange elements of each row of a 2D array in ascending order using
Bubble Sort technique.
11. To print the initials of a name except the last word i.e. surname.
12. From the given two words generate a new word in which the first word
is followed by the first character of the second word and so on.
13. Check if a string is Palindrome or not (using Recursion).
14. Delete multiple characters from a sentence.
15. Replace vowels with the letter succeeding it.
16. To calculate telephone bill using the concept of inheritance.
17. To find the radius and area of a circle using the concept of
inheritance.
18. Single inheritance.
19. To calculate the area of a rectangles and compare the areas of 2
rectangles using the concept of object passing.
20. Display the calendar of a month by accepting the first day of a month.
21. To insert element at rear end in a linked list.
22. To delete element at rear end in a linked list.
23. To display upper triangular of a square matrix.
24. Sort 2 arrays using Insertion Sort.
25. Amicable numbers.
26. Bibliography.
PROGRAM: 1
QUESTION:

Write a Java program to check if a number is a Magic number using recursion.

A Magic number is a number where the sum of the digits is recursively calculated until a
single digit is obtained, and if the single digit is 1, the number is considered a Magic number.

CODE:

import java.util.Scanner;

public class MagicNumber

// Function to calculate the sum of digits of a number

public static int sumOfDigits(int num)

if (num == 0)

return 0;

return (num % 10) + sumOfDigits(num / 10); // Recursive call

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

public static boolean isMagicNumber(int num)

// If the number is reduced to a single digit

if (num < 10)

return (num == 1); // Check if the single digit is 1

// Recursive call to check the sum of digits

int sum = sumOfDigits(num);

return isMagicNumber(sum); // Recursive call to check if the sum is magic

public static void main(String[] args)


{

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = sc.nextInt();

// Check if the number is a Magic number

if (isMagicNumber(number))

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

else

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

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Start.

Step 2: Take an integer input from the user.

Step 3: Define a recursive function sumOfDigits(num) that:

 If the number is 0, return 0 (base case).


 Else, return the last digit (num % 10) plus the sum of digits of the remaining
number (num / 10).

Step 4: Define a recursive function isMagicNumber(num) that:

 If the number is less than 10, check if it is 1. If yes, return true; otherwise, return
false.
 Else, find the sum of the digits using the sumOfDigits() function.
 Recursively check if the sum is a Magic number by calling isMagicNumber(sum).

Step 5: In the main method, get the input from the user.

Step 6: Call the isMagicNumber() function with the input number.

Step 7: Print whether the number is a Magic number or not based on the result.

Step 8: End.

Variable Description Chart (VDC):

Variable Name Data Type Description


int int Input number provided by the user.
sum int Stores the sum of digits during recursion.
number int Input number to check if it is Magic number.
sc Scanner Scanner object for input handling.
PROGRAM: 2
QUESTION:

Write a Java program to find the HCF (Highest Common Factor) of two numbers using
recursion.

CODE:

import java.util.Scanner;

public class HCFRecursion

// Recursive function to calculate HCF

public static int findHCF(int a, int b)

if (b == 0)

return a;

return findHCF(b, a % b); // Recursive call with updated values

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input two numbers from the user

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

int num1 = sc.nextInt();


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

int num2 = sc.nextInt();

// Call the recursive function to find HCF

int hcf = findHCF(num1, num2);

// Display the HCF

System.out.println("The HCF of " + num1 + " and " + num2 + " is: " + hcf);

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Start.

Step 2: Input two numbers, say a and b.

Step 3: Define a recursive function findHCF(a, b):

 If b == 0, return a (Base case).


 Else, return findHCF(b, a % b) (Recursive case).

Step 4: Call the function findHCF with the two numbers.

Step 5: The function returns the HCF of the two numbers.

Step 6: Print the HCF.

Step 7: End.

Variable Description Chart (VDC):

Variable Name Data Type Description


a int First number input by the user.
b int Second number input by the user.
num1 int Stores the first number entered by the user.
num2 int Stores the second number entered by the user.
hcf int Stores the calculated HCF of num1 and num2.
PROGRAM: 3
QUESTION:

Write a program in Java to check if a given number is an Armstrong number using recursion .

CODE:

import java.util.Scanner;

public class ArmstrongNumber

// Function to calculate the number of digits

public static int countDigits(int num)

if (num == 0)

return 0;

return 1 + countDigits(num / 10);

// Recursive function to check Armstrong number

public static int armstrongSum(int num, int digits)

if (num == 0)

return 0;

int digit = num % 10;

return (int) Math.pow(digit, digits) + armstrongSum(num / 10, digits);

// Main function to check if the number is Armstrong

public static boolean isArmstrong(int num)

int digits = countDigits(num);


return num == armstrongSum(num, digits);

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = sc.nextInt();

if (isArmstrong(num))

System.out.println(num + " is an Armstrong number.");

else

System.out.println(num + " is not an Armstrong number.");

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Start

Step 2: Input the number to be checked.

Step 3: Define a function countDigits to count the number of digits in the given number:

 Base case: If the number is 0, return 0.


 Otherwise, recursively call countDigits with the number divided by 10 and return 1 +
result.

Step 4: Define a recursive function armstrongSum to calculate the sum of digits raised to
the power of the total number of digits:

 Base case: If the number is 0, return 0.


 Otherwise, calculate the last digit and recursively call armstrongSum for the
remaining number and return the sum of powers.

Step 5: In the main function, call isArmstrong to check if the number equals the result of
armstrongSum.

Step 6: If the number is equal to armstrongSum, it is an Armstrong number, otherwise it is


not.

Step 7: Display the result.

Step 8: End

Variable Description Chart (VDC):

Variable Name Data Type Description


num int The number entered by the user to check for Armstrong.
digits int The number of digits in the entered number.
digit int The current last digit of the number being processed.
sc Scanner Object to take input from the user.
PROGRAM: 4
QUESTION:

Write a Java program to convert a decimal number to its binary equivalent using recursion.

CODE:

import java.util.Scanner;

public class DecimalToBinary

// Recursive method to convert decimal to binary

public static String decimalToBinary(int num)

if (num == 0)

return "";

return decimalToBinary(num / 2) + (num % 2);

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input from user

System.out.print("Enter a decimal number: ");

int decimal = sc.nextInt();


// Handle case when input is 0

if (decimal == 0)

System.out.println("Binary equivalent: 0");

else

// Call recursive method and display the result

System.out.println("Binary equivalent: " + decimalToBinary(decimal));

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Input: Read a decimal number from the user.

Step 2: Base Case: If the decimal number is 0, return an empty string (end of recursion).

Step 3: Recursive Step:

 Divide the decimal number by 2 (integer division).


 Recursively call the method with the quotient.
 Append the remainder (num % 2) to the result obtained from the recursive call.

Step 4: Output: The final binary equivalent is constructed by concatenating remainders in


reverse order of computation.

Variable Description Chart (VDC):

Variable Name Data Type Description


num int The decimal number to be converted to binary.
decimal int Stores the user-input decimal number.
sc Scanner To take input from the user.
PROGRAM: 5
QUESTION:

Write a Java program to generate the Fibonacci series using recursion. The program should
display the first n numbers in the Fibonacci sequence, where n is provided by the user.

CODE:

import java.util.Scanner;

public class FibonacciRecursion

// Recursive method to calculate the nth Fibonacci number

public static int fibonacci(int n)

if (n == 0)

return 0;

else if (n == 1)

return 1;

else

return fibonacci(n - 1) + fibonacci(n - 2);

public static void main(String[] args)


{

Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of terms for Fibonacci series: ");

int n = sc.nextInt();

System.out.println("Fibonacci series:");

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

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

OUTPUT:

ALGORITHM:

Step 1: Start

Step 2: Define a recursive function fibonacci(int n):

 If n == 0, return 0.
 If n == 1, return 1.
 Otherwise, return fibonacci(n-1) + fibonacci(n-2).

Step 3: In the main function:

 Accept the number of terms (n) from the user.


 Use a loop to print the first n terms of the Fibonacci sequence by calling the
fibonacci() function.

Step 4: End

Variable Description Chart (VDC):

Variable Name Data Type Description


n int Number of terms to be generated in the Fibonacci series.
i int Loop counter to print each term in the series.
PROGRAM: 6
QUESTION:

Write a Java program to find the factorial of a number using recursion.

CODE:

import java.util.Scanner;

public class FactorialRecursion

// Recursive method to calculate factorial

public static int factorial(int n)

if (n == 0 || n == 1)

return 1; // Base case

else

return n * factorial(n - 1); // Recursive call

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number to find its factorial: ");

int num = sc.nextInt();


// Call the recursive method and display the result

int result = factorial(num);

System.out.println("Factorial of " + num + " is: " + result);

sc.close();

OUTPUT:

ALGORITHM:

Step 1: Start

Step 2: Define a recursive function factorial(n):

 If n is 0 or 1, return 1 (base case).


 Else, return n * factorial(n - 1) (recursive step).

Step 3: In the main() method:

 Take user input for the number num.


 Call the factorial() method with num and store the result.
 Display the result.

Step 4: End
Variable Description Chart (VDC):

Variable Name Data Type Description


n int The number for which the factorial is to be calculated.
num int Input number provided by the user.
result int The calculated factorial of the input number.
PROGRAM: 7
QUESTION:

Write a Java program to arrange elements of each row of a 2D array in ascending order
using Bubble Sort. The program should take input for a 2D array, and for each row, it should
sort the elements in ascending order using the Bubble Sort algorithm.

CODE:

import java.util.Scanner;

public class BubbleSort2DArray

// Method to perform Bubble Sort on each row of the 2D array

public static void bubbleSortRow(int[] row)

int n = row.length;

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

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

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

// Swap elements if they are in wrong order

int temp = row[j];

row[j] = row[j + 1];

row[j + 1] = temp;

}
}

// Method to sort all rows of the 2D array

public static void sortRows(int[][] arr)

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

bubbleSortRow(arr[i]); // Sort each row

// Method to display the 2D array

public static void displayArray(int[][] arr)

for (int[] row : arr)

for (int element : row)

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

System.out.println();

public static void main(String[] args)

Scanner sc = new Scanner(System.in);


// Input the size of the 2D array

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

int rows = sc.nextInt();

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

int cols = sc.nextInt();

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

// Input elements for the 2D array

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

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

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

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

// Sort each row using Bubble Sort

sortRows(array);

// Display the sorted 2D array

System.out.println("The 2D array with rows sorted in ascending order:");

displayArray(array);

}
OUTPUT:

ALGORITHM:

Step 1: Input the size of the 2D array (rows and columns).

Step 2: Create a 2D array based on the user input.

Step 3: Input the elements of the 2D array.

Step 4: For each row:

 Apply Bubble Sort to arrange the elements in ascending order.


 Compare adjacent elements and swap if they are in the wrong order.

Step 5: After sorting all rows, display the 2D array.

Step 6: End.

Variable Description Chart (VDC):

Variable Name Data Type Description


rows int Stores the number of rows in the 2D array.
cols int Stores the number of columns in the 2D array.
arrays int[][] 2D array to store the input values.
i, j int Loop control variables for array traversal.
n int Length of the current row in the 2D array.
temp int Temporary variable for swapping elements.
PROGRAM: 8
QUESTION:

Write a program in Java to check if a given 2D array is symmetric or not. A 2D array is said
to be symmetric if it is equal to its transpose (i.e., the element at position [i][j] is the same
as the element at [j][i] for all i and j).

CODE:

import java.util.Scanner;

public class SymmetricMatrix

// Method to check if the matrix is symmetric

static boolean isSymmetric(int[][] matrix, int n)

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

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

if (matrix[i][j] != matrix[j][i])

return false; // If any element doesn't match its transpose, it's not
symmetric

return true;

public static void main(String[] args)


{

Scanner sc = new Scanner(System.in);

// Input matrix size

System.out.print("Enter the size of the square matrix: ");

int n = sc.nextInt();

// Declare the matrix

int[][] matrix = new int[n][n];

// Input matrix elements

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

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

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

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

// Check if the matrix is symmetric

if (isSymmetric(matrix, n))

System.out.println("The matrix is symmetric.");

else
{

System.out.println("The matrix is not symmetric.");

sc.close();

OUTPUT:

ALGORITHM:

Step 1: Start.

Step 2: Declare the method isSymmetric which takes the matrix and its size as parameters.

Step 3: In the method, iterate through the matrix and check if matrix[i][j] is equal to
matrix[j][i] for all i and j.

 If any pair of elements don't match, return false (matrix is not symmetric).
 If all elements match, return true (matrix is symmetric).

Step 4: In the main method, input the size n of the matrix.

Step 5: Input the matrix elements.

Step 6: Call the isSymmetric method to check if the matrix is symmetric.

Step 7: Print the result based on the return value of the method.

Step 8: End.
Variable Description Chart (VDC):

Variable Name Data Type Description


matrix int[][] 2D array to store the elements of the matrix.
n int Size of the square matrix (number of rows and columns).
i int Loop variable for iterating through rows of the matrix.
j int Loop variable for iterating through columns of the matrix.
sc Scanner Object to take user input for matrix elements.
PROGRAM: 9
QUESTION:

Write a Java program to find the product of two matrices of size m x n and n x p. The
program should take input for both matrices and display the resultant matrix. Ensure that
the number of columns in the first matrix is equal to the number of rows in the second
matrix.

CODE:

import java.util.Scanner;

public class MatrixMultiplication

// Method to multiply two matrices

public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2, int rows1, int cols1,
int cols2)

int[][] result = new int[rows1][cols2];

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

for (int j = 0; j < cols2; j++)

result[i][j] = 0;

for (int k = 0; k < cols1; k++)

result[i][j] += matrix1[i][k] * matrix2[k][j];

}
return result;

// Method to display a matrix

public static void displayMatrix(int[][] matrix, int rows, int cols)

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

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

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

System.out.println();

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input dimensions of the first matrix

System.out.print("Enter number of rows of first matrix: ");

int rows1 = sc.nextInt();

System.out.print("Enter number of columns of first matrix: ");

int cols1 = sc.nextInt();


// Input dimensions of the second matrix

System.out.print("Enter number of rows of second matrix: ");

int rows2 = sc.nextInt();

System.out.print("Enter number of columns of second matrix: ");

int cols2 = sc.nextInt();

// Check if matrix multiplication is possible

if (cols1 != rows2)

System.out.println("Matrix multiplication not possible. Number of columns of first


matrix must be equal to number of rows of second matrix.");

return;

// Input elements of the first matrix

int[][] matrix1 = new int[rows1][cols1];

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

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

for (int j = 0; j < cols1; j++)

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

// Input elements of the second matrix

int[][] matrix2 = new int[rows2][cols2];


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

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

for (int j = 0; j < cols2; j++)

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

// Multiply the matrices

int[][] result = multiplyMatrices(matrix1, matrix2, rows1, cols1, cols2);

// Display the result

System.out.println("Product of the two matrices is:");

displayMatrix(result, rows1, cols2);

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Input the dimensions of the first matrix (rows1, cols1).

Step 2: Input the dimensions of the second matrix (rows2, cols2).

Step 3: Check if matrix multiplication is possible by verifying that the number of columns of
the first matrix equals the number of rows of the second matrix.

Step 4: Input the elements of both matrices.

Step 5: Initialize a result matrix of size rows1 x cols2.

Step 6: For each element in the result matrix:

 Multiply corresponding elements of the first and second matrix, and accumulate the
sum.

Step 7: Output the resultant matrix.

Variable Description Chart (VDC):

Variable Name Data Type Description


matrix1 int[][] Stores the elements of the first matrix.
matrix2 int[][] Stores the elements of the second matrix.
result int[][] Stores the product of the two matrices.
rows1 int Number of rows in the first matrix.
cols1 int Number of columns in the first matrix.
rows2 int Number of rows in the second matrix.
cols2 int Number of columns in the second matrix.
i, j, k int Loop control variables for traversing the matrices.
PROGRAM: 10
QUESTION:

Write a Java program to arrange all the elements of each row of an n * n matrix in ascending
order using Bubble Sort. The program should sort each row individually and print the sorted
matrix.

CODE:

import java.util.Scanner;

public class RowSortMatrix

// Function to perform bubble sort on each row

public static void bubbleSortRow(int arr[])

int n = arr.length;

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

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

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

// Swap arr[j] and arr[j+1]

int temp = arr[j];

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

arr[j + 1] = temp;

}
public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input matrix size

System.out.print("Enter the size of matrix (n x n): ");

int n = sc.nextInt();

// Declare matrix

int matrix[][] = new int[n][n];

// Input matrix elements

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

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

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

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

// Sorting each row of the matrix

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

bubbleSortRow(matrix[i]);

}
// Display sorted matrix

System.out.println("Matrix with each row sorted in ascending order:");

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

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

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

System.out.println();

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Input the matrix size (n x n) from the user.

Step 2: Initialize a matrix of size n x n.

Step 3: Take input of matrix elements from the user.

Step 4: For each row of the matrix, apply the Bubble Sort algorithm:

 Loop through the row and compare each adjacent pair of elements.
 If an element is greater than the next one, swap them.
 Repeat the process for all elements in the row until the row is sorted.

Step 5: Print the sorted matrix row by row.

Step 6: End the program.

Variable Description Chart (VDC):

Variable Name Data Type Description


n int Size of the matrix (number of rows/columns).
matrix int[][] 2D array to store matrix elements.
i int Loop variable for rows of the matrix.
j int Loop variable for columns of the matrix.
temp int Temporary variable used for swapping elements in Bubble
Sort.
PROGRAM: 11
QUESTION:

Write a program to input a name and print the initials of that name except the last word
(surname), each initial must be followed by symbol dot ().
Example :
Input : Mohandas Karamchand Gandhi
Output : M. K. Gandhi

CODE:

import java.util.Scanner;

public class InitialsPrinter

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// Input full name

System.out.print("Enter full name: ");

String fullName = scanner.nextLine();

// Split the name into words

String[] words = fullName.split(" ");

// Get the surname (last word)

String surname = words[words.length - 1];

// Print initials for all but the last word

StringBuilder initials = new StringBuilder();


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

initials.append(words[i].charAt(0)).append(". ");

// Output result

System.out.println(initials.toString() + surname);

scanner.close();

OUTPUT:

ALGORITHM:

Step 1: Start.

Step 2: Import necessary classes.

Step 3: Create a scanner object to read input.

Step 4: Prompt the user to enter the full name.

Step 5: Read the full name using the scanner.

Step 6: Split the name into an array of words using space as the delimiter.
Step 7: Retrieve the last word as the surname.

Step 8: Initialize an empty StringBuilder to store initials.

Step 9: Loop through each word except the last one:

 Extract the first character and append it to the initials followed by a dot.

Step 10: Print the initials followed by the surname.

Step 11: Close the scanner.

Step 12: End.

Variable Description Chart (VDC):

Variable Name Data Type Description


sc Scanner Used to read input from the user.
fullName String Stores the complete name entered by the user.
words String[] An array that holds the individual words of the name.
surname String Stores the last word from the array (the surname).
initials StringBuilder Builds the string containing initials.
i int Loop counter used to iterate through the words.
PROGRAM: 12
QUESTION:

Write a program to input 2 words from the user. The first character of the first word is
followed by the first character of the second word and so on. If the words are of different
length, the remaining characters of the longer word are put at the end.

Example: If the first word is “JUMP” and the second word is “STROLL”, then the required
word will be “JSUTMRPOLL”

CODE:

import java.util.Scanner;

public class Mix

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// Input two words

System.out.print("Enter the first word: ");

String word1 = scanner.nextLine();

System.out.print("Enter the second word: ");

String word2 = scanner.nextLine();

// Call the mixWords method and store the result

String mixedWord = mixWords(word1, word2);

// Output the mixed word

System.out.println("The mixed word is: " + mixedWord);


// Close the scanner

scanner.close();

// Method to mix the two words

public static String mixWords(String word1, String word2)

StringBuilder mixed = new StringBuilder();

int len1 = word1.length();

int len2 = word2.length();

int minLength = Math.min(len1, len2);

// Mix characters of both words

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

mixed.append(word1.charAt(i));

mixed.append(word2.charAt(i));

// Append remaining characters from the longer word

if (len1 > len2)

mixed.append(word1.substring(minLength));

else
{

mixed.append(word2.substring(minLength));

return mixed.toString();

OUTPUT:

ALGORITHM:

Step 1: Input the two words from the user.

Step 2: Determine the lengths of both words.

Step 3: Initialize an empty StringBuilder to store the mixed word.

Step 4: Iterate through the characters of both words up to the length of the shorter word:

 Append the character from the first word.


 Append the character from the second word.

Step 5: Append the remaining characters of the longer word, if any.

Step 6: Display the mixed word.


Variable Description Chart (VDC):

Variable Name Data Type Description


scanner Scanner Used to take input from the user.
word1 String Stores the first input word provided by the user.
word2 String Stores the second input word provided by the user.
mixed StringBuilder Holds the final mixed word created from both input words.
len1 int Length of the first word.
len2 int Length of the second word.
minLength int The minimum length between the two input words.
i int Loop counter for iterating through the characters of words.
PROGRAM: 13
QUESTION:

Write a Java program to check whether a given string is a palindrome or not using recursion.

CODE:

import java.util.Scanner;

public class PalindromeChecker

// Recursive method to check if the string is a palindrome

public static boolean isPalindrome(String str, int start, int end)

// Base case: if start index crosses end index

if (start >= end)

return true;

// Check characters at start and end

if (str.charAt(start) != str.charAt(end))

return false; // Not a palindrome

// Recursive call

return isPalindrome(str, start + 1, end - 1);

public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String input = scanner.nextLine();

// Remove spaces and convert to lowercase for uniformity

String cleanedInput = input.replaceAll("\\s+", "").toLowerCase();

// Check if the cleaned input is a palindrome

boolean result = isPalindrome(cleanedInput, 0, cleanedInput.length() - 1);

if (result)

System.out.println("\"" + input + "\" is a palindrome.");

else

System.out.println("\"" + input + "\" is not a palindrome.");

scanner.close();

OUTPUT:
ALGORITHM:

Step 1: Input the string from the user.

Step 2: Clean the input string by removing spaces and converting it to lowercase.

Step 3: Define a recursive method isPalindrome that takes three parameters: the string,
the starting index, and the ending index.

 Base Case: If the starting index is greater than or equal to the ending index, return
true.
 Check Characters: Compare the characters at the starting and ending indices. If they
are not equal, return false.
 Recursive Case: Call the isPalindrome method with the next starting index and previous
ending index.

Step 4: Display the result indicating whether the original string is a palindrome.

Variable Description Chart (VDC):

Variable Name Data Type Description


input String The original string entered by the user.
cleanedInput String The cleaned version of the input string (spaces removed and
lowercase).
start int The starting index for the current substring being checked.
end int The ending index for the current substring being checked.
result boolean The final result indicating whether the string is a
palindrome or not.
PROGRAM: 14
QUESTION:

Write a Java program to delete multiple specified characters from a given sentence. The
program should take a sentence and a string of characters to be deleted, and it should
output the modified sentence.

CODE:

import java.util.Scanner;

public class DeleteCharacters

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// Input original sentence

System.out.print("Enter the sentence: ");

String sentence = scanner.nextLine();

// Input characters to be deleted

System.out.print("Enter characters to delete: ");

String charsToDelete = scanner.nextLine();

// Call the method to delete characters

String modifiedSentence = deleteCharacters(sentence, charsToDelete);

// Output the modified sentence

System.out.println("Modified sentence: " + modifiedSentence);


scanner.close();

// Method to delete specified characters from the sentence

public static String deleteCharacters(String sentence, String charsToDelete)

StringBuilder result = new StringBuilder();

// Convert the string of characters to be deleted into a character array

char[] charsArray = charsToDelete.toCharArray();

// Iterate through each character in the original sentence

for (char ch : sentence.toCharArray())

boolean toDelete = false;

// Check if the character is in the array of characters to delete

for (char delCh : charsArray)

if (ch == delCh)

toDelete = true;

break;

// If not to be deleted, append to the result


if (!toDelete)

result.append(ch);

return result.toString();

OUTPUT:

ALGORITHM:

Step 1: Input: Read the original sentence and the characters to be deleted from the user.

Step 2: Initialization: Convert the string of characters to be deleted into a character array
for easy processing.

Step 3: Processing:

 Create a StringBuilder to store the modified sentence.


 Iterate through each character of the original sentence.
 For each character, check if it is in the array of characters to be deleted.

If it is not in the array, append it to the StringBuilder.

Step 4: Output: Convert the StringBuilder to a string and print the modified sentence.
Variable Description Chart (VDC):

Variable Name Data Type Description


scanner Scanner Used to take input from the user.
sentence String Stores the original sentence entered by the user.
charsToDelete String Stores the characters that need to be deleted.
modifiedSentence String Stores the modified sentence after removing specified
characters.
result StringBuilder Used to build the modified sentence.
charsArray char[] Array of characters that need to be deleted.
ch char Current character being processed from the original
sentence.
toDelete boolean Flag indicating whether the character should be
deleted.
delCh char Character from the array of characters to delete.
PROGRAM: 15
QUESTION:

Write a Java program to replace all vowels in a given string with the letter that succeeds
them in the alphabet. The vowels are 'a', 'e', 'i', 'o', and 'u', and their successors are 'b',
'f', 'j', 'p', and 'v' respectively. The program should handle both uppercase and lowercase
vowels.

CODE:

import java.util.Scanner;

public class ReplaceVowels

// Method to replace vowels with succeeding letters

public static String replaceVowels(String input)

StringBuilder result = new StringBuilder();

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

char ch = input.charAt(i);

switch (ch)

case 'a': result.append('b'); break;

case 'e': result.append('f'); break;

case 'i': result.append('j'); break;

case 'o': result.append('p'); break;

case 'u': result.append('v'); break;

case 'A': result.append('B'); break;

case 'E': result.append('F'); break;


case 'I': result.append('J'); break;

case 'O': result.append('P'); break;

case 'U': result.append('V'); break;

default: result.append(ch); break;

return result.toString();

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input string from user

System.out.print("Enter a string: ");

String input = sc.nextLine();

// Output the modified string

String modifiedString = replaceVowels(input);

System.out.println("Modified String: " + modifiedString);

sc.close();

}
OUTPUT:

ALGORITHM:

Step 1: Input: Read the input string from the user.

Step 2: Initialize: Create an empty StringBuilder to store the modified string.

Step 3: Process Each Character:

 Loop through each character of the string.


 Check if the character is a vowel (a, e, i, o, u, or their uppercase counterparts).
 Replace the vowel with its succeeding letter in the alphabet.
 Append the non-vowel characters as they are.

Step 4: Output: After processing all characters, print the modified string.

Step 5: End: Close the scanner object.

Variable Description Chart (VDC):

Variable Name Data Type Description


input String Stores the input string entered by the user.
result StringBuilder Used to build the modified string with replaced vowels.
i int Loop counter for iterating through each character.
ch char Stores the current character being processed.
modifiedString String Stores the final string after replacing vowels.
sc Scanner Used to take input from the user.
PROGRAM: 16
QUESTION:

Write a program in Java to calculate a telephone bill using the concept of inheritance. The
program should contain a base class with customer details and a derived class that calculates
the bill based on the number of calls made. Assume the following rates:

 First 100 calls: Free


 Next 200 calls: ₹1.00 per call
 Above 300 calls: ₹1.50 per call

CODE:

import java.util.Scanner;

// Base class for customer details

class Customer

String customerName;

String phoneNumber;

// Constructor for Customer class

Customer(String customerName, String phoneNumber)

this.customerName = customerName;

this.phoneNumber = phoneNumber;

// Method to display customer details

void displayCustomerDetails()

System.out.println("Customer Name: " + customerName);

System.out.println("Phone Number: " + phoneNumber);


}

// Derived class for calculating the bill

class TelephoneBill extends Customer

int numberOfCalls;

double billAmount;

// Constructor for TelephoneBill class

TelephoneBill(String customerName, String phoneNumber, int numberOfCalls)

super(customerName, phoneNumber); // Inheriting from Customer class

this.numberOfCalls = numberOfCalls;

this.billAmount = 0.0;

// Method to calculate bill based on number of calls

void calculateBill()

if (numberOfCalls <= 100)

billAmount = 0; // No charge for the first 100 calls

else if (numberOfCalls <= 300)

billAmount = (numberOfCalls - 100) * 1.0; // ₹1 per call for the next 200 calls
}

else

billAmount = (200 * 1.0) + (numberOfCalls - 300) * 1.5; // ₹1.50 for calls above 300

// Method to display the bill details

void displayBill()

displayCustomerDetails(); // Calling method from base class

System.out.println("Number of Calls: " + numberOfCalls);

System.out.println("Total Bill Amount: ₹" + billAmount);

// Main class to run the program

public class TelephoneBillMain

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input customer details and number of calls

System.out.print("Enter Customer Name: ");

String name = sc.nextLine();

System.out.print("Enter Phone Number: ");


String phone = sc.nextLine();

System.out.print("Enter Number of Calls: ");

int calls = sc.nextInt();

// Create object of TelephoneBill class and calculate bill

TelephoneBill bill = new TelephoneBill(name, phone, calls);

bill.calculateBill();

bill.displayBill();

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Start the program.

Step 2: Define a base class Customer that contains customer details (name and phone
number) and a method to display these details.

Step 3: Define a derived class TelephoneBill that inherits from Customer.

Step 4: In TelephoneBill, accept the number of calls and calculate the bill based on the rate:

 First 100 calls are free.


 The next 200 calls are charged at ₹1.00 per call.
 Calls beyond 300 are charged at ₹1.50 per call.

Step 5: Display the customer details along with the number of calls and the total bill
amount.

Step 6: In the main() method, accept input for the customer's name, phone number, and
number of calls.

Step 7: Create an object of the TelephoneBill class and call its methods to calculate and
display the bill.

Step 8: End the program.

Variable Description Chart (VDC):

Variable Name Data Type Description


customerName String Stores the name of the customer.
phoneNumber String Stores the customer's phone number.
numberOfCalls int Stores the number of calls made by the
customer.
billAmount double Stores the total calculated bill amount.
name String Stores the user input for customer name.
phone String Stores the user input for phone number.
calls int Stores the user input for number of calls.
PROGRAM: 17
QUESTION:

Write a Java program to find the radius and area of a circle using the concept of
inheritance.

CODE:

// Base class to define the basic properties of a circle

class Circle

protected double radius;

// Constructor to initialize radius

public Circle(double r)

radius = r;

// Method to display radius

public void displayRadius()

System.out.println("Radius of the circle: " + radius);

// Derived class to calculate and display the area of the circle

class CircleArea extends Circle

// Constructor to initialize the radius using the base class constructor

public CircleArea(double r)
{

super(r);

// Method to calculate and display the area of the circle

public void displayArea()

double area = Math.PI * radius * radius;

System.out.println("Area of the circle: " + area);

// Main class to test the functionality

public class Main

public static void main(String[] args)

// Create an object of CircleArea and pass radius

CircleArea circle = new CircleArea(5.5); // Example radius

circle.displayRadius(); // Display radius

circle.displayArea(); // Display area

}
OUTPUT:

ALGORITHM:

Step 1: Start

Step 2: Define a base class Circle with a protected variable radius and a method
displayRadius() to display the radius.

Step 3: Create a derived class CircleArea that extends Circle.

Step 4: In CircleArea, define a method displayArea() to calculate and display the area of
the circle using the formula:

𝑨𝒓𝒆𝒂 = 𝝅 ∗ 𝒓𝒂𝒅𝒊𝒖𝒔𝟐

Step 5: In the main() method, create an object of CircleArea class, passing the radius value
to the constructor.

Step 6: Call displayRadius() to display the radius.

Step 7: Call displayArea() to display the area.

Step 8: End

Variable Description Chart (VDC):

Variable Name Data Type Description


radius double Stores the radius of the circle.
area double Stores the calculated area of the circle.
circle CircleArea Object of the derived class CircleArea.
PROGRAM: 18
QUESTION:

Write a Java program to demonstrate single inheritance where a Person class is extended by
a Student class. The Person class should have attributes like name and age, while the
Student class should have attributes like roll number and marks. The program should display
the details of a student.

CODE:

// Class Person

class Person

String name;

int age;

// Constructor for Person

public Person(String name, int age)

this.name = name;

this.age = age;

// Method to display Person details

public void displayPerson()

System.out.println("Name: " + name);

System.out.println("Age: " + age);

// Class Student extending Person (Single Inheritance)


class Student extends Person

int rollNumber;

double marks;

// Constructor for Student

public Student(String name, int age, int rollNumber, double marks)

// Calling superclass (Person) constructor

super(name, age);

this.rollNumber = rollNumber;

this.marks = marks;

// Method to display Student details

public void displayStudent() {

// Displaying Person details

displayPerson();

// Displaying Student-specific details

System.out.println("Roll Number: " + rollNumber);

System.out.println("Marks: " + marks);

// Main class to execute the program

public class InheritanceDemo

public static void main(String[] args)


{

// Creating a Student object

Student student = new Student("Naitik", 17, 14, 92.4);

// Displaying the details of the student

student.displayStudent();

OUTPUT:

ALGORITHM:

Step 1: Define the Person class:

 Declare attributes name and age.


 Create a constructor to initialize these attributes.
 Create a method displayPerson() to display name and age.

Step 2: Define the Student class:

 Extend the Person class to inherit its attributes and methods.


 Declare additional attributes rollNumber and marks.
 Create a constructor that calls the Person constructor using super() to initialize
inherited attributes and initializes rollNumber and marks.
 Create a method displayStudent() that calls displayPerson() and prints rollNumber and
marks.

Step 3: Create the Main class:


 Create an object of the Student class by passing appropriate values for name, age,
rollNumber, and marks.
 Call the displayStudent() method to print the student's details.

Variable Description Chart (VDC):

Variable Name Data Type Description


name String Stores the name of the person/student.
age int Stores the age of the person/student.
rollNumber int Stores the roll number of the student.
marks double Stores the marks of the student.
student Student An object of the Student class.
PROGRAM: 19
QUESTION:

Write a Java program to demonstrate object passing as a parameter to a method. Create a


Rectangle class with methods to calculate the area of a rectangle and compare the areas of
two rectangles. The measurements of the rectangles should be taken from the user.

CODE:

import java.util.Scanner;

class Rectangle

int length, width;

// Constructor to initialize rectangle dimensions

Rectangle(int l, int w)

length = l;

width = w;

// Method to calculate area of the rectangle

int calculateArea()

return length * width;

// Method to compare areas of two rectangles

void compareArea(Rectangle r)

int area1 = this.calculateArea();

int area2 = r.calculateArea();


if (area1 > area2)

System.out.println("The first rectangle has a larger area.");

else if (area1 < area2)

System.out.println("The second rectangle has a larger area.");

else

System.out.println("Both rectangles have equal area.");

public class Main

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input dimensions of the first rectangle

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

int length1 = sc.nextInt();

System.out.print("Enter width of the first rectangle: ");


int width1 = sc.nextInt();

// Create first rectangle object

Rectangle rect1 = new Rectangle(length1, width1);

// Input dimensions of the second rectangle

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

int length2 = sc.nextInt();

System.out.print("Enter width of the second rectangle: ");

int width2 = sc.nextInt();

// Create second rectangle object

Rectangle rect2 = new Rectangle(length2, width2);

// Calculate and display the areas of the rectangles

System.out.println("Area of the first rectangle: " + rect1.calculateArea());

System.out.println("Area of the second rectangle: " + rect2.calculateArea());

// Compare the areas of the two rectangles

rect1.compareArea(rect2);

sc.close();

}
OUTPUT:

ALGORITHM:

Step 1: Start.

Step 2: Create a Rectangle class with attributes length and width and the following
methods:

 calculateArea(): Calculates and returns the area of the rectangle.


 compareArea(Rectangle r): Compares the area of the current rectangle with the area
of another rectangle.

Step 3: In the main method:

 Prompt the user to enter the length and width of the first rectangle.
 Create a Rectangle object rect1 with the given dimensions.
 Prompt the user to enter the length and width of the second rectangle.
 Create a Rectangle object rect2 with the given dimensions.
 Calculate and display the areas of rect1 and rect2 using the calculateArea() method.
 Compare the areas of rect1 and rect2 using the compareArea() method.

Step 4: End.
Variable Description Chart (VDC):

Variable Name Data Type Description


length int Stores the length of the rectangle.
width int Stores the width of the rectangle.
l int Parameter passed to set the length.
w int Parameter passed to set the width.
area1 int Stores the area of the first rectangle.
area2 int Stores the area of the second rectangle.
rect1 Rectangle Stores the first rectangle object.
rect2 Rectangle Stores the second rectangle object.
length1 int Stores the length of the first rectangle (input).
width1 int Stores the width of the first rectangle (input).
length2 int Stores the length of the second rectangle (input).
width2 int Stores the width of the second rectangle (input).
PROGRAM: 20
QUESTION:

Write a Java program to display the calendar of a month by accepting the first day of the
month (as an integer from 0 for Sunday to 6 for Saturday) and the total number of days in
the month. The program should print the calendar in a tabular format, where each week
starts on Sunday.

CODE:

import java.util.Scanner;

public class CalendarDisplay

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input: First day of the month (0 = Sunday, 1 = Monday, ..., 6 = Saturday)

System.out.print("Enter the first day of the month (0 for Sunday, 1 for Monday, ... 6
for Saturday): ");

int firstDay = sc.nextInt();

// Input: Number of days in the month

System.out.print("Enter the number of days in the month: ");

int daysInMonth = sc.nextInt();

// Display calendar

System.out.println("\nSun Mon Tue Wed Thu Fri Sat");


// Print leading spaces for the first day

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

System.out.print(" ");

// Print the days of the month

for (int day = 1; day <= daysInMonth; day++)

System.out.printf("%3d ", day);

// Move to the next line after Saturday (day % 7 == 0)

if ((day + firstDay) % 7 == 0)

System.out.println();

System.out.println(); // End of calendar

OUTPUT:
ALGORITHM:

Step 1: Start.

Step 2: Accept the first day of the month as an integer (0 for Sunday, 1 for Monday, ..., 6
for Saturday).

Step 3: Accept the number of days in the month.

Step 4: Print the headers for the days of the week: "Sun Mon Tue Wed Thu Fri Sat".

Step 5: Use a loop to print the necessary leading spaces based on the first day of the
month.

Step 6: Start printing the days of the month from 1 up to the number of days entered.

Step 7: After every 7th day (i.e., after Saturday), move to the next line.

Step 8: End the loop once all days of the month are printed.

Step 9: End.

Variable Description Chart (VDC):

Variable Name Data Type Description


firstDay int Stores the day of the week the month starts on (0-6).
daysInMonth int Stores the number of days in the month.
day int Counter variable used to print each day of the month.
PROGRAM: 21
QUESTION:

Write a Java program to insert elements at the rear end of a linked list.

CODE:

import java.util.Scanner;

class Node

int data;

Node next;

public Node(int data)

this.data = data;

this.next = null;

class LinkedList

Node head;

public LinkedList()

head = null;

// Method to insert an element at the rear end

public void insertAtRear(int data)

{
Node newNode = new Node(data);

if (head == null)

head = newNode;

else

Node temp = head;

while (temp.next != null)

temp = temp.next;

temp.next = newNode;

// Method to display the linked list

public void display()

if (head == null)

System.out.println("The linked list is empty.");

else

Node temp = head;


while (temp != null)

System.out.print(temp.data + " -> ");

temp = temp.next;

System.out.println("null");

public class LinkedListRearInsertion

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

LinkedList list = new LinkedList();

System.out.print("Enter the number of elements to insert: ");

int n = sc.nextInt();

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

System.out.print("Enter element " + (i + 1) + ": ");

int element = sc.nextInt();

list.insertAtRear(element);

}
System.out.println("Linked list after insertion:");

list.display();

OUTPUT:

ALGORITHM:

Step 1: Start

Step 2: Create a class Node with an integer data and a Node reference next.

Step 3: Create a class LinkedList that has a head node initialized to null.

Step 4: Define the insertAtRear method:

 Create a new node with the provided data.


 If the list is empty, set the new node as the head.
 Otherwise, traverse the list to find the last node, and set the next of the last node to
the new node.

Step 5: Define the display method to print all elements of the list.

Step 6: In the main method, prompt the user to enter the number of elements to insert.

Step 7: For each element, call the insertAtRear method to add the element to the list.

Step 8: Call the display method to print the elements of the linked list.

Step 9: End
Variable Description Chart (VDC):

Variable Name Data Type Description


data int Stores the data value of the node.
next Node Stores the reference to the next node.
head Node Stores the reference to the first node.
newNode Node Temporarily holds the newly created node.
temp Node Temporary variable used for list traversal.
n int Stores the number of elements to be inserted.
element int Stores the value of the current element.
PROGRAM: 22
QUESTION:

Write a Java program to delete an element at the rear end of a linked list. The program
should implement a linked list with basic functionalities, including deletion from the rear end.
Display the list before and after deletion.

CODE:

import java.util.Scanner;

// Node class to define each element in the linked list

class Node

int data;

Node next;

public Node(int data)

this.data = data;

this.next = null;

// LinkedList class with deletion at rear end functionality

class LinkedList

Node head;

// Constructor to initialize an empty list

public LinkedList()

head = null;
}

// Method to insert an element at the rear end of the list

public void insertAtRear(int data)

Node newNode = new Node(data);

if (head == null)

head = newNode;

else

Node temp = head;

while (temp.next != null)

temp = temp.next;

temp.next = newNode;

// Method to delete the element at the rear end of the list

public void deleteAtRear()

if (head == null)

System.out.println("List is empty. No element to delete.");


return;

if (head.next == null)

{ // Only one element

head = null;

else

Node temp = head;

while (temp.next.next != null)

temp = temp.next;

temp.next = null;

System.out.println("Element at the rear end has been deleted.");

// Method to display the elements of the list

public void display()

if (head == null)

System.out.println("List is empty.");

else
{

Node temp = head;

System.out.print("Linked List: ");

while (temp != null)

System.out.print(temp.data + " ");

temp = temp.next;

System.out.println();

// Main class to perform operations on the linked list

public class LinkedListDeletion

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

LinkedList list = new LinkedList();

// Inserting elements at the rear end of the list

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

int n = sc.nextInt();

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

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


{

int element = sc.nextInt();

list.insertAtRear(element);

// Displaying the list before deletion

System.out.println("\nBefore deletion:");

list.display();

// Deleting the element at the rear end

list.deleteAtRear();

// Displaying the list after deletion

System.out.println("\nAfter deletion:");

list.display();

sc.close();

OUTPUT:
ALGORITHM:

Step 1: Node class: Define a Node class to represent each node of the linked list, which
contains two fields: data and next.

Step 2: LinkedList class:

 Create a LinkedList class with a head pointer.


 Implement the insertAtRear() method to insert a new node at the end of the list.
 Implement the deleteAtRear() method to delete the last node:

 If the list is empty, print that the list is empty.


 If there's only one node, set head to null.
 If there are multiple nodes, traverse the list to the second last node and set its
next pointer to null.

 Implement the display() method to print the linked list.

Step 3: Main class:

 Initialize the linked list and accept the number of elements from the user.
 Insert the elements in the list.
 Display the list before and after deletion of the rear-end element.

Variable Description Chart (VDC):

Variable Name Data Type Description


data int Stores the data of a node.
next Node Pointer to the next node in the list.
head Node Points to the first node in the linked list.
temp Node Temporary pointer used to traverse the linked list.
n int Temporary pointer used to traverse the linked list.
element int Holds the value of the element to be inserted.
sc Scanner Used for taking input from the user.
PROGRAM: 23
QUESTION:

Write a Java program to display the upper triangular matrix of a given square matrix. The
upper triangular matrix contains elements above and on the main diagonal, while all elements
below the main diagonal are set to zero.

CODE:

import java.util.Scanner;

public class UpperTriangularMatrix

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input: Size of the matrix (n x n)

System.out.print("Enter the size of the matrix (n x n): ");

int n = sc.nextInt();

int[][] matrix = new int[n][n];

// Input: Elements of the matrix

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

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

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

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

// Display the original matrix

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

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

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

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

System.out.println();

// Display the upper triangular matrix

System.out.println("Upper Triangular Matrix:");

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

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

if (i > j)

System.out.print("0 ");

else

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


}

System.out.println();

sc.close();

OUTPUT:

ALGORITHM:

Step 1: Input the matrix size (n x n):

 Read the matrix dimension n from the user.

Step 2: Input the matrix elements:

 Initialize an n x n matrix.

 Use a nested loop to input each element of the matrix.

Step 3: Display the original matrix:

 Use a nested loop to print the matrix elements row-wise.

Step 4: Display the upper triangular matrix:


 Iterate through each element of the matrix.

 If the row index i is greater than the column index j, set the element to 0 (because
it's below the diagonal).

 Otherwise, print the element.

Step 5: Close the scanner:

 End the input process.

Variable Description Chart (VDC):

Variable Name Data Type Description


n int Stores the size of the square matrix.
matrix int[][] 2D array to store the matrix elements.
i int Row index for traversing the matrix.
j int Column index for traversing the matrix.
sc Scanner Object of Scanner class to take user input.
PROGRAM: 24
QUESTION:

Write a Java program to sort two arrays using the insertion sort algorithm. The program
should take two arrays as input and sort them in ascending order using the insertion sort
technique.

CODE:

import java.util.Scanner;

public class InsertionSortArrays

// Method to perform insertion sort

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;

// Shift elements of arr[0..i-1] that are greater than key

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

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

j = j - 1;

arr[j + 1] = key;

}
}

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

// Input for the first array

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

int size1 = sc.nextInt();

int[] arr1 = new int[size1];

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

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

arr1[i] = sc.nextInt();

// Input for the second array

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

int size2 = sc.nextInt();

int[] arr2 = new int[size2];

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

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

arr2[i] = sc.nextInt();

// Sort both arrays using insertion sort

insertionSort(arr1);
insertionSort(arr2);

// Output the sorted arrays

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

for (int i : arr1)

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

System.out.println("\nSorted second array:");

for (int i : arr2) {

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

OUTPUT:
ALGORITHM:

Step 1: Input the Arrays:

 Accept two arrays from the user, including their sizes and elements.

Step 2: Insertion Sort Logic:

 For each element in the array (starting from the second element):

i. Compare the element with elements before it.


ii. Shift the elements larger than the current element to the right.
iii. Insert the current element in the correct position.

Step 3: Sort the First Array:

 Apply insertion sort on the first array.

Step 4: Sort the Second Array:

 Apply insertion sort on the second array.

Step 5: Display Sorted Arrays:

 Print both sorted arrays.

Variable Description Chart (VDC):

Variable Name Data Type Description


arr1 int[] Array to store the elements of the first array.
arr2 int[] Array to store the elements of the second array.
size1 int Size of the first array.
size2 int Size of the second array.
key int Holds the current element being sorted in insertion sort.
i int Loop variable for traversing the array.
j int Loop variable for comparing elements during sorting.
PROGRAM: 25
QUESTION:

Write a Java program to check whether two given numbers are amicable numbers or not.
Amicable numbers are two numbers such that the sum of the proper divisors (excluding the
number itself) of one number is equal to the other number and vice versa.

CODE:

import java.util.Scanner;

public class AmicableNumber

// Method to calculate the sum of divisors

public static int sumOfDivisors(int num)

int sum = 0;

for (int i = 1; i <= num / 2; i++)

if (num % i == 0)

sum += i;

return sum;

// Main method to check for amicable numbers

public static void main(String[] args)

Scanner sc = new Scanner(System.in);


// Input two numbers

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

int num1 = sc.nextInt();

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

int num2 = sc.nextInt();

// Get the sum of divisors for both numbers

int sum1 = sumOfDivisors(num1);

int sum2 = sumOfDivisors(num2);

// Check if the numbers are amicable

if (sum1 == num2 && sum2 == num1)

System.out.println(num1 + " and " + num2 + " are amicable numbers.");

else

System.out.println(num1 + " and " + num2 + " are not amicable numbers.");

sc.close();

}
OUTPUT:

ALGORITHM:

Step 1: Input: Accept two numbers (num1 and num2) from the user.

Step 2: Sum of divisors:

 Define a method sumOfDivisors that calculates the sum of proper divisors of a


number.
 For a given number num, iterate from 1 to num / 2, and if the number divides num
evenly, add it to the sum.

Step 3: Check condition:

 Get the sum of divisors of num1 and store it in sum1.


 Get the sum of divisors of num2 and store it in sum2.
 If sum1 is equal to num2 and sum2 is equal to num1, print that the numbers are
amicable.
 Otherwise, print that they are not amicable.

Step 4: End: Terminate the program.

Variable Description Chart (VDC):

Variable Name Data Type Description


num1 int Stores the first number input by the user.
num2 int Stores the second number input by the user.
sum1 int Stores the sum of proper divisors of num1.
sum2 int Stores the sum of proper divisors of num2.
i int Loop variable used to find divisors of a number.
sc Scanner Object of Scanner class to take input from the user.
Bibliography

BOOKS: 1. Computer Science with Java class XII ISC – Sumita Arora .

2. Computer Science with Java class XI ISC – Sumita Arora .

WEBSITES: 1. https://openai.com/

2. https://www.knowledgeboat.com/

3. https://www.scribd.com/

4. https://simplycoding.in/

You might also like