You are on page 1of 72

ISC Computer Project

Name-Arinjoy Mervyn Gomes


Class - 12 Sec - A Roll - 21
Subject - Computer
Introduction to Java Programs
Java is a popular, versatile, and widely-used programming language that is known for its
portability, object-oriented features, and strong community support. It's used in various domains
including web development, mobile app development, desktop applications, server-side
applications, and more.

Here's a brief overview of some fundamental concepts in Java programming:

Syntax and Structure:


Java has a C-like syntax. It uses curly braces {} to define blocks of code and semicolons ; to
terminate statements. The entry point for a Java program is the main method:

Variables and Data Types:


Java has various data types such as int, double, char, boolean, etc. Variables are declared
using these types:

Control Flow:
Java provides control flow statements like if, else, switch, while, for, and more. These help you
control the flow of your program based on conditions and loops:

Functions and Methods:


In Java, functions are called methods. You can define methods to break your code into smaller,
reusable parts:

Classes and Objects:


Java is an object-oriented language. You define classes to create objects that encapsulate data
and behavior. Each class has fields (variables) and methods (functions):

Inheritance and Polymorphism:


Java supports inheritance, allowing you to create new classes based on existing ones. This
promotes code reuse. Polymorphism lets you use objects of different classes interchangeably
through method overriding.

Exception Handling:
Java has a robust exception handling mechanism to deal with runtime errors and exceptions:

Packages and Libraries:


Java's standard library provides a wide range of classes and methods for various tasks. You can
also create your own packages and libraries to organize and share code.

Java's extensive ecosystem, community support, and its Write Once, Run Anywhere (WORA)
capability through the Java Virtual Machine (JVM) make it a powerful choice for a wide range of
programming tasks. Whether you're a beginner or an experienced programmer, Java offers a
solid foundation to build upon.

Java Programs
1.Binary Addtion
Question:
The provided Java program performs binary addition on two binary numbers. You need to write the
algorithm for the given program, create a variable description table for the code, and provide a sample
input along with its corresponding output.

Algorithm:
1st Initialize a Scanner object to read input from the user.
2nd
3rd Display the message "Enter first binary number:" to prompt the user for input.
4th
5thRead the first binary number entered by the user using the nextLine() method of the Scanner and store
it in the variable binary1.
6th
7thDisplay the message "Enter second binary number:" to prompt the user for input.
8th
9thRead the second binary number entered by the user using the nextLine() method of the Scanner and
store it in the variable binary2.
10th
11th Close the Scanner object to release system resources.
12th
13th Call the addBinary function with the arguments binary1 and binary2.
14th
15th Store the returned value from the addBinary function in the variable result.
16th
17th Display the message "Sum of two binary numbers: " followed by the value of the result variable.
Note:
The addBinary function is not detailed in the algorithm, as it's already provided in the code and performs
the binary addition logic.
The algorithm outlines the steps the program takes to read two binary numbers, perform binary addition,
and then display the result to the user.
1st

Java Code:
import java.util.Scanner;

public class BinaryAddition {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter first binary number:");
String binary1 = scanner.nextLine();
System.out.println("Enter second binary number:");
String binary2 = scanner.nextLine();
scanner.close();

String result = addBinary(binary1, binary2);


System.out.println("Sum of two binary numbers: " + result);
}

public static String addBinary(String a, String b) {


StringBuilder result = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;

while (i >= 0 || j >= 0) {


int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
result.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) result.append(carry);
return result.reverse().toString();
}
}
Variable Description Table:
Variable Description
scanner A Scanner object to read user input.
binary1 String to store the first binary number.
binary2 String to store the second binary number.
result StringBuilder to store the binary sum.
i, j Integer variables for indexing binary strings.
carry Integer to store carry during binary addition.

Sample Input and Output:


Input:
sqlCopy code
Enter first binary number:
1010
Enter second binary number:
1101
Output:
mathematicaCopy code
Sum of two binary numbers: 11011
2.Longest Word Finder
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for finding the longest word in a given sentence. The algorithm uses a
recursive approach to divide the array of words and compare their lengths to determine the longest word.

1st The program starts by taking user input, which is a sentence.


2nd The sentence is split into an array of words using a space as the delimiter.
3rd The findLongestWord method is called with the array of words, the left index (initially 0), and the
right index (initially words.length - 1).
4thIn the findLongestWord method, the base case is when the left index is equal to the right index. In this
case, the function returns the word at the current index.
5thIf the length of the word at the left index is greater than or equal to the length of the word at the right
index, the function recursively calls itself with the left index incremented by 1 and the same right
index.
6thIf the length of the word at the left index is less than the length of the word at the right index, the
function recursively calls itself with the same left index and the right index decremented by 1.
7thThe process continues until the base case is reached and the longest word is determined.

Java Code:
javaCopy code
import java.util.Scanner;

public class LongestWordFinder {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
scanner.close();
String[] words = sentence.split(" ");
String longestWord = findLongestWord(words, 0, words.length - 1);
System.out.println("The longest word is: " + longestWord);
}

public static String findLongestWord(String[] words, int left, int right) {


if (left == right) return words[left];
if (words[left].length() >= words[right].length()) {
return findLongestWord(words, left + 1, right);
} else {
return findLongestWord(words, left, right - 1);
}
}
}

Variable Description Table:


Variable Description
sentence The input sentence provided by the user.
words An array of words obtained by splitting the
sentence.
longestWord The variable that holds the longest word in the
sentence.
left The left index used for partitioning the array.
right The right index used for partitioning the array.

Sample Input and Output:


vbnetCopy code
Input: "The quick brown fox jumped over the lazy dog"
Output: "jumped"
In this example, the input sentence is split into words. The recursive algorithm compares the lengths of
words and identifies "jumped" as the longest word in the sentence, which is then printed as the output.
3.Lucky Numbers
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for finding and printing lucky numbers within a given range. A lucky number is
a number that remains after a specific elimination process. Here's how the algorithm works:
1st The program takes input from the user for the upper limit of the range n.
2nd The code iterates through each number from 1 to n and checks whether it is a lucky number using
the isLucky function.
3rd If a number is identified as a lucky number, it is printed.
4thThe isLucky function determines whether a given number is lucky:
 It initializes an ArrayList numbers and populates it with numbers from 1 to n.
 It sets the initial index to 1.
 While the current index is less than the size of numbers:
 The algorithm retrieves the "step" value at the current index (which is the value at
numbers.get(index)).
 If the step value is greater than the remaining numbers to process, the loop breaks.
 It initializes a count to 0.
 It loops through the remaining numbers, starting from the current index, and removes every step
- count-th number while incrementing the count.
 The index is incremented.


1st Finally, the function checks if the given number n is present in the numbers list, and if it is, the number
is considered lucky.

Java Code:
javaCopy code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LuckyNumbers {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the range (n) to find lucky numbers till n:");
int n = scanner.nextInt();
scanner.close();

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


if (isLucky(i)) {
System.out.print(i + " ");
}
}
}

public static boolean isLucky(int n) {


List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= n; i++) {
numbers.add(i);
}
int index = 1;
while (index < numbers.size()) {
int step = numbers.get(index);
if (step > numbers.size() - index) {
break;
}
int count = 0;
for (int i = index; i < numbers.size(); i += step - count) {
numbers.remove(i - count);
count++;
}
index++;
}
return numbers.contains(n);
}
}

Variable Description Table:


Variable Description
n The upper limit of the range to find lucky numbers.
numbers An ArrayList holding numbers from 1 to n during
the lucky number determination process.
index The current index used for traversal and step
determination in the numbers list.
step The value at the current index in the numbers list,
used to determine the elimination step.
count A counter used to adjust the step size when
removing numbers from the numbers list.
Sample Input and Output:
makefileCopy code
Input: 20
Output: 1 3 7 9 13 15 19
In this example, when the range is set to 20, the lucky numbers within that range are 1, 3, 7, 9, 13, 15, and
19. These numbers are printed as the output.

4.SaddlePoint
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for finding saddle points in a given matrix. A saddle point is an element in the
matrix that is both the smallest element in its row and the largest element in its column. The algorithm
works as follows:
1st The program takes input from the user for the number of rows and columns of the matrix.
2nd The program creates a 2D array (matrix) to store the elements of the matrix.
3rd The user is prompted to input the elements of the matrix row by row.
4thAfter inputting the matrix, the findSaddlePoint function is called to identify saddle points.
5thThe findSaddlePoint function iterates through each row of the matrix.
 For each row, it initializes minRow to the value of the first element in that row and colIdx to 0.
 It then iterates through the remaining elements of the row, updating minRow and colIdx if a smaller
element is found.
 After identifying the smallest element in the row, it checks if this element is also the largest
element in its column:
 It iterates through the rows at the same column index (colIdx) and checks if the current element
is greater than minRow.
 If any such element is found, the current element cannot be a saddle point, and the loop breaks.
 If no such element is found, the current element is a saddle point, and it is printed.


1st The algorithm continues this process for each row in the matrix.

Java Code:
javaCopy code
import java.util.Scanner;

public class SaddlePoint {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of rows of the matrix:");
int rows = scanner.nextInt();
System.out.println("Enter the number of columns of the matrix:");
int cols = scanner.nextInt();

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


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();

findSaddlePoint(matrix);
}

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


for (int i = 0; i < matrix.length; i++) {
int minRow = matrix[i][0];
int colIdx = 0;
for (int j = 1; j < matrix[i].length; j++) {
if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
colIdx = j;
}
}
boolean isSaddle = true;
for (int k = 0; k < matrix.length; k++) {
if (matrix[k][colIdx] > minRow) {
isSaddle = false;
break;
}
}
if (isSaddle) {
System.out.println("Saddle point found: " + minRow);
}
}
}
}

Variable Description Table:


Variable Description
rows The number of rows in the matrix.
cols The number of columns in the matrix.
matrix A 2D array containing the matrix elements.
minRow The smallest element found in the current row.
colIdx The index of the column where the smallest element
(minRow) was found in the current row.
isSaddle A boolean flag indicating whether the current element is
a saddle point (both row and column minimum).

Sample Input and Output:


yamlCopy code
Input:
Enter the number of rows of the matrix: 3
Enter the number of columns of the matrix: 3
Enter the elements of the matrix:
456
278
391

Output:
Saddle point found: 7
In this example, the input matrix has only one saddle point: the element 7 at row 2, column 2. The
program identifies this saddle point and prints it as the output.

Enter the range (n) to find lucky numbers till n:


100
Lucky numbers: 1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99

5.Date Validation
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for validating whether a given date is valid or not. It takes user input for a day,
month, and year and then checks whether the provided combination of day, month, and year is a valid
date according to the rules of the Gregorian calendar. The algorithm works as follows:
1st The program takes input from the user for the day, month, and year.
2nd The program then calls the isValidDate function to determine if the provided date is valid or not.
3rd The isValidDate function first checks if the provided month is within the range 1 to 12, and the
day is within the range 1 to 31. If not, it immediately returns false.
4thIf the month is February (month 2), the function uses the isLeapYear function to determine if the year
is a leap year:
 If it's a leap year, February can have up to 29 days.
 If it's not a leap year, February can have up to 28 days.

1st If the month is April, June, September, or November (months 4, 6, 9, 11), the function ensures that the
day is within the range 1 to 30.
2nd For all other months, the function returns true since they have up to 31 days.

Java Code:
javaCopy code
import java.util.Scanner;

public class DateValidation {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month:");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
scanner.close();

if (isValidDate(day, month, year)) {


System.out.println("The date is valid.");
} else {
System.out.println("The date is invalid.");
}
}

public static boolean isLeapYear(int year) {


return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}

public static boolean isValidDate(int day, int month, int year) {


if (month < 1 || month > 12) return false;
if (day < 1 || day > 31) return false;

if (month == 2) {
return isLeapYear(year) ? day <= 29 : day <= 28;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
return day <= 30;
}
return true;
}
}

Variable Description Table:


Variable Description
day The day input provided by the user.
month The month input provided by the user.
year The year input provided by the user.
isValid A boolean flag indicating whether the date is valid
(true) or not (false).

Sample Input and Output:


yamlCopy code
Input:
Enter day: 29
Enter month: 2
Enter year: 2020

Output:
The date is valid.
In this example, the user provides input for a date (February 29, 2020). Since 2020 is a leap year, the date
is valid, and the program prints "The date is valid." as the output.

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


int minRow = matrix[i][0];
int colIdx = 0;
for (int j = 1; j < matrix[i].length; j++) {
if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
colIdx = j;
}
}
boolean isSaddle = true;
for (int k = 0; k < matrix.length; k++) {
if (matrix[k][colIdx] > minRow) {
isSaddle = false;
break;
}
}
if (isSaddle) {
System.out.println("Saddle point found: " + minRow);
}
}
}
}

6.Recursive Word Sort

Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for recursively sorting words in a sentence using the merge sort algorithm. The
program takes a sentence as input, splits it into words, sorts the words, and then prints the sorted sentence.
The algorithm works as follows:
1st The program takes input from the user for a sentence.
2nd The sentence is split into an array of words using spaces as delimiters.
3rd The sortWords function is called to start the sorting process, passing the array of words, left index
(initially 0), and right index (initially words.length - 1).
4thIn the sortWords function, if the left index is less than the right index, it calculates the middle index
(mid) and divides the array into two halves: the left half and the right half.
5thThe function then recursively calls itself for both halves.
6thThe merge function is called to merge the two sorted halves back together.
 The merge function first calculates the sizes of the left and right halves (n1 and n2).
 It creates temporary arrays L and R to hold the elements of the left and right halves, respectively.
 It copies the elements of the left half into array L and the elements of the right half into array R.
 The function then compares the elements from L and R and merges them back into the original
words array in sorted order.

1st The sorted sentence is printed using a loop that iterates through the sorted words array.

Java Code:
javaCopy code
import java.util.Scanner;

public class RecursiveWordSort {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
scanner.close();

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


sortWords(words, 0, words.length - 1);
System.out.println("Sorted sentence:");
for (String word : words) {
System.out.print(word + " ");
}
}

public static void sortWords(String[] words, int left, int right) {


if (left < right) {
int mid = (left + right) / 2;
sortWords(words, left, mid);
sortWords(words, mid + 1, right);
merge(words, left, mid, right);
}
}

public static void merge(String[] words, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
String[] L = new String[n1];
String[] R = new String[n2];
for (int i = 0; i < n1; i++) {
L[i] = words[left + i];
}
for (int j = 0; j < n2; j++) {
R[j] = words[mid + 1 + j];
}
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i].compareTo(R[j]) <= 0) {
words[k] = L[i];
i++;
} else {
words[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
words[k] = L[i];
i++;
k++;
}
while (j < n2) {
words[k] = R[j];
j++;
k++;
}
}
}
Variable Description Table:
Variable Description
sentence The input sentence provided by the user.
words An array of words obtained by splitting the
sentence.
left The left index of the current subarray during
sorting.
right The right index of the current subarray during
sorting.
mid The middle index used to divide the array into
subarrays.
n1 The size of the left half during merging.
n2 The size of the right half during merging.
L Temporary array holding elements of the left half
during merging.
R Temporary array holding elements of the right half
during merging.
i, j Index variables for iterating through the left and
right halves during merging.
Variable Description
k Index variable for placing merged elements back
into the original words array during merging.

Sample Input and Output:


vbnetCopy code
Input: "apple banana cherry date"
Output: "apple banana cherry date"
In this example, the input sentence is split into words. The recursive merge sort algorithm sorts the words
in lexicographic order, and the sorted sentence is printed as the output.

7.HCF and LCM


Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for calculating the Highest Common Factor (HCF) and Lowest Common
Multiple (LCM) of two given numbers. The program takes user input for two numbers, calculates their
HCF using a recursive algorithm, and then calculates the LCM using the HCF value. The algorithm works
as follows:
1st The program takes input from the user for two numbers (num1 and num2).
2nd The program calls the findHCF function to calculate the HCF of the two numbers.
 The findHCF function is a recursive function that calculates the HCF using the Euclidean
algorithm. The algorithm works by repeatedly taking the remainder of the larger number divided by
the smaller number until the remainder becomes 0. At that point, the smaller number becomes the
HCF.

1st The LCM is calculated using the formula: LCM = (num1 * num2) / HCF.
2nd The calculated HCF and LCM are then printed as output.

Java Code:
javaCopy code
import java.util.Scanner;

public class HCFandLCM {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number:");
int num1 = scanner.nextInt();
System.out.println("Enter the second number:");
int num2 = scanner.nextInt();
scanner.close();

int hcf = findHCF(num1, num2);


int lcm = (num1 * num2) / hcf;

System.out.println("HCF: " + hcf);


System.out.println("LCM: " + lcm);
}

public static int findHCF(int a, int b) {


if (b == 0) {
return a;
}
return findHCF(b, a % b);
}
}

Variable Description Table:


Variable Description
num1 The first number input provided by the user.
num2 The second number input provided by the user.
hcf The calculated Highest Common Factor (HCF) of
num1 and num2.
lcm The calculated Lowest Common Multiple (LCM)
of num1 and num2.

Sample Input and Output:


yamlCopy code
Input:
Enter the first number: 12
Enter the second number: 18
Output:
HCF: 6
LCM: 36
In this example, the user provides input for two numbers (12 and 18). The HCF of these numbers is 6, and
the LCM is 36. The program calculates and prints the HCF and LCM as the output.

8.Day Of Week Finder


Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for finding the day of the week for a given date using the Zeller's Congruence
algorithm. The program takes user input for a day, month, and year, and then calculates and prints the
corresponding day of the week. The algorithm works as follows:
1st The program takes input from the user for a day, month, and year.
2nd The program then calls the findDayOfWeek function to determine the day of the week for the
provided date.
3rd In the findDayOfWeek function, if the provided month is January or February, it's adjusted for the
algorithm's requirements:
 The month value is increased by 12.
 The year value is decreased by 1.

1st The findDayOfWeek function calculates the day of the week (0 for Saturday, 1 for Sunday, ..., 6 for
Friday) using the Zeller's Congruence formula:
2nd scssCopy code
3rd f = q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) - (2 * J)
4thwhere:
 q is the day of the month.
 m is the adjusted month value.
 K is the last two digits of the year.
 J is the first two digits of the year.

1st The calculated value f is divided by 7, and the remainder gives the day of the week.
2nd The algorithm uses a switch statement to map the calculated day of the week value to its
corresponding name ("Saturday", "Sunday", ...).
3rd The determined day of the week is returned as a string.

Java Code:
javaCopy code
import java.util.Scanner;

public class DayOfWeekFinder {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month (1 for January, 12 for December):");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
scanner.close();

String dayOfWeek = findDayOfWeek(day, month, year);


System.out.println("The day of the week is: " + dayOfWeek);
}

public static String findDayOfWeek(int day, int month, int year) {


if (month < 3) {
month += 12;
year -= 1;
}
int q = day;
int m = month;
int K = year % 100;
int J = year / 100;
int f = q + ((13 * (m + 1)) / 5) + K + (K / 4) + (J / 4) - (2 * J);
int dayOfWeek = f % 7;

switch (dayOfWeek) {
case 0:
return "Saturday";
case 1:
return "Sunday";
case 2:
return "Monday";
case 3:
return "Tuesday";
case 4:
return "Wednesday";
case 5:
return "Thursday";
case 6:
return "Friday";
default:
return "Invalid";
}
}
}

Variable Description Table:


Variable Description
day The day input provided by the user.
month The month input provided by the user.
year The year input provided by the user.
q The day of the month used in the calculation.
m The month value used in the calculation.
K The last two digits of the year used in the
calculation.
J The first two digits of the year used in the
calculation.
f The intermediate value calculated using the Zeller's
Congruence formula.
dayOfWeek The calculated day of the week (0 for Saturday, 1
for Sunday, ..., 6 for Friday).

Sample Input and Output:


yamlCopy code
Input:
Enter day: 15
Enter month (1 for January, 12 for December): 8
Enter year: 2023

Output:
The day of the week is: Wednesday
In this example, the user provides input for a date (August 15, 2023). The program calculates that the day
falls on a Wednesday and prints "The day of the week is: Wednesday" as the output.
9.Date After Days
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for calculating the date after adding a certain number of days to a given date.
The program takes user input for a day, month, year, and the number of days to add. It then calculates and
prints the resulting date after adding the specified number of days. The algorithm works as follows:
1st The program takes input from the user for a day, month, year, and the number of days to add
(daysToAdd).
2nd The program calls the findDateAfterDays function to determine the resulting date after adding the
days.
3rd In the findDateAfterDays function, it creates an array daysInMonth to store the number of days in
each month of a non-leap year.
 If the year is a leap year, it updates the number of days in February to 29.

1st The findDateAfterDays function adds the daysToAdd value to the input day.
 It then enters a loop that checks if the resulting day exceeds the number of days in the current
month:
 If it does, the exceeding days are subtracted from the current month, and the month is
incremented by 1.
 If the month becomes greater than 12, the year is incremented by 1, and the month is reset to 1
(January).
 If the year is a leap year, the days in February are updated accordingly.

 This loop continues until the resulting day is within the valid range of the month.

1st The calculated day, month, and year are returned as an array of integers.

Java Code:
javaCopy code
import java.util.Scanner;

public class DateAfterDays {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month (1 for January, 12 for December):");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
System.out.println("Enter the number of days to add:");
int daysToAdd = scanner.nextInt();
scanner.close();

int[] result = findDateAfterDays(day, month, year, daysToAdd);


System.out.println("The date after adding the days is: " + result[0] + "/" + result[1] + "/" + result[2]);
}

public static int[] findDateAfterDays(int day, int month, int year, int daysToAdd) {
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) {
daysInMonth[2] = 29;
}

day += daysToAdd;
while (day > daysInMonth[month]) {
day -= daysInMonth[month];
month++;
if (month > 12) {
month = 1;
year++;
if (isLeapYear(year)) {
daysInMonth[2] = 29;
} else {
daysInMonth[2] = 28;
}
}
}
return new int[]{day, month, year};
}

public static boolean isLeapYear(int year) {


return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}
}
Variable Description Table:
Variable Description
day The day input provided by the user.
month The month input provided by the user.
year The year input provided by the user.
daysToAdd The number of days to add to the given date.
daysInMonth An array containing the number of days in each
month of a non-leap year.
result An array containing the resulting day, month, and
year after adding the specified number of days.

Sample Input and Output:


yamlCopy code
Input:
Enter day: 15
Enter month (1 for January, 12 for December): 2
Enter year: 2023
Enter the number of days to add: 20

Output:
The date after adding the days is: 7/3/2023
In this example, the user provides input for a date (February 15, 2023) and wants to add 20 days to it. The
program calculates and prints that the resulting date is March 7, 2023.

Enter day:
15
Enter month (1 for January, 12 for December):
8
Enter year:
2023
The day of the week is: Sunday
10.Armstrong Number
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for determining whether a given number is an Armstrong number or not. An
Armstrong number (also known as a narcissistic number or a pluperfect digital invariant) is a number that
is equal to the sum of its own digits raised to the power of the number of digits. The program takes user
input for a number, checks whether it is an Armstrong number, and then prints the result. The algorithm
works as follows:
1st The program takes input from the user for a number (num).
2nd The program calls the isArmstrong function to determine whether the given number is an
Armstrong number.
3rd In the isArmstrong function:
 The original number (originalNum) is stored in a separate variable.
 The length of the number (i.e., the number of digits) is calculated and stored in n.
 The algorithm uses a loop to extract each digit of the number one by one:
 The last digit (digit) is obtained by taking the remainder of the number when divided by 10.
 The digit is raised to the power of n and added to the sum.
 The last digit is removed from the number by dividing it by 10.

 After the loop, if the sum is equal to the originalNum, the number is an Armstrong number.

1st The function returns true if the number is an Armstrong number and false otherwise.

Java Code:
javaCopy code
import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
scanner.close();

if (isArmstrong(num)) {
System.out.println(num + " is an Armstrong number.");
} else {
System.out.println(num + " is not an Armstrong number.");
}
}

public static boolean isArmstrong(int num) {


int originalNum = num;
int sum = 0;
int n = String.valueOf(num).length();

while (num > 0) {


int digit = num % 10;
sum += Math.pow(digit, n);
num /= 10;
}

return sum == originalNum;


}
}

Variable Description Table:


Variable Description
num The number input provided by the user.
originalNum The original number before processing.
sum The sum of the digits raised to the power of n.
n The number of digits in the input number.
digit The last digit of the number extracted during the
loop iteration.

Sample Input and Output:


vbnetCopy code
Input:
Enter a number: 153

Output:
153 is an Armstrong number.
In this example, the user provides input for the number 153. The program calculates that 153 is an
Armstrong number because 1^3 + 5^3 + 3^3 = 153, and it prints "153 is an Armstrong number" as the
output.

11.Boundary Sort
Question:
Explain the algorithm used in the provided Java code. Provide a variable description table and a sample
input/output example.

Algorithm:
The provided Java code is for sorting the boundary elements of a given matrix in a clockwise manner.
The boundary elements are those elements that are on the outermost edges of the matrix. The program
takes user input for the number of rows and columns of the matrix, as well as the matrix elements. It then
sorts the boundary elements and places them back in the matrix, and finally, it prints the matrix with the
sorted boundary elements. The algorithm works as follows:
1st The program takes input from the user for the number of rows (rows) and number of columns (cols) of
the matrix.
2nd The program then initializes a 2D array matrix to store the matrix elements.
3rd The program takes input from the user for the elements of the matrix using nested loops.
4thThe program calls the sortBoundary function to sort the boundary elements of the matrix.
5thIn the sortBoundary function:
 The number of rows and columns are stored in rows and cols respectively.
 The total number of boundary elements (n) is calculated as twice the sum of rows and columns
minus 4 (to account for the corners).
 An array boundary is created to store the boundary elements, and an index idx is initialized to keep
track of the boundary element being added.
 The boundary elements are extracted in a clockwise manner:
 The top row is traversed from left to right.
 The right column (excluding the top element) is traversed from top to bottom.
 The bottom row (excluding the right and bottom corners) is traversed from right to left.
 The left column (excluding the bottom and left corners) is traversed from bottom to top.

 The boundary array is then sorted in ascending order.
 The sorted boundary elements are placed back into the matrix in the same clockwise order:
 The top row is filled with elements from the boundary array.
 The right column is filled with elements from the boundary array.
 The bottom row is filled with elements from the boundary array.
 The left column is filled with elements from the boundary array.

Java Code:
javaCopy code
import java.util.Arrays;
import java.util.Scanner;

public class BoundarySort {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of rows:");
int rows = scanner.nextInt();
System.out.println("Enter the number of columns:");
int cols = scanner.nextInt();

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


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();

sortBoundary(matrix);
System.out.println("Matrix after boundary sorting:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

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


int rows = matrix.length;
int cols = matrix[0].length;
int n = 2 * (rows + cols) - 4; // Number of boundary elements
int[] boundary = new int[n];
int idx = 0;

// Extract boundary elements in clockwise order


for (int j = 0; j < cols; j++) {
boundary[idx++] = matrix[0][j];
}
for (int i = 1; i < rows; i++) {
boundary[idx++] = matrix[i][cols - 1];
}
for (int j = cols - 2; j >= 0; j--) {
boundary[idx++] = matrix[rows - 1][j];
}
for (int i = rows - 2; i > 0; i--) {
boundary[idx++] = matrix[i][0];
}
// Sort boundary elements
Arrays.sort(boundary);

// Place the sorted elements back


idx = 0;
for (int j = 0; j < cols; j++) {
matrix[0][j] = boundary[idx++];
}
for (int i = 1; i < rows; i++) {
matrix[i][cols - 1] = boundary[idx++];
}
for (int j = cols - 2; j >= 0; j--) {
matrix[rows - 1][j] = boundary[idx++];
}
for (int i = rows - 2; i > 0; i--) {
matrix[i][0] = boundary[idx++];
}
}
}

Variable Description Table:


Variable Description
rows The number of rows in the matrix.
cols The number of columns in the matrix.
matrix A 2D array representing the matrix.
n The total number of boundary elements in the
matrix.
boundary An array to store the boundary elements extracted
from the matrix.
idx An index to keep track of the position in the
boundary array.

Sample Input and Output:


yamlCopy code
Input:
Enter the number of rows: 3
Enter the number of columns: 3
Enter the elements of the matrix:
123
456
789

Output:
Matrix after boundary sorting:
123
804
765
In this example, the user provides input for a 3x3 matrix. The program extracts the boundary elements in
a clockwise order, sorts them, and places them back in the matrix. The resulting matrix is printed as
output.

12.Stack Implementation
Question:
Explain the provided Java code for implementing a stack. Provide a variable description table and a
sample input/output example.

Algorithm:
The provided Java code demonstrates the implementation of a stack using a class named
StackImplementation. The stack is implemented using an array and various methods to manipulate the
stack operations such as push, pop, and peek. Additionally, the isFull and isEmpty methods are used to
check whether the stack is full or empty, respectively.
1st The Stack class:
 The Stack class is nested within the StackImplementation class.
 It has member variables MAX (maximum capacity of the stack), arr (an integer array to store the
elements of the stack), and top (a pointer to the top element of the stack).
 The constructor Stack(int size) initializes the stack with the given size. The top is initialized to -1 to
indicate an empty stack.
 The isFull() method checks if the stack is full, and the isEmpty() method checks if the stack is
empty.
 The push(int x) method adds an element to the top of the stack. It checks for stack overflow before
pushing.
 The pop() method removes and returns the top element from the stack. It checks for stack
underflow before popping.
 The peek() method returns the value of the top element without removing it. It also checks for stack
underflow.

1st The main method:
 Inside the main method, a Stack object named stack is created with a maximum capacity of 5.
 Three elements (1, 2, and 3) are pushed onto the stack using the push method.
 The peek method is used to display the top element.
 The pop method is used to remove and display the popped element.
 Finally, the peek method is used again to display the new top element.

Java Code:
javaCopy code
public class StackImplementation {

static class Stack {


int MAX;
int[] arr;
int top;

Stack(int size) {
MAX = size;
arr = new int[MAX];
top = -1;
}

boolean isFull() {
return top == MAX - 1;
}

boolean isEmpty() {
return top == -1;
}
void push(int x) {
if (isFull()) {
System.out.println("Stack Overflow");
return;
}
arr[++top] = x;
System.out.println(x + " pushed to stack");
}

int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top--];
}

int peek() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top];
}
}

public static void main(String[] args) {


Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Top element: " + stack.peek());
System.out.println(stack.pop() + " popped from stack");
System.out.println("Top element: " + stack.peek());
}
}

Variable Description Table:


Variable Description
MAX The maximum capacity of the stack.
arr An integer array to store the elements of the stack.
top A pointer indicating the index of the top element in
the stack.
x The element to be pushed onto the stack.
Sample Output:
arduinoCopy code
1 pushed to stack
2 pushed to stack
3 pushed to stack
Top element: 3
3 popped from stack
Top element: 2
In this example, the program demonstrates the operations of a stack. Elements 1, 2, and 3 are pushed onto
the stack. The top element is then displayed (which is 3), followed by popping an element (3) from the
stack. Finally, the new top element (2) is displayed.

13.Queue Implementation
Question:
Explain the provided Java code for implementing a queue. Provide a variable description table and a
sample input/output example.
Algorithm:
The provided Java code demonstrates the implementation of a queue using a class named
QueueImplementation. The queue is implemented using an array and various methods to manipulate the
queue operations such as enqueue, dequeue, and peek. Additionally, the isFull and isEmpty methods are
used to check whether the queue is full or empty, respectively.
1st The Queue class:
 The Queue class is nested within the QueueImplementation class.
 It has member variables MAX (maximum capacity of the queue), arr (an integer array to store the
elements of the queue), front (an index pointing to the front element of the queue), rear (an index
pointing to the rear element of the queue), and size (the current size of the queue).
 The constructor Queue(int size) initializes the queue with the given size. The front is initialized to
0, the rear to -1, and the size to 0.
 The isFull() method checks if the queue is full, and the isEmpty() method checks if the queue is
empty.
 The enqueue(int x) method adds an element to the rear of the queue. It checks for queue overflow
before enqueueing.
 The dequeue() method removes and returns the front element from the queue. It checks for queue
underflow before dequeueing.
 The peek() method returns the value of the front element without removing it. It also checks for
queue underflow.

1st The main method:
 Inside the main method, a Queue object named queue is created with a maximum capacity of 5.
 Three elements (10, 20, and 30) are enqueued into the queue using the enqueue method.
 The peek method is used to display the front element.
 The dequeue method is used to remove and display the dequeued element.
 Finally, the peek method is used again to display the new front element.

Java Code:
javaCopy code
public class QueueImplementation {

static class Queue {


int MAX;
int[] arr;
int front, rear, size;

Queue(int size) {
MAX = size;
arr = new int[MAX];
front = 0;
rear = -1;
size = 0;
}

boolean isFull() {
return size == MAX;
}

boolean isEmpty() {
return size == 0;
}

void enqueue(int x) {
if (isFull()) {
System.out.println("Queue Overflow");
return;
}
rear = (rear + 1) % MAX;
arr[rear] = x;
size++;
System.out.println(x + " enqueued to queue");
}

int dequeue() {
if (isEmpty()) {
System.out.println("Queue Underflow");
return -1;
}
int item = arr[front];
front = (front + 1) % MAX;
size--;
return item;
}

int peek() {
if (isEmpty()) {
System.out.println("Queue Underflow");
return -1;
}
return arr[front];
}
}

public static void main(String[] args) {


Queue queue = new Queue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
System.out.println("Front element: " + queue.peek());
System.out.println(queue.dequeue() + " dequeued from queue");
System.out.println("Front element: " + queue.peek());
}
}

Variable Description Table:


Variable Description
MAX The maximum capacity of the queue.
arr An integer array to store the elements of the queue.
front An index pointing to the front element of the
queue.
rear An index pointing to the rear element of the queue.
size The current size of the queue.
Variable Description
x The element to be enqueued into the queue.
item The element dequeued from the front of the queue.

Sample Output:
arduinoCopy code
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
Front element: 10
10 dequeued from queue
Front element: 20
In this example, the program demonstrates the operations of a queue. Elements 10, 20, and 30 are
enqueued into the queue. The front element is then displayed (which is 10), followed by dequeuing an
element (10) from the queue. Finally, the new front element (20) is displayed.

14.LargeFactorial

Question:
Explain the provided Java code for calculating the factorial of a large number using the BigInteger class.
Provide a variable description table and a sample input/output example.

Algorithm:
The provided Java code calculates the factorial of a given number using the BigInteger class, which is
capable of handling large integer values without causing overflow or loss of precision. This is especially
useful when calculating factorials of large numbers that cannot be accommodated within the range of
standard integer types.
1st The main method:
 The user is prompted to input a number using the Scanner class.
 The findFactorial method is then called with the input number to calculate the factorial.
 The calculated factorial is printed as the output.

1st The findFactorial method:
 This method calculates the factorial of the input number using a BigInteger variable named fact.
 fact is initialized with the value of BigInteger.ONE, which represents the value 1.
 A loop iterates from 2 to the input number (inclusive).
 In each iteration, the fact variable is multiplied by the current value of i, where i is the loop
variable.
 The result of the multiplication is assigned back to the fact variable.
 After the loop completes, the method returns the calculated factorial.

Java Code:
javaCopy code
import java.util.Scanner;
import java.math.BigInteger;

public class LargeFactorial {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int num = scanner.nextInt();
scanner.close();

BigInteger factorial = findFactorial(num);


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

public static BigInteger findFactorial(int num) {


BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= num; i++) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}

Variable Description Table:


Variable Description
num The input number for which the factorial is to be
calculated.
factorial The BigInteger variable to store the calculated
factorial value.
fact A BigInteger variable used to calculate the
factorial.
i Loop variable used in the findFactorial loop.

Sample Input/Output:
vbnetCopy code
Input: 10
Output: Factorial of 10 is: 3628800
In this example, the program calculates the factorial of the input number 10 using the BigInteger class and
displays the result. The factorial of 10 is 3628800.
15.Bank System
Question:
Provide an explanation of the given Java code that represents a simple bank system with account types
including SavingsAccount and CurrentAccount. Include a variable description table and a sample output.

Algorithm:
The provided Java code simulates a basic bank system that includes two types of accounts:
SavingsAccount and CurrentAccount. These classes inherit from a base Account class. Each account type
has specific features and methods that cater to the characteristics of savings and current accounts.
1st The Account class:
 This class serves as the base class for both SavingsAccount and CurrentAccount.
 It contains a protected instance variable balance, along with methods for depositing, withdrawing,
and retrieving the balance.

1st The SavingsAccount class:
 This class extends the Account class and adds properties such as interestRate and
minimumBalance.
 It overrides the withdraw method to check if the withdrawal amount breaches the minimum
balance.
 The addInterest method calculates and adds interest to the balance.

1st The CurrentAccount class:
 Similar to the SavingsAccount class, this class extends the Account class and includes an
overdraftLimit property.
 The withdraw method checks if the withdrawal amount breaches the overdraft limit.

1st The BankSystem class:
 This class contains the main method, which demonstrates the usage of the defined account classes.
 A SavingsAccount and a CurrentAccount object are created with initial balances and relevant
properties.
 Various account operations are performed, such as withdrawals, interest addition, etc.
 The results are displayed as output.

Java Code:
javaCopy code
class Account {
protected double balance;

public Account(double balance) {


this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


balance -= amount;
}

public double getBalance() {


return balance;
}
}

class SavingsAccount extends Account {


private double interestRate;
private double minimumBalance;

public SavingsAccount(double balance, double interestRate, double minimumBalance) {


super(balance);
this.interestRate = interestRate;
this.minimumBalance = minimumBalance;
}

@Override
public void withdraw(double amount) {
if (balance - amount >= minimumBalance) {
super.withdraw(amount);
} else {
System.out.println("Cannot withdraw as it will breach the minimum balance.");
}
}
public void addInterest() {
balance += balance * interestRate;
}
}

class CurrentAccount extends Account {


private double overdraftLimit;

public CurrentAccount(double balance, double overdraftLimit) {


super(balance);
this.overdraftLimit = overdraftLimit;
}

@Override
public void withdraw(double amount) {
if (balance - amount >= -overdraftLimit) {
super.withdraw(amount);
} else {
System.out.println("Cannot withdraw as it will breach the overdraft limit.");
}
}
}

public class BankSystem {

public static void main(String[] args) {


SavingsAccount savings = new SavingsAccount(1000, 0.05, 500);
CurrentAccount current = new CurrentAccount(1000, 500);

savings.withdraw(600);
savings.addInterest();
System.out.println("Savings account balance: " + savings.getBalance());

current.withdraw(1200);
System.out.println("Current account balance: " + current.getBalance());
}
}
Variable Description Table:

Variable Description
balance The current balance of an account.
interestRate The interest rate for the savings account.
minimumBalance The minimum balance required for the savings
account.
overdraftLimit The overdraft limit for the current account.
savings An instance of the SavingsAccount class.
current An instance of the CurrentAccount class.
amount The amount to deposit or withdraw from an
account.

Sample Output:
yamlCopy code
Cannot withdraw as it will breach the minimum balance.
Savings account balance: 950.0
Cannot withdraw as it will breach the overdraft limit.
Current account balance: 1000.0
In this example, the program simulates a bank system using the SavingsAccount and CurrentAccount
classes. Withdrawals that would breach the minimum balance or overdraft limit are prevented. Interest is
added to the savings account balance, and the results are displayed as output.
16.Swap Without Third Variable
Question:
Could you please explain the algorithm used in the provided Java code for swapping two numbers
without using a third variable? Additionally, provide a sample input and output.

Algorithm Explanation:
The provided Java code demonstrates a simple algorithm to swap two numbers (a and b) without using a
third variable. The algorithm uses basic arithmetic operations to achieve the swapping:
1st Input two numbers, a and b, from the user.
2nd Perform the following steps: a. Add the value of a and b and store the result in a. (a = a + b) b.
Subtract the value of b from the new value of a and store the result in b. (b = a - b) c. Subtract the
value of b (which is now the original value of a) from the new value of a (which is the sum of the
original a and b) and store the result in a. (a = a - b)
After these steps, the values of a and b are swapped without using a third variable.

Java Code:
javaCopy code
import java.util.Scanner;

public class SwapWithoutThirdVariable {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number:");
int a = scanner.nextInt();
System.out.println("Enter the second number:");
int b = scanner.nextInt();
scanner.close();

a = a + b;
b = a - b;
a = a - b;

System.out.println("After swapping:");
System.out.println("First number: " + a);
System.out.println("Second number: " + b);
}
}

Variable Description Table:


Variable Description
a Stores the value of the first input number.
b Stores the value of the second input number.
scanner An instance of the Scanner class used for reading
input from the user.

Sample Input/Output:
yamlCopy code
Enter the first number:
5
Enter the second number:
10
After swapping:
First number: 10
Second number: 5
In this example, the user inputs two numbers: 5 and 10. After the swapping algorithm is applied, the
values of a and b are swapped, resulting in a being 10 and b being 5. This demonstrates the swapping of
two numbers without using a third variable.

17.Square Root Without Library


Question: Could you please explain the algorithm used in the provided Java code for calculating the
square root of a number without using a library function? Also, provide a sample input and output.
Algorithm Explanation: The provided Java code demonstrates an algorithm to calculate the square root
of a given number without using a library function. The algorithm uses the binary search approach to find
the square root with a specified precision.
1st Input a number, num, from the user.
2nd Define a precision value, precision (e.g., 0.00001), to determine how close the approximation
needs to be.
3rd Initialize variables: start, end, and mid.
 If num is less than 1, set end to 1.
 Otherwise, set end to num.
 Set start to 0.
 Calculate mid as the average of start and end.

1st Use a loop to iteratively adjust start and end values to approach the square root:
 If mid * mid is less than num, set start to mid.
 Otherwise, set end to mid.
 Calculate a new mid value as the average of the updated start and end.
 Continue iterating until the difference between mid * mid and num is less than the specified
precision.

1st The value of mid after the loop represents the approximate square root of the input num .
Java Code:
javaCopy code
import java.util.Scanner;

public class SquareRootWithoutLibrary {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
double num = scanner.nextDouble();
scanner.close();

double precision = 0.00001;


double start = 0, end;
if (num < 1) {
end = 1;
} else {
end = num;
}
double mid = (start + end) / 2;
while (Math.abs(mid * mid - num) > precision) {
if (mid * mid < num) {
start = mid;
} else {
end = mid;
}
mid = (start + end) / 2;
}
System.out.println("Square root of " + num + " is approximately: " + mid);
}
}

Variable Description Table:

Variable Description
num Stores the input number for which the square root
needs to be calculated.
precision Represents the desired precision for the square root
approximation.
start Represents the lower bound of the range for which
the square root is being approximated. Initially set
to 0.
end Represents the upper bound of the range for which
the square root is being approximated. If num is
less than 1, end is set to 1, otherwise, it is set to
num.
mid Represents the midpoint of the range for which the
square root is being approximated. Initially
calculated as the average of start and end.

Sample Input/Output:
mathematicaCopy code
Enter a number:
25
Square root of 25.0 is approximately: 5.0
In this example, the user inputs the number 25. The algorithm iteratively approximates the square root of
25 using the binary search approach, and the result is approximately 5.0. The algorithm aims to achieve
the desired precision (0.00001) in the approximation.

18.String Permutations
Question:
Could you please explain the algorithm used in the provided Java code for generating permutations of a
string? Also, provide a sample input and output.

Algorithm Explanation:
The provided Java code demonstrates an algorithm to generate all permutations of a given string. The
algorithm utilizes a recursive approach to achieve this. Here's how the algorithm works:
1st Input a string, str, from the user.
2nd Call the generatePermutations function with the input string and an empty prefix.
3rd The generatePermutations function is a recursive function with two parameters:
 str: The portion of the string yet to be processed.
 prefix: The portion of the string that has been processed so far and forms part of a potential
permutation.

1st If the length of the str is 0, it means all characters have been processed, and a permutation has been
formed. Print the prefix as the output.
2nd Otherwise, iterate through each character of the str:
 Create a string rem that removes the current character from the str.
 Recursively call generatePermutations with the new rem and the prefix concatenated with the
current character.

1st The recursion continues until all possible permutations have been generated.

Java Code:
javaCopy code
import java.util.Scanner;

public class StringPermutations {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String str = scanner.nextLine();
scanner.close();

generatePermutations(str, "");
}

public static void generatePermutations(String str, String prefix) {


if (str.length() == 0) {
System.out.println(prefix);
} else {
for (int i = 0; i < str.length(); i++) {
String rem = str.substring(0, i) + str.substring(i + 1);
generatePermutations(rem, prefix + str.charAt(i));
}
}
}
}
Variable Description Table:

Variable Description
str Stores the input string for which permutations need
to be generated.
prefix Stores the current permutation being formed.
Initially set to an empty string.
scanner An instance of the Scanner class used for reading
input from the user.

Sample Input/Output:
cCopy code
Enter a string:
abc
abc
acb
bac
bca
cab
cba
In this example, the user inputs the string "abc". The algorithm generates all possible permutations of the
characters "a", "b", and "c". The output includes all six permutations: "abc", "acb", "bac", "bca", "cab",
and "cba". Each permutation is printed on a separate line.
19.Magic Square
Question:
The given Java program generates and displays a magic square of odd size. Write an algorithm for the
program, provide the Java code, create a variable description table, and give a sample input along with its
corresponding output.

Algorithm:
1st Initialize a Scanner object to read input from the user.
2nd Display the message "Enter the size of the magic square (odd number only):" to prompt the user
for input.
3rd Read an integer n (size of the magic square) using the nextInt() method of the Scanner.
4thClose the Scanner object to release system resources.
5thCheck if n is even. If it is, print "Size should be an odd number." and return from the program.
6thInitialize a 2D array magicSquare of size n by n to store the magic square values.
7thInitialize variables i and j to determine the current row and column respectively, and num to represent
the current value to be placed.
8thUse a loop that runs from num = 1 to num = n * n:
 Place the value num at the current position (i, j) in the magicSquare array.
 Increment num.
 Calculate the next row and column to move to using modulo arithmetic to ensure wraparound
within the array bounds.
 If the next position is unoccupied, update i and j to the next position; otherwise, move only to the
next row.

1st Return the magicSquare array.

Java Code:
javaCopy code
import java.util.Scanner;

public class MagicSquare {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of the magic square (odd number only):");
int n = scanner.nextInt();
scanner.close();

if (n % 2 == 0) {
System.out.println("Size should be an odd number.");
return;
}

int[][] magicSquare = generateMagicSquare(n);

System.out.println("Magic Square:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(magicSquare[i][j] + "\t");
}
System.out.println();
}
}

public static int[][] generateMagicSquare(int n) {


// Implementation of the magic square generation algorithm
}
}

Variable Description Table:


Variable Description
scanner A Scanner object to read user input.
n An integer representing the size of the magic
square.
magicSquare A 2D array to store the generated magic square.
i, j Integers representing current row and column
positions.
num Integer to represent the current value to be placed.

Sample Input and Output:


Input:
scssCopy code
Enter the size of the magic square (odd number only):
5
Output:
mathematicaCopy code
Magic Square:
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
In this example, the user entered a size of 5, and the program generated and displayed a magic square of
odd size.
20.Circular Queue Implementation
Question:
The given Java program implements a circular queue using an array. Write an algorithm for the program,
provide the Java code, create a variable description table, and give a sample input along with its
corresponding output.

Algorithm:
1st
2nd Initialize a Scanner object to read input from the user.
3rd
4thDisplay the message "Enter the size of the queue:" to prompt the user for input.
5th
6thRead an integer size (size of the circular queue) using the nextInt() method of the Scanner.
7th
8thCreate a new CircularQueue object named queue with the given size.
9th
10th Enter an infinite loop to repeatedly display the menu options and perform queue operations until
the user chooses to exit:
 Display the menu options: "1. Enqueue", "2. Dequeue", "3. Display", "4. Exit".
 Read the user's choice using the nextInt() method of the Scanner.

1st In a switch statement, based on the user's choice:
 Case 1: Enqueue
 Display the message "Enter the value to enqueue:" to prompt the user for input.
 Read an integer value using the nextInt() method of the Scanner.
 Call the enqueue method of the queue object with the value as an argument.

 Case 2: Dequeue
 Call the dequeue method of the queue object to dequeue an element.

 Case 3: Display
 Call the display method of the queue object to display the queue's contents.

 Case 4: Exit
 Display the message "Exiting...".
 Close the Scanner object to release system resources.
 Return from the main method to exit the program.

 Default: Invalid option
 Display the message "Invalid option! Try again."

Java Code:
javaCopy code
import java.util.Scanner;

class CircularQueue {
// Implementation of the CircularQueue class
}

public class CircularQueueImplementation {


// Implementation of the main method
}

Variable Description Table:


Variable Description
scanner A Scanner object to read user input.
size An integer representing the size of the queue.
queue An instance of the CircularQueue class.
choice An integer representing the user's menu choice.
value An integer representing the value to enqueue.
Sample Input and Output:
Input/Output:
markdownCopy code
Enter the size of the queue:
5

Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter the value to enqueue:
10
Enqueued 10 to the queue.

Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter the value to enqueue:
20
Enqueued 20 to the queue.

Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
3
Queue elements: 10 20

Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
2
Dequeued 10 from the queue.

Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
3
Queue elements: 20
Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
4
Exiting...
21.Decimal To Base

Question:
The given Java program converts a decimal number to a specified base between 2 and 16. Write an
algorithm for the program, provide the Java code, create a variable description table, and give a sample
input along with its corresponding output.

Algorithm:
1st
2nd Initialize a Scanner object to read input from the user.
3rd
4thDisplay the message "Enter the decimal number:" to prompt the user for input.
5th
6thRead an integer decimalNumber (the decimal number to be converted) using the nextInt() method of
the Scanner.
7th
8thDisplay the message "Enter the base (between 2 and 16):" to prompt the user for input.
9th
10th Read an integer base (the base to which the decimal number will be converted) using the nextInt()
method of the Scanner.
11th
12th Close the Scanner object to release system resources.
13th
14th Check if the entered base is less than 2 or greater than 16. If it is, print "Invalid base. Enter a base
between 2 and 16." and return from the program.
15th
16th Call the convertToBase function with decimalNumber and base as arguments.
17th
18th Display the converted number along with a message.
19th

Java Code:
import java.util.Scanner;
import java.util.Stack;

public class DecimalToBase {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the decimal number:");
int decimalNumber = scanner.nextInt();
System.out.println("Enter the base (between 2 and 16):");
int base = scanner.nextInt();
scanner.close();

if (base < 2 || base > 16) {


System.out.println("Invalid base. Enter a base between 2 and 16.");
return;
}

String convertedNumber = convertToBase(decimalNumber, base);

System.out.println("Number " + decimalNumber + " in base " + base + " is: " + convertedNumber);
}

public static String convertToBase(int number, int base) {


Stack<Character> stack = new Stack<>();
char[] baseChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

while (number > 0) {


int remainder = number % base;
stack.push(baseChars[remainder]);
number /= base;
}

StringBuilder result = new StringBuilder();


while (!stack.isEmpty()) {
result.append(stack.pop());
}

return result.toString();
}
}

Variable Description Table:


Variable Description
scanner A Scanner object to read user input.
decimalNumber An integer representing the decimal number to
convert.
base An integer representing the base for conversion.
stack A Stack to hold the characters of the converted
number.
baseChars An array of characters representing digits and
letters for bases up to 16.
remainder An integer representing the remainder in each step
of conversion.
result A StringBuilder to store the converted number.
Sample Input and Output:
Input:
mathematicaCopy code
Enter the decimal number:
255
Enter the base (between 2 and 16):
16
Output:
csharpCopy code
Number 255 in base 16 is: FF
In this example, the user entered a decimal number 255 and a base 16. The program converted the
decimal number to its hexadecimal representation, which is FF.
22.Distance Between Points

Question:
The given Java program calculates the distance between two points in a 2D plane. Write an algorithm for
the program, provide the Java code, create a variable description table, and give a sample input along with
its corresponding output.

Algorithm:
1st
2nd Initialize a Scanner object to read input from the user.
3rd
4thDisplay the message "Enter the coordinates for Point 1 (x y):" to prompt the user for the coordinates of
the first point.
5th
6thRead two double values x1 and y1 representing the x and y coordinates of Point 1 using the
nextDouble() method of the Scanner.
7th
8thDisplay the message "Enter the coordinates for Point 2 (x y):" to prompt the user for the coordinates of
the second point.
9th
10th Read two double values x2 and y2 representing the x and y coordinates of Point 2 using the
nextDouble() method of the Scanner.
11th
12th Close the Scanner object to release system resources.
13th
14th Create two Point objects point1 and point2 using the entered coordinates.
15th
16th Call the calculateDistance function with point1 and point2 as arguments.
17th
18th Display the calculated distance along with a message.
19th

Java Code:
javaCopy code
import java.util.Scanner;

class Point {
// Implementation of the Point class
}

public class DistanceBetweenPoints {


// Java code for the DistanceBetweenPoints program
}
Variable Description Table:
Variable Description
scanner A Scanner object to read user input.
x1, y1 double values representing the coordinates of Point
1.
x2, y2 double values representing the coordinates of Point
2.
point1, point2 Point objects representing the two points.
distance double representing the calculated distance.

Sample Input and Output:


Input:
mathematicaCopy code
Enter the coordinates for Point 1 (x y):
1.0 2.0
Enter the coordinates for Point 2 (x y):
4.0 6.0
Output:
csharpCopy code
Distance between the two points is: 5.0
In this example, the user entered the coordinates of two points: Point 1 (1.0, 2.0) and Point 2 (4.0, 6.0).
The program calculated the Euclidean distance between these two points, which is 5.0.
23.Text File Creation
Question:
The given Java program creates a text file with user-specified content. Write an algorithm for the
program, provide the Java code, create a variable description table, and give a sample input along with its
corresponding output.

Algorithm:
1st
2nd Initialize a Scanner object to read input from the user.
3rd
4thDisplay the message "Enter the filename (with .txt extension):" to prompt the user for the filename.
5th
6thRead a String filename representing the desired filename (with .txt extension) using the nextLine()
method of the Scanner.
7th
8thDisplay the message "Enter the content to write to the file:" to prompt the user for the content.
9th
10th Read a String content representing the content to be written to the file using the nextLine()
method of the Scanner.
11th
12th Close the Scanner object to release system resources.
13th
14th Use a try block to handle file operations:
 Create a FileWriter named fileWriter with the specified filename.
 Write the content to the file using the write method of the FileWriter.
 Close the FileWriter to save the changes to the file.

1st In case of an IOException, catch the exception and:
 Display "An error occurred while creating the file."
 Print the exception stack trace.

Java Code:
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;

public class TextFileCreation {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the filename (with .txt extension):");
String filename = scanner.nextLine();
System.out.println("Enter the content to write to the file:");
String content = scanner.nextLine();
scanner.close();
try {
FileWriter fileWriter = new FileWriter(filename);
fileWriter.write(content);
fileWriter.close();
System.out.println("File " + filename + " has been created successfully!");
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
}

Variable Description Table:


Variable Description
scanner A Scanner object to read user input.
filename A String representing the filename with .txt
extension.
content A String representing the content to be written to
the file.
fileWriter A FileWriter object to write content to the file.

Sample Input and Output:


Input:
vbnetCopy code
Enter the filename (with .txt extension):
output.txt
Enter the content to write to the file:
Hello, this is a test content.
Output:
arduinoCopy code
File output.txt has been created successfully!
In this example, the user entered the filename output.txt and the content "Hello, this is a test content.".
The program successfully created the file and wrote the provided content to it.
24.CommonElementsInArrays
Question:
The given Java program finds the common elements in three sorted arrays. Write an algorithm for the
program, provide the Java code, create a variable description table, and give a sample input along with its
corresponding output.

Algorithm:
1st
2nd Initialize three sorted arrays arr1, arr2, and arr3.
3rd
4thDisplay the message "Common elements are:".
5th
6thCall the findCommon function with arr1, arr2, and arr3 as arguments.
7th
8thIn the findCommon function:
 Initialize three pointers i, j, and k to traverse arr1, arr2, and arr3 respectively.

 Use a while loop to iterate until any of the arrays reaches its end:
 If arr1[i], arr2[j], and arr3[k] are equal:
 Print the common element.
 Increment all three pointers (i, j, and k).

 Else if arr1[i] is less than arr2[j], increment i.
 Else if arr2[j] is less than arr3[k], increment j.
 Else increment k.


1st End of the program.
2nd

Java Code:
public class CommonElementsInArrays {

public static void main(String[] args) {


int[] arr1 = {1, 5, 10, 20, 40, 80};
int[] arr2 = {6, 7, 20, 80, 100};
int[] arr3 = {3, 4, 15, 20, 30, 70, 80, 120};

System.out.println("Common elements are:");


findCommon(arr1, arr2, arr3);
}

public static void findCommon(int[] arr1, int[] arr2, int[] arr3) {


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

while (i < arr1.length && j < arr2.length && k < arr3.length) {


if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
System.out.print(arr1[i] + " ");
i++;
j++;
k++;
} else if (arr1[i] < arr2[j]) {
i++;
} else if (arr2[j] < arr3[k]) {
j++;
} else {
k++;
}
}
}
}

Variable Description Table:


Variable Description
arr1 An array of integers representing the first sorted
array.
arr2 An array of integers representing the second sorted
array.
arr3 An array of integers representing the third sorted
array.
i, j, k Integer pointers for traversing the three arrays.

Sample Input and Output:


Output:
sqlCopy code
Common elements are:
20 80
In this example, the program finds the common elements in the three sorted arrays:
 arr1: {1, 5, 10, 20, 40, 80}
 arr2: {6, 7, 20, 80, 100}
 arr3: {3, 4, 15, 20, 30, 70, 80, 120}
The common elements are 20 and 80, which are printed as output.
25.PendulumArrangement
Question:
The given Java program arranges the elements of an array in a pendulum arrangement. Write an algorithm
for the program, provide the Java code, create a variable description table, and give a sample input along
with its corresponding output.

Algorithm:
1st
2nd Initialize a Scanner object to read input from the user.
3rd
4thDisplay the message "Enter the size of the array:" to prompt the user for the size of the array.
5th
6thRead an integer n representing the size of the array using the nextInt() method of the Scanner.
7th
8thCreate an integer array arr of size n.
9th
10th Display the message "Enter the elements of the array:" to prompt the user for the elements of the
array.
11th
12th Use a for loop to read n elements and store them in the arr array.
13th
14th Close the Scanner object to release system resources.
15th
16th Call the getPendulumArrangement function with the arr array as an argument.
17th
18th Display the pendulum arrangement by printing each element of the resulting pendulumArr array.
19th

Java Code:
javaCopy code
import java.util.Arrays;
import java.util.Scanner;

public class PendulumArrangement {


// Java code for the PendulumArrangement program
}

Variable Description Table:


Variable Description
scanner A Scanner object to read user input.
n An integer representing the size of the array.
arr An integer array to store the elements of the input
array.
Variable Description
pendulumArr An integer array to store the pendulum
arrangement.
center An integer representing the center index of the
array.
left, right Integer indices for arranging elements to the left
and right of the center.
i Integer used in looping through the array.

Sample Input and Output:


Input:
cCopy code
Enter the size of the array:
6
Enter the elements of the array:
739152
Output:
yamlCopy code
Pendulum arrangement:
523179
In this example, the user entered an array of size 6 with elements {7, 3, 9, 1, 5, 2}. The program arranged
the elements in a pendulum arrangement and printed the result as output.

26.FactorialUsingRecursion

Question:
The goal of this program is to calculate the factorial of a given number using recursion.
Algorithm:
1st Input a number from the user.
2nd Call the computeFactorial method with the input number as an argument to calculate the factorial.
3rd Print the calculated factorial.
Java Code:
javaCopy code
import java.util.Scanner;

public class FactorialUsingRecursion {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
scanner.close();

long factorial = computeFactorial(num);

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


}

public static long computeFactorial(int num) {


if (num == 0 || num == 1) {
return 1;
}
return num * computeFactorial(num - 1);
}
}
Variable Description Table:
Variable Description
num Stores the input number for which the factorial is to
be calculated.
scanner An instance of the Scanner class used for reading
input from the user.
factorial Stores the calculated factorial value.

Sample Input:
cssCopy code
Enter a number:
5
Output:
csharpCopy code
Factorial of 5 is: 120
In this example, the input number is 5. The computeFactorial method calculates the factorial using
recursion and returns the result, which is 120. The output displays the calculated factorial for the input
number.

27.BinaryTreeTraversal
Question:
The goal of this program is to demonstrate different traversals (inorder, preorder, postorder) of a binary
tree.

Algorithm:
1st Define a Node class to represent individual nodes in the binary tree.
2nd Inside the BinaryTreeTraversal class:
 Define inorder, preorder, and postorder methods to perform corresponding tree traversals.
 In each traversal method, if the current node is not null, recursively traverse the left subtree,
process the current node, and recursively traverse the right subtree.

1st In the main method:
 Create an instance of BinaryTreeTraversal.
 Build a sample binary tree by creating nodes and assigning their left and right children.
 Print the inorder, preorder, and postorder traversals of the binary tree.

Java Code:
javaCopy code
class Node {
int value;
Node left, right;

public Node(int item) {


value = item;
left = right = null;
}
}

public class BinaryTreeTraversal {

Node root;

void inorder(Node node) {


if (node == null) {
return;
}
inorder(node.left);
System.out.print(node.value + " ");
inorder(node.right);
}

void preorder(Node node) {


if (node == null) {
return;
}
System.out.print(node.value + " ");
preorder(node.left);
preorder(node.right);
}

void postorder(Node node) {


if (node == null) {
return;
}
postorder(node.left);
postorder(node.right);
System.out.print(node.value + " ");
}

public static void main(String[] args) {


BinaryTreeTraversal tree = new BinaryTreeTraversal();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);

System.out.println("Inorder traversal:");
tree.inorder(tree.root);

System.out.println("\nPreorder traversal:");
tree.preorder(tree.root);

System.out.println("\nPostorder traversal:");
tree.postorder(tree.root);
}
}
Variable Description Table:
Variable Description
Node Represents an individual node in the binary tree.
Contains value, left, and right attributes.
root The root node of the binary tree.
tree An instance of the BinaryTreeTraversal class.
item An integer value to be assigned to a node.

Sample Output:
yamlCopy code
Inorder traversal:
42513
Preorder traversal:
12453
Postorder traversal:
45231
In this example, a binary tree is constructed and traversed using inorder, preorder, and postorder traversal
methods. The printed outputs show the order in which nodes are visited during each traversal.
Conclusion
Java programming is a versatile and widely-used language that has made a significant
impact in various domains, including software development, web applications, mobile
apps, and more. Here's a conclusion about Java programming:

Java's Versatility: Java's "write once, run anywhere" philosophy has been a major driver
of its popularity. Its platform independence, achieved through the Java Virtual Machine
(JVM), allows Java programs to run on different operating systems without modification.
Strong Ecosystem: Java boasts a rich ecosystem of libraries, frameworks, and tools that
facilitate development across diverse domains. Popular frameworks like Spring enable
rapid and efficient development of robust applications.

Object-Oriented Paradigm: Java's strong emphasis on object-oriented programming


promotes modular, reusable, and maintainable code. Its class-based structure
encourages developers to organize code into meaningful units.
Safety and Reliability: Java's robust type system, exception handling, and memory
management contribute to the language's reputation for safety and reliability. This
makes it well-suited for large-scale applications.

Community and Resources: Java's large and active community has led to a wealth of
online resources, tutorials, and forums, making it easy for developers to learn, share
knowledge, and find solutions to problems.
Mobile Development: With the advent of Android, Java became a dominant language for
mobile app development, offering developers the opportunity to create applications for a
wide user base.

Challenges and Evolution: While Java remains strong, it faces challenges from
emerging languages and paradigms. The language has evolved over the years with
features like lambdas and modules to stay current.

Career Opportunities: Proficiency in Java opens up diverse career opportunities, from


backend development and enterprise software to Android app development and more.
In conclusion, Java programming's versatility, community support, and robust features
have solidified its place as a cornerstone of modern software development. Its role in
various domains, combined with its adaptability and ongoing evolution, ensures that
Java will continue to be a relevant and influential language in the programming
landscape.

You might also like