Java Programs for ISBN and Prime Checks
Java Programs for ISBN and Prime Checks
Write a program in Java to accept a ten digit code from the user
and check if the code is a valid ISBN.
ALGORITHM:
JAVA CODE:
import [Link].*;
class ISBN_code
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
[Link]("INPUT CODE: ");
String isbn = [Link](); // Read user input for ISBN code
int l = [Link](); // Calculate the length of the input
int i, t, ctr, s;
char ch;
if(l!= 10)
{
[Link]("INVALID INPUT");
//If input length is not 10, print error message
}
else
{
ctr = 10; // Initialize counter
s = 0; // Initialize sum
for(i=0;i < l;i++)
{
1|P age
ch = [Link](i); // Get the character at position i in the ISBN
code
if(ch == 'X')
t = 10; // If character is 'X', assign t the value 10
else
t = ch - 48; // Convert character to integer value
s= s + ctr*t; // Calculate the weighted sum
ctr--; // Decrement the counter
}
if(s%11 == 0)
{
[Link]("SUM = "+s);
[Link]("LEAVES NO REMAINDER - VALID ISBN CODE");
}
else
{
[Link]("SUM = "+s);
[Link]("LEAVES REMAINDER - INVALID ISBN CODE");
}
}
}
}
VARIABLE DESCRIPTION:
Variable Data Type Description
br BufferedReader Used to read input
from the user.
isbn String Stores the input ISBN
code.
l int Stores the length of
the ISBN code.
i int Used as a loop
iteration variable.
t int Stores the current
digit value.
ctr int Used as the weight
counter for digits.
s int Stores the sum of
weighted digits.
ch char Stores the current
character in the
loop.
2|P age
OUTPUT:
3|P age
QUESTION 2
ALGORITHM:
1. Begin program.
2. Prompt for integer 'n'.
3. Read 'n'.
4. If 'n' <= 0, display "INVALID INPUT" and end.
5. Check if 'n' is prime.
6. If prime, perform circular rotation for circular primes:
a. Display 'n' (circular prime by itself).
b. For each circular rotation of 'n':
i. If not prime, set 'isCircularPrime' to false and exit
loop.
7. Display based on 'isCircularPrime':
a. If true, show "n IS A CIRCULAR PRIME."
b. If false, show "n IS NOT A CIRCULAR PRIME."
8. End program.
JAVA CODE:
import [Link];
public class CircularPrime
{ // Function to check if a number is prime
public static boolean isPrime(int num)
{
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
c++;
}
}
return c == 2;
} // Function to count the number of digits in a number
public static int getDigitCount(int num)
{
int c = 0;
while (num != 0)
{
c++;
num /= 10;
}
return c;
}
4|P age
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER INTEGER TO CHECK (N): ");
int n = [Link]();
if (n <= 0)
{
[Link]("INVALID INPUT");
return;
}
boolean isCircularPrime = true;
if (isPrime(n)) // Check if the input number is prime
{
[Link](n); // Print the original number
int digitCount = getDigitCount(n);
int divisor = (int)([Link](10, digitCount - 1));
int n2 = n; // Initialize a variable for rotation
for (int i = 1; i < digitCount; i++)
{
int t1 = n2 / divisor;
int t2 = n2 % divisor;
n2 = t2 * 10 + t1;
[Link](n2); // Print the rotated number
if (!isPrime(n2))
{ // If rotated number is not prime, break the loop
isCircularPrime = false;
break;
}
}
}
else
{
isCircularPrime = false;
}
// Print the result
if (isCircularPrime)
{
[Link](n + " IS A CIRCULAR PRIME.");
}
else
{
[Link](n + " IS NOT A CIRCULAR PRIME.");
}
}
}
5|P age
VARIABLE DESCRIPTION:
OUTPUT:
6|P age
QUESTION 3
Write a program to accept an even integer 'N' where N > 9 and N <
50. Find all the odd prime pairs whose sum is equal to the number
'N'.
ALGORITHM:
1. Begin program.
2. Prompt for integer 'n'.
3. Read 'n'.
4. If 'n' <= 9 or 'n' >= 50, display "INVALID INPUT. NUMBER OUT OF
RANGE." and end.
5. If 'n' is odd, display "INVALID INPUT. NUMBER IS ODD." and end.
6. Initialize 'a' as 3 and 'b' as 0.
7. Display "PRIME PAIRS ARE:" for prime pairs.
8. Use a while loop to find prime pairs ('b' = 'n' - 'a') with odd
'a' ≤ 'n' / 2, both 'a' and 'b' being prime, and 'a' incremented
by 2.
9. End program.
JAVA CODE:
import [Link];
public class GoldbachNumber
{ // Function to check if a number is prime
public static boolean isPrime(int num)
{
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
c++;
}
}
return c == 2;
}
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER THE VALUE OF N: ");
int n = [Link]();
if (n <= 9 || n >= 50)
{
[Link]("INVALID INPUT. NUMBER OUT OF RANGE.");
return;
}
if (n % 2 != 0)
{
7|P age
[Link]("INVALID INPUT. NUMBER IS ODD.");
return;
}
[Link]("PRIME PAIRS ARE:");
int a = 3; // Starting value for the first prime
int b = 0;
while (a <= n / 2)
{
b = n - a; // Calculate the second prime in the pair
if (isPrime(a) && isPrime(b))
{
[Link](a + ", " + b); // Print the prime pair
}
a += 2; // Increment a by 2 to skip even numbers (odd primes)
}
}
}
VARIABLE DSCRIPTION:
OUTPUT:
8|P age
QUESTION 4
ALGORITHM:
JAVA CODE:
import [Link];
public class PrimeAdam
{ // Function to reverse a number
public static int reverse(int num)
{
int rev = 0;
while (num != 0)
{
int d = num % 10;
rev = rev * 10 + d;
num /= 10;
}
return rev;
}
public static boolean isAdam(int num)
{ // Function to check if a number is an Adam number
int sqNum = num * num;
int revNum = reverse(num);
int sqRevNum = revNum * revNum;
int rev = reverse(sqNum);
return rev == sqRevNum;
}
public static boolean isPrime(int num)
9|P age
{ // Function to check if a number is prime
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
c++;
}
}
return c == 2;
}
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter the value of m: ");
int m = [Link]();
[Link]("Enter the value of n: ");
int n = [Link]();
int count = 0; // Counter to keep track of the frequency
if (m >= n)
{
[Link]("INVALID INPUT");
return;
}
[Link]("THE PRIME-ADAM INTEGERS ARE:");
for (int i = m; i <= n; i++)
{
boolean adam = isAdam(i);
if (adam)
{
boolean prime = isPrime(i);
if (prime)
{
[Link](i + " "); // Print the prime-Adam integer
count++;
}
}
}
if (count == 0)
{
[Link]("NIL"); // If no prime-Adam integers were found
}
[Link]();
[Link]("FREQUENCY OF PRIME-ADAM INTEGERS IS: " +
count);
}
}
10 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
11 | P a g e
QUESTION 5
ALGORITHM:
JAVA CODE:
import [Link];
public class FactorialCalculator
{ // Recursive function to calculate the factorial of a number
public static BigInteger factorial(int num)
{
if (num == 0 || num == 1)
{
return [Link]; // Factorial of 0 and 1 is 1
}
else
{ // Multiply the number by the factorial of the previous number
return [Link](num).multiply(factorial(num - 1));
}
}
public static void main(String[] args)
{
[Link] scanner = new [Link]([Link]);
[Link]("Enter a positive integer: ");
int number = [Link]();
if (number < 0)
{
[Link]("Factorial is not defined for negative
numbers.");
}
else
{
12 | P a g e
BigInteger result = factorial(number); // Calculate the factorial
[Link]("Factorial of " + number + " is: " + result);
}
[Link](); // Close the scanner to prevent resource leakage
}
}
VARIABLE DESCRIPTION:
OUTPUT:
13 | P a g e
QUESTION 6
ALGORITHM:
1. Define a recursive function decimalToBinary that takes an
integer decimal as input and returns a binary string.
2. If decimal is 0, return the string "0".
3. If decimal is 1, return the string "1".
4. Otherwise, return the concatenation of
decimalToBinary(decimal/2) and the remainder of decimal divided
by 2 (decimal % 2).
JAVA CODE:
14 | P a g e
}
VARIABLE DESCIPTION
OUTPUT:
15 | P a g e
QUESTION 7
Write a program to accept the numbers M and N from the user and
print the smallest required number whose sum of all its digits is
equal to N. Also, print the total number of digits present in the
required number. The program should check for the validity of the
inputs and display an appropriate message for an invalid input.
ALGORITHM:
1. Begin program.
2. Prompt for two integers 'm' and 'n'.
3. Read 'm' and 'n'.
4. If 'm' < 100, 'm' > 10000, 'n' < 1, or 'n' >= 100, display
"Invalid Input" and end.
5. Create Scanner 'in'.
6. Initialize 'number' and 'count' to -1 and 0.
7. Use for loop 'i' from 'm' + 1:
a. Initialize 'sum' to 0, 'count' to 0.
b. While 'i' > 0:
i. Add last digit of 'i' to 'sum'.
ii. Remove last digit from 'i', increment 'count'.
c. If 'sum' == 'n', set 'number' to 'i' and break.
8. Check 'number':
a. If -1, show "Required number not found".
b. Else, display 'number' and 'count'.
9. End program.
JAVA CODE:
import [Link];
public class KboatNumber
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter m: ");
int m = [Link]();
[Link]("Enter n: ");
int n = [Link]();
// Check for valid input ranges
if (m < 100 || m > 10000 || n < 1 || n >= 100)
{
[Link]("Invalid Input");
return;
}
int number = -1, count = 0;
// Initialize the number to a placeholder value and digit count
for (int i = m + 1; i < Integer.MAX_VALUE; i++)
16 | P a g e
{ // Loop to find the required number
int sum = 0;
count = 0;
int t = i;
// Calculate the sum of digits and count the number of digits
while (t != 0)
{
int d = t % 10;
sum += d;
t /= 10;
count++;
}
if (sum == n) // Check if the sum of digits matches n
{
number = i; // Assign the found number
break;
}
}
// Display the result based on whether the number was found or not
if (number == -1)
{
[Link]("Required number not found");
}
else
{
[Link]("The required number = " + number);
[Link]("Total number of digits = " + count);
}
}
}
VARIABLE DESCRIPTION:
17 | P a g e
t int Temporary variable
for iterating through
digits.
OUTPUT:
18 | P a g e
QUESTION 8
ALGORITHM:
1. Begin program.
2. Prompt for two integers 'm' and 'n'.
3. Read 'm' and 'n'.
4. If 'm' ≤ 2, 'm' ≥ 10, 'n' ≤ 2, or 'n' ≥ 10, display "MATRIX SIZE
OUT OF RANGE." and end.
5. Create Scanner 'in'.
6. Create 'a' as 2D array 'm' x 'n'.
7. Prompt for matrix elements, store in 'a'.
8. Display original matrix using nested loops.
9. Sort rows using nested loops and bubble sort:
a. Sort elements of each row.
10. Display sorted matrix with nested loops.
11. End program.
JAVA CODE:
import [Link];
public class ArraySort
{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
// Input the dimensions of the matrix
[Link]("ENTER THE VALUE OF M: ");
int m = [Link]();
[Link]("ENTER THE VALUE OF N: ");
int n = [Link]();
// Check for valid matrix size range
if (m <= 2 || m >= 10 || n <= 2|| n >= 10)
{
[Link]("MATRIX SIZE OUT OF RANGE.");
return;
}
int a[][] = new int[m][n];
// Input elements of the matrix
[Link]("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++)
19 | P a g e
{
[Link]("ENTER ELEMENTS OF ROW " + (i+1) + ":");
for (int j = 0; j < n; j++)
{
a[i][j] = [Link]();
}
}
[Link]("ORIGINAL MATRIX");
// Display the original matrix
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
[Link](a[i][j] + " ");
}
[Link]();
}
// Sort the rows of the matrix using bubble sort
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n - 1; j++)
{
for (int k = 0; k < n - j - 1; k++)
{
if (a[i][k] > a[i][k + 1])
{
int t = a[i][k];
a[i][k] = a[i][k+1];
a[i][k+1] = t;
}
}
}
}
[Link]("MATRIX AFTER SORTING ROWS");
// Display the matrix after sorting rows
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
[Link](a[i][j] + " ");
}
[Link]();
}
}
}
20 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
21 | P a g e
QUESTION 9
ALGORITHM:
JAVA CODE:
import [Link];
public class Array
{ // Function to sort an array using the bubble sort algorithm
public static void sortArray(int arr[])
{
int n = [Link];
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
22 | P a g e
{
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
}
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER VALUE OF N: ");
int n = [Link]();
if (n <= 2 || n >= 10)
{
[Link]("MATRIX SIZE OUT OF RANGE");
return;
}
int a[] = new int[n];
int b[][] = new int[n][n];
[Link]("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:");
for (int i = 0; i < n; i++)
{
a[i] = [Link]();
}
sortArray(a); // Sort the array using the sortArray function
[Link]("SORTED ARRAY:");
for (int i = 0; i < n; i++)
{
[Link](a[i] + " ");
}
for (int i = n - 1, r = 0; i >= 0; i--, r++)
{
for (int j = 0; j <= i; j++)
{
b[r][j] = a[j]; // Fill the 2D matrix using sorted array values
}
for (int k = n - 1; k > i; k--)
{
b[r][k] = a[k - i - 1];
}
}
[Link]();
[Link]("FILLED MATRIX:");
// Display the filled matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
[Link](b[i][j] + " ");
}
23 | P a g e
[Link]();
}
}
}
VARIABLE DESCRIPTION:
OUTPUT:
24 | P a g e
QUESTION 10
ALGORITHM:
1. Start program.
2. Prompt for integer 'n' (participants).
3. Read 'n'.
4. If 'n' ≤ 3 or 'n' ≥ 11, display "INPUT SIZE OUT OF RANGE." and
end.
5. Create Scanner 'in'.
6. Create 2D char array 'answers'.
7. Create char array 'key'.
8. Prompt for participant answers, store in 'answers'.
9. Prompt for answer key, store in 'key'.
10. Initialize 'hScore' = 0.
11. Create int array 'score'.
12. Calculate scores:
a. Iterate participant answers, compare with 'key'.
b. Increment participant's 'score' for each correct answer.
13. Find highest score ('hScore').
14. Display participants' scores.
15. Display participant(s) with highest score ('hScore').
16. End program.
JAVA CODE:
import [Link];
public class QuizCompetition
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
// Input: Number of participants
[Link]("Enter the Number of Participants (N): ");
int n = [Link]();
// Check if the input size is within the valid range
if (n <= 3 || n >= 11)
{
[Link]("INPUT SIZE OUT OF RANGE.");
25 | P a g e
return;
}
char answers[][] = new char[n][5];
char key[] = new char[5];
[Link]("Enter answers of participants");
for (int i = 0; i < n; i++)
{
[Link]("Participant " + (i+1));
for (int j = 0; j < 5; j++)
{
answers[i][j] = [Link]().charAt(0); // Input: Participants' answers
}
}
[Link]("Enter Answer Key:");
for (int i = 0; i < 5; i++)
{
key[i] = [Link]().charAt(0); // Input: Answer Key
}
int hScore = 0; // Initialize highest score
int score[] = new int[n]; // Array to store participants' scores
[Link]("Scores:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 5; j++)
{
if (answers[i][j] == key[j])
{
score[i]++;
}
}
if (score[i] > hScore)
{
hScore = score[i];
}
[Link]("Participant " + (i+1) + " = " + score[i]);
}
// Output: Participants with the highest score
[Link]("Highest Score:");
for (int i = 0; i < n; i++)
{
if (score[i] == hScore)
{
[Link]("Participant " + (i+1));
}
}
}
}
26 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
27 | P a g e
QUESTION 11
ALGORITHM:
1. Start program.
2. Prompt for integer 'm' (matrix size).
3. Read 'm'.
4. If 'm' ≤ 3 or 'm' ≥ 10, display "THE MATRIX SIZE IS OUT OF
RANGE." and end.
5. Create Scanner 'in'.
6. Create 2D int array 'a' (size 'm' x 'm').
7. Prompt for matrix elements, store in 'a'.
8. If any element < 0, display "INVALID INPUT" and end.
9. Display original matrix using 'printMatrix'.
10. Sort non-boundary elements ascending using
'sortNonBoundaryMatrix':
a. Create 'b' (1D array) for non-boundary elements.
b. Extract non-boundary elements to 'b'.
c. Sort 'b'.
d. Replace matrix non-boundary with 'b'.
11. Display rearranged matrix using 'printMatrix'.
12. Compute and display diagonal elements and sum using
'computePrintDiagonalSum':
a. Iterate matrix elements:
i. If on main or secondary diagonal, add to 'sum'.
ii. Print element if on diagonal, else print tab.
b. Display sum of diagonal elements.
13. End program.
JAVA CODE:
import [Link];
public class MatrixSort
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER MATRIX SIZE (M): ");
int m = [Link](); // Input: Matrix size
28 | P a g e
if (m <= 3 || m >= 10)
{
[Link]("THE MATRIX SIZE IS OUT OF RANGE.");
return;
}
int a[][] = new int[m][m]; // Initialize matrix
[Link]("ENTER ELEMENTS OF MATRIX");
for (int i = 0; i < m; i++)
{
[Link]("ENTER ROW " + (i+1) + ":");
for (int j = 0; j < m; j++)
{
a[i][j] = [Link]();
if (a[i][j] < 0)
{
[Link]("INVALID INPUT");
return;
}
}
}
[Link]("ORIGINAL MATRIX");
printMatrix(a, m);
// Sort non-boundary elements of the matrix
sortNonBoundaryMatrix(a, m);
[Link]("REARRANGED MATRIX");
printMatrix(a, m);
computePrintDiagonalSum(a, m); // Calculate and print diagonal sum
}
// Sorts the non-boundary elements of the matrix
public static void sortNonBoundaryMatrix(int a[][], int m)
{
int b[] = new int[(m - 2) * (m - 2)];
int k = 0;
for (int i = 1; i < m - 1; i++)
{
for (int j = 1; j < m - 1; j++)
{
b[k++] = a[i][j];
}
}
for (int i = 0; i < k - 1; i++)
{
for (int j = 0; j < k - i - 1; j++)
{
if (b[j] > b[j + 1])
{
int t = b[j];
b[j] = b[j+1];
b[j+1] = t;
}
}
29 | P a g e
}
k = 0;
for (int i = 1; i < m - 1; i++)
{
for (int j = 1; j < m - 1; j++)
{
a[i][j] = b[k++];
}
}
}
// Computes and prints diagonal elements and their sum
public static void computePrintDiagonalSum(int a[][], int m)
{
int sum = 0;
[Link]("DIAGONAL ELEMENTS");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
if (i == j || i + j == m - 1)
{
sum += a[i][j];
[Link](a[i][j] + "\t");
}
else
{
[Link]("\t");
}
}
[Link]();
}
[Link]("SUM OF THE DIAGONAL ELEMENTS = " + sum);
}
// Prints the matrix
public static void printMatrix(int a[][], int m)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
[Link](a[i][j] + "\t");
}
[Link]();
}
}
}
30 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
31 | P a g e
QUESTION 12
ALGORITHM:
1. Begin program.
2. Prompt for integer 'm' (matrix size).
3. Read 'm'.
4. If 'm' ≤ 2 or 'm' ≥ 10, display "SIZE OUT OF RANGE" and end.
5. Create Scanner 'scan'.
6. Create 2D int array 'a' ('m' x 'm').
7. Create 1D int array 'b' ('m * m').
8. Prompt for 'm * m' numbers, store in 'a'.
9. Display original matrix using nested loops.
10. Copy 'a' to 'b' row-wise.
11. Rotate matrix elements clockwise by 90 degrees:
a. Iterate rows, fill columns from 'b' in reverse.
b. Display rotated matrix using nested loops.
12. Calculate and display sum of corner elements.
13. End program.
JAVA CODE:
import [Link].*;
class MatrixRotation
{
public static void main(String args[])
throws InputMismatchException
{
Scanner scan=new Scanner([Link]);
// Input: Number of rows for the square matrix
[Link]("Enter the number of rows (greater than 2 and
less than 10) for the square matrix : ");
int m=[Link]();
if(m<=2 || m>=10)
[Link]("SIZE OUT OF RANGE");
else
32 | P a g e
{
int a[][]=new int[m][m];
int b[] = new int[m*m];
int i,j,ctr,c;
[Link]("Enter "+(m*m)+" numbers for the matrix: ");
for(i=0;i < m;i++)
{
for(j=0;j < m;j++)
{
a[i][j] = [Link](); // Input: Matrix elements
}
}
ctr = 0;
[Link]("ORIGINAL MATRIX");
// Display original matrix and store elements in array 'b'
for(i=0;i < m;i++)
{
for(j=0;j < m;j++)
{
[Link](a[i][j] + " ");
b[ctr++] = a[i][j];
}
[Link]();
}
c = m-1;
ctr = 0;
// Rotate matrix by transferring elements
do
{
for(i=0; i < m; i++)
a[i][c] = b[ctr++];
c--;
}
while(c >= 0);
[Link]("MATRIX AFTER ROTATION");
for(i=0;i < m;i++)
{
for(j=0;j < m;j++)
{
[Link](a[i][j] + " ");
}
[Link]();
}
[Link]("Sum of the corner elements="+(a[0][0] + a[0][m-
1] + a[m-1][0] + a[m-1][m-1]));
}
}
}
33 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
34 | P a g e
QUESTION 13
ALGORITHM:
JAVA CODE:
import [Link].*;
public class StringCheck
{
public static String sortString(String ipStr)
{
StringTokenizer st = new StringTokenizer(ipStr);
int wordCount = [Link]();
String strArr[] = new String[wordCount];
// Tokenize the input sentence and store words in an array
for (int i = 0; i < wordCount; i++)
{
strArr[i] = [Link]();
}
// Sort words based on length and lexicographical order
for (int i = 0; i < wordCount - 1; i++)
{
for (int j = 0; j < wordCount - i - 1; j++)
35 | P a g e
{
if (strArr[j].length() > strArr[j + 1].length())
{
String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
}
if (strArr[j].length() == strArr[j +
1].length()&&(strArr[j].compareTo(strArr[j+1]) > 0))
{
String t = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = t;
}
}
}
// Construct the sorted string
StringBuffer sb = new StringBuffer();
for (int i = 0; i < wordCount; i++)
{
[Link](strArr[i]);
[Link](" ");
}
return [Link]().trim();
}
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter a sentence:");
String str = [Link]();
int len = [Link]();
[Link]();
// Check if the sentence ends with '.', '?', or '!'
if ([Link](len - 1) != '.'&& [Link](len - 1) != '?'&&
[Link](len - 1) != '!')
{
[Link]("INVALID INPUT");
return;
}
// Sort the sentence and print original and sorted versions
String sortedStr = sortString([Link](0, len - 1));
[Link](str);
[Link](sortedStr);
}
}
36 | P a g e
VARIABLE DESCRIPTION
OUTPUT:
37 | P a g e
QUESTION 14
ALGORITHM:
JAVA CODE:
import [Link].*;
public class Palindrome
{
// Function to check if a given string is a palindrome
public static boolean isPalindrome(String word)
{
boolean palin = true;
int len = [Link]();
for (int i = 0; i <= len / 2; i++)
{
// Compare characters from both ends of the word
if ([Link](i) != [Link](len - 1 - i))
{
palin = false;
// If characters don't match, word is not a palindrome
break;
}
}
38 | P a g e
return palin;
}
// Function to make a palindrome by appending characters
public static String makePalindrome(String word)
{
int len = [Link]();
char lastChar = [Link](len - 1);
int i = len - 1;
while ([Link](i) == lastChar)
{
i--;
}
StringBuffer sb = new StringBuffer(word);
for (int j = i; j >= 0; j--)
{
[Link]([Link](j)); // Append characters in reverse order
}
return [Link]();
}
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER THE SENTENCE:");
String ipStr = [Link]().trim().toUpperCase();
int len = [Link]();
char lastChar = [Link](len - 1);
// Check if the input ends with '.', '?', or '!'
if (lastChar != '.'&& lastChar != '?'&& lastChar != '!')
{
[Link]("INVALID INPUT");
return;
}
String str = [Link](0, len - 1);
StringTokenizer st = new StringTokenizer(str);
StringBuffer sb = new StringBuffer();
/* Tokenize input, check for palindromes, and construct the
converted string
*/
while ([Link]())
{
String word = [Link]();
boolean isPalinWord = isPalindrome(word);
if (isPalinWord)
{
[Link](word); // If the word is a palindrome, keep it as it is
}
else
{
String palinWord = makePalindrome(word);
// Otherwise, make it a palindrome
[Link](palinWord);
39 | P a g e
}
[Link](" "); // Add a space between words
}
String convertedStr = [Link]().trim();
[Link]();
[Link](ipStr);
[Link](convertedStr);
}
}
VARIABLE DESCRIPTION:
40 | P a g e
by reversing it.
convertedStr String The final converted
sentence with
palindromes or
palindrome versions
of words.
OUTPUT:
41 | P a g e
QUESTION – 15
ALGORITHM:
JAVA CODE:
import [Link];
public class Banner
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER THE VALUE OF N: ");
int n = [Link](); // Input: Value of N
[Link](); // Consume the newline character
// Check if N is within the valid range
if (n <= 2 || n >= 9)
{
[Link]("INVALID INPUT");
return;
}
String teams[] = new String[n];
int highLen = 0;
// Input: Team names and find the highest length
for (int i = 0; i < n; i++)
{
[Link]("Team " + (i+1) + ": ");
teams[i] = [Link]();
if (teams[i].length() > highLen)
42 | P a g e
{
highLen = teams[i].length();
}
}
// Print the banner
for (int i = 0; i < highLen; i++)
{
for (int j = 0; j < n; j++)
{
int len = teams[j].length();
if (i >= len)
{
[Link](" \t"); // Print spaces if the team name is shorter
}
else
{
[Link](teams[j].charAt(i) + "\t");
// Print the character at position i
}
}
[Link]();
// Move to the next line after printing each row
}
}
}
VARIABLE DESCRIPTION:
Variable Data Type Description
n int An integer representing
the number of teams
entered by the user.
in Scanner An instance of the
Scanner class used to
read input from the
user.
teams String[] An array of strings to
store the names of the
teams.
highLen int An integer representing
the length of the
longest team name.
i, j int Integer variables used
as iterators in loop
iterations.
len int An integer representing
the length of a team
name in the array.
43 | P a g e
OUTPUT:
44 | P a g e
QUESTION – 16
ALGORITHM:
JAVA CODE:
import [Link].*;
public class VowelWord
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("ENTER THE SENTENCE:"); // Input: Sentence
String ipStr = [Link]().trim().toUpperCase();
int len = [Link]();
char lastChar = [Link](len - 1);
// Check if the sentence ends with '.', '?', or '!'
if (lastChar != '.'&& lastChar != '?'&& lastChar != '!')
{
[Link]("INVALID INPUT");
return;
45 | P a g e
}
String str = [Link](0, len - 1);
StringTokenizer st = new StringTokenizer(str);
StringBuffer sbVowel = new StringBuffer();
StringBuffer sb = new StringBuffer();
int c = 0;
while ([Link]())
{
String word = [Link]();
int wordLen = [Link]();
if (isVowel([Link](0))&& isVowel([Link](wordLen - 1)))
{
c++; // Increment the count
[Link](word);
[Link](" ");
}
else
{
[Link](word);
[Link](" ");
}
}
String newStr = [Link]() + [Link]();
[Link]("NUMBER OF WORDS BEGINNING AND ENDING WITH A
VOWEL = " + c);
[Link](newStr);
}
// Function to check if a character is a vowel
public static boolean isVowel(char ch)
{
ch = [Link](ch);
boolean ret = false;
if (ch == 'A'|| ch == 'E'|| ch == 'I'|| ch == 'O'|| ch == 'U')
ret = true;
return ret;
}
}
VARIABLE DESCRIPTION:
Variable Data Type Description
in Scanner An instance of the
Scanner class used to
read input from the
user.
ipStr String The input sentence
provided by the user,
trimmed and converted
to uppercase.
len int The length of the input
sentence.
46 | P a g e
lastChar char The last character of
the input sentence.
str String The modified sentence
after removing the last
punctuation character.
st StringTokenizer A class used to
tokenize the modified
sentence into words.
sbVowel StringBuffer A mutable string buffer
to store words
beginning and ending
with vowels.
sb StringBuffer A mutable string buffer
to store words not
meeting the vowel
conditions.
c int A counter to track the
number of words
starting and ending
with vowels.
word String The current word
extracted from the
tokens during
iteration.
wordLen int The length of the
current word.
newStr String The final rearranged
sentence combining
words as per vowel
conditions.
ch char The character being
checked for vowel
status within the
isVowel function.
OUTPUT:
47 | P a g e
QUESTION – 17
ALGORITHM:
JAVA CODE:
import [Link].*;
class StringCheck2
{
public static void main(String arg[])throws IOException
{
int i, j, vowels, cons, p, l;
String str,word, tmp;
char ch, ch1;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter a paragraph : ");
str=[Link]();
l = [Link]();
ch = [Link](l-1);
[Link]("\nOUTPUT:");
48 | P a g e
// Check if the input ends with '.', '?', or '!'
if(ch != '.' && ch != '?')
[Link]("INVALID INPUT");
else
{
p = vowels = cons = 0;
tmp = str+" ";
str = "";
/* Tokenize the input paragraph into words and capitalize the first
letter of each word
*/
for(i=0;i < [Link]();i++)
{
ch = [Link](i);
if(ch == ' ')
{
word = [Link](p,i);
ch1 = [Link](0);
word = [Link](ch1)+[Link](1);
str+= word+" ";
p = i + 1;
}
}
[Link]("\n"+str);
[Link]("\nWord");
// Print formatting
for(j= 15 - 4; j>=1;j--)
[Link](" ");
[Link]("\tVowels\tConsonants");
p=0;
for(i=0;i < l;i++)
{
ch = [Link](i);
if( ch != ' ' && ch != '.' && ch != '?')
{
if((ch>=65 && ch <= 90) || (ch>=97 && ch<=122))
{ // Count vowels and consonants
if("aeiouAEIOU".indexOf(ch) != -1)
vowels++;
else
cons++;
}
}
else
{
word = [Link](p,i);
[Link](word);
// Print formatting
for(j= 15 - [Link](); j>=1;j--)
[Link](" ");
[Link]("\t "+vowels+"\t "+cons);
49 | P a g e
p = i + 1;
vowels = cons = 0;
}
}
}
}
}
VARIABLE DESCRIPTION:
OUTPUT:
50 | P a g e
QUESTION – 18
ALGORITHM:
JAVA CODE:
import [Link].*;
class SentenceManipulation
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
// Input: Sentence
[Link]("Enter a sentence (terminated by '.', '?', or
'!'): ");
String inputSentence = [Link]().trim(); // Trim whitespace
char lastChar = [Link]([Link]() - 1);
// Check if the sentence ends with '.', '?', or '!'
if (lastChar != '.' && lastChar != '?' && lastChar != '!')
{
[Link]("INVALID INPUT.");
return;
}
51 | P a g e
// Process: Remove extra spaces from the sentence
String sentence = reduceSpaces(inputSentence);
// Input: Word to delete and its position
[Link]("Enter a word to delete: ");
String wordToDelete = [Link]().trim();
[Link]("Enter the position number of the word: ");
int wordPosition = [Link]([Link]());
// Process: Delete word and get updated sentence
String updatedSentence = deleteWord(sentence, wordToDelete,
wordPosition);
// Output: Display the updated sentence
[Link]("OUTPUT: " + updatedSentence);
}
// Function to remove extra spaces from a sentence
public static String reduceSpaces(String input)
{
return [Link]("\\s+", " ");
}
// Function to delete a word from a sentence at a specific position
public static String deleteWord(String sentence, String
wordToDelete, int position) {
String[] words = [Link]("\\s+");
StringBuilder updatedSentence = new StringBuilder();
int count = 0;
for (String word : words)
{
if ( || count != position - 1)
{
[Link](word).append(" ");
}
else
{
count++;
}
count++;
}
// If the sentence is empty after deletion, return an empty string
if ([Link]() == 0)
{
return "";
}
return [Link]().trim();
}
}
52 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
53 | P a g e
QUESTION – 19
ALGORITHM:
JAVA CODE:
import [Link];
class DateValidation
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter your date of birth in dd mm yyyy
format");
int day = [Link]();
int month = [Link]();
int year = [Link]();
boolean isValid = true;
// Array to store the maximum number of days for each month
int[] maxDays = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
if (year > 0 && month >= 1 && month <= 12)
{
// Check for leap year and update February's max days
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
maxDays[2] = 29;
}
if (day >= 1 && day <= maxDays[month])
54 | P a g e
{
int dayNumber = calculateDayNumber(day, month, maxDays);
[Link]("VALID DATE");
[Link](dayNumber); // Output day number in the year
}
else
{
isValid = false;
}
}
else
{
isValid = false;
}
if (!isValid)
{
[Link]("INVALID DATE");
}
}
// Function to calculate the day number in the year
public static int calculateDayNumber(int day, int month, int[]
maxDays)
{
int dayNumber = day;
for (int i = 1; i < month; i++)
{
dayNumber += maxDays[i];
}
return dayNumber;
}
}
VARIABLE DESCRIPTION:
55 | P a g e
number of the year.
i int Loop iterator
variable.
OUTPUT:
56 | P a g e
QUESTION – 20
Design a program to accept a day number (between 1 and 366), year
(in 4 digits) from the user to generate and display the
corresponding date. Also, accept 'N' (1 <= N <= 100) from the user
to compute and display the future date corresponding to 'N' days
after the generated date. Display an error message if the value of
the day number, year and N are not within the limit or not
according to the condition specified.
ALGORITHM:
1. Define Functions:
- `isLeapYear(year)`: Check if `year` is a leap year.
- `getMonthDay(year, dayNumber)`: Calculate `month` and `day`
from `dayNumber`.
- `getMonthName(month)`: Get name of a `month` based on `month`
number.
- `formatDateString(month, day, year)`: Format a date string.
- `calculateFutureDate(year, month, day, nDays)`: Calculate
future date.
2. Main Program:
- Initialize a Scanner for input.
- Input `dayNumber`, `year`, and `nDays`.
- Validate input ranges.
- Get `month` and `day` using `getMonthDay`.
- Print formatted date for `dayNumber`.
- Calculate and print future date using `calculateFutureDate`.
3. Functions Description:
- `isLeapYear(year)`: Check if `year` is a leap year.
- `getMonthDay(year, dayNumber)`: Calculate `month` and `day`.
- `getMonthName(month)`: Get name of a `month`.
- `formatDateString(month, day, year)`: Format a date string.
- `calculateFutureDate(year, month, day, nDays)`: Calculate
future date.
JAVA CODE:
import [Link];
public class DateCalculator
{
public static boolean isLeapYear(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static int[] getMonthDay(int year, int dayNumber)
{
// Array to store the number of days in each month
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
if (isLeapYear(year))
57 | P a g e
{
daysInMonth[2] = 29; // February has 29 days in a leap year
}
int month = 1;
while (dayNumber > daysInMonth[month])
{
dayNumber -= daysInMonth[month];
month++;
}
int[] result = {month, dayNumber};
return result;
}
public static String getMonthName(int month)
{
// Array to store the names of the months
String[] monthNames = {"", "JANUARY", "FEBRUARY", "MARCH", "APRIL",
"MAY", "JUNE" , "JULY", "AUGUST", "SEPTEMBER", "OCTOBER",
"NOVEMBER", "DECEMBER"};
return monthNames[month];
}
public static String formatDateString(int month, int day, int year)
{
// Determine the appropriate suffix for the day
String suffix = "TH";
if (day == 1 || day == 21 || day == 31)
{
suffix = "ST";
}
else if (day == 2 || day == 22)
{
suffix = "ND";
}
else if (day == 3 || day == 23)
{
suffix = "RD";
}
return day + suffix + " " + getMonthName(month) + ", " + year;
}
public static int[] calculateFutureDate(int year, int month, int
day, int nDays)
{
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
if (isLeapYear(year))
{
daysInMonth[2] = 29;
}
day += nDays;
while (day > daysInMonth[month])
{
day -= daysInMonth[month];
58 | P a g e
month++;
if (month > 12)
{
month = 1;
year++;
}
}
int[] result = {year, month, day};
return result;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
try
{
[Link]("DAY NUMBER: ");
int dayNumber = [Link]();
[Link]("YEAR: ");
int year = [Link]();
[Link]("DATE AFTER (N DAYS): ");
int nDays = [Link]();
// Validation checks
if (dayNumber < 1 || dayNumber > 366)
{
[Link]("DAY NUMBER OUT OF RANGE");
return;
}
if (year < 1000 || year > 9999)
{
[Link]("INVALID YEAR");
return;
}
if (nDays < 1 || nDays > 100)
{
[Link]("DATE AFTER (N DAYS) OUT OF RANGE");
return;
}
// Get the month and day corresponding to the given day number
int[] monthDay = getMonthDay(year, dayNumber);
int month = monthDay[0];
int day = monthDay[1];
[Link]("DATE: " + formatDateString(month, day, year));
// Calculate the future date and display it
int[] futureDate = calculateFutureDate(year, month, day, nDays);
int futureYear = futureDate[0];
int futureMonth = futureDate[1];
int futureDay = futureDate[2];
[Link]("DATE AFTER " + nDays + " DAYS: " +
formatDateString(futureMonth, futureDay, futureYear));
}
catch (Exception e)
59 | P a g e
{
[Link]("Invalid input. Please enter valid numeric
values.");
}
finally
{
[Link]();
}
}
}
VARIABLE DESCRIPTION:
OUTPUT:
60 | P a g e
QUESTION – 21
ALGORITHM:
JAVA CODE:
import [Link];
class DateGenerator
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
// Input: Day Number, Year, and Number of Days
[Link]("DAY NUMBER: ");
int dayNumber = [Link]();
[Link]("YEAR: ");
int year = [Link]();
[Link]("DATE AFTER (N DAYS): ");
int nDays = [Link]();
// Validate input ranges
if (dayNumber < 1 || dayNumber > 366)
{
[Link]("DAY NUMBER OUT OF RANGE");
}
else if (year < 1000 || year > 9999)
{
[Link]("INVALID YEAR FORMAT");
} else if (nDays < 1 || nDays > 100)
{
[Link]("DATE AFTER (N DAYS) OUT OF RANGE");
}
else
61 | P a g e
{
int[] maxDays = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31};
int month = 1;
// Calculate month and day within month
while (dayNumber > maxDays[month])
{
dayNumber -= maxDays[month];
month++;
}
// Check for leap year
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year %
400 == 0;
if (isLeapYear)
{
maxDays[2] = 29;
}
int futureDayNumber = dayNumber + nDays;
// Calculate future date
while (futureDayNumber > maxDays[month])
{
futureDayNumber -= maxDays[month];
month++;
if (month > 12)
{
month = 1;
year++;
isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
if (isLeapYear)
{
maxDays[2] = 29;
}
else
{
maxDays[2] = 28;
}
}
}
// Get month name and day suffix
String monthName = getMonthName(month);
String date = dayNumber + getDaySuffix(dayNumber) + " " + monthName
+ ", " + year;
String futureDate = futureDayNumber + getDaySuffix(futureDayNumber)
+ " " + monthName + ", " + year;
// Output: Display dates
[Link]("DATE: " + date);
[Link]("DATE AFTER " + nDays + " DAYS: " + futureDate);
}
}
// Function to get month name
public static String getMonthName(int month)
62 | P a g e
{
String[] monthNames = {"", "JANUARY", "FEBRUARY", "MARCH", "APRIL",
"MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER",
"NOVEMBER", "DECEMBER"};
return monthNames[month];
}
// Function to get day suffix
public static String getDaySuffix(int day)
{
if (day >= 11 && day <= 13)
{
return "TH";
}
switch (day % 10)
{
case 1: return "ST";
case 2: return "ND";
case 3: return "RD";
default: return "TH";
}
}
}
VARIABLE DESCRIPTION:
63 | P a g e
days.
monthNames String[] An array containing
month names.
daySuffix String The suffix for the
day (e.g., "ST",
"ND", "RD", "TH").
OUTPUT:
64 | P a g e
QUESTION – 22
ALGORITHM:
1. StackArray Class:
- Private vars: `maxSize`, `top` (-1), `stackArray` (int array).
- Constructor `StackArray(size)`: Init `maxSize`, `stackArray`
(size), set `top` (-1).
- Method `push(data)`: If `isFull()`, print error. Else,
increment `top`, assign `data` to `stackArray[top]`.
- Method `pop()`: If `isEmpty()`, print error, return -1. Else,
decrement `top`, return `stackArray[top]`.
- Method `isEmpty()`: Return top == -1.
- Method `isFull()`: Return top == maxSize - 1.
- Method `display()`: If `isEmpty()`, print "Empty." Else,
iterate `stackArray`, print elements.
2. StackArrayDemo Class:
- Create Scanner.
- Read stack size.
- Create `stack` instance.
- Loop for menu:
- Display Push, Pop, Display, Exit options.
- Read user choice.
- Switch-case for actions:
- Push: Read data, call `[Link](data)`.
- Pop: Call `[Link]()`.
- Display: Call `[Link]()`.
- Exit: Print "Exiting...", close scanner.
- Default: Print "Invalid".
JAVA CODE:
import [Link];
class StackArray
{
private int maxSize; // Maximum size of the stack
private int top; // Index of the top element
private int[] stackArray; // Array to store the stack elements
public StackArray(int size)
{
maxSize = size;
top = -1; // Initialize top to -1 to indicate an empty stack
stackArray = new int[maxSize];
}
public void push(int data)
{
if (isFull())
65 | P a g e
{
[Link]("Stack is full. Cannot push.");
return;
}
stackArray[++top] = data;
// Increment top and add data to the top of the stack
[Link]("Pushed " + data + " onto the stack.");
}
public int pop()
{
if (isEmpty())
{
[Link]("Stack is empty. Cannot pop.");
return -1;
}
int popped = stackArray[top--]; // Remove and return the top element
[Link]("Popped " + popped + " from the stack.");
return popped;
}
public boolean isEmpty()
{
return top == -1; // Check if the stack is empty
}
public boolean isFull()
{
return top == maxSize - 1; // Check if the stack is full
}
public void display()
{
if (isEmpty())
{
[Link]("Stack is empty.");
return;
}
[Link]("Stack: ");
for (int i = 0; i <= top; i++)
{
[Link](stackArray[i] + " ");
}
[Link]();
}
}
public class StackArrayDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the stack: ");
int size = [Link]();
StackArray stack = new StackArray(size);
while (true)
66 | P a g e
{
[Link]("\nMenu:");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter data to push onto the stack: ");
int data = [Link]();
[Link](data);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice. Please enter a valid choice.");
}
}
}
}
VARIABLE DESCRIPTION:
67 | P a g e
stack StackArray Instance of the
StackArray class to
manage the stack.
OUTPUT:
68 | P a g e
QUESTION – 23
ALGORITHM:
1. Node Class:
- Define a `Node` struct with `data` (int) and `next` (Node
reference).
2. StackLinkedList Class:
- Private `top` (Node).
- Constructor `StackLinkedList()`: Initialize `top` as null.
- Method `push(data)`: Create and set `[Link]` to current
`top`, update `top` to `newNode`, print push message.
- Method `pop()`: If `isEmpty()`, print error, return -1. Get
and update `top`, print pop message, return data.
- Method `isEmpty()`: Return true if `top` is null.
- Method `display()`: Print empty message if `isEmpty()`.
Traverse stack, print elements.
3. StackLinkedListDemo Class:
- Create Scanner.
- Create `stack` instance.
- Loop for menu options:
- Read user choice.
- Switch-case:
- Push: Read data, call `[Link](data)`.
- Pop: Call `[Link]()`, display popped element.
- Display: Call `[Link]()`.
- Exit: Print "Exiting...", close scanner.
- Default: Print "Invalid".
JAVA CODE:
import [Link];
// Node class to represent individual elements in the linked list
class Node
{
int data;
Node next;
public Node(int data)
{
[Link] = data;
[Link] = null;
}
}
// Stack implementation using linked list
class StackLinkedList
{
private Node top; // Reference to the top element of the stack
public StackLinkedList()
69 | P a g e
{
top = null; // Initialize the stack as empty
}
public void push(int data)
{
Node newNode = new Node(data);
[Link] = top;
top = newNode;
[Link]("Pushed " + data + " onto the stack.");
}
public int pop()
{
if (isEmpty())
{
[Link]("Stack is empty. Cannot pop.");
return -1;
}
int popped = [Link];
top = [Link];
[Link]("Popped " + popped + " from the stack.");
return popped;
}
public boolean isEmpty()
{
return top == null;
}
public void display()
{
if (isEmpty())
{
[Link]("Stack is empty.");
return;
}
[Link]("Stack: ");
Node current = top;
while (current != null)
{
[Link]([Link] + " ");
current = [Link];
}
[Link]();
}
}
public class StackLinkedListDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
StackLinkedList stack = new StackLinkedList();
while (true)
{
70 | P a g e
[Link]("\nMenu:");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter data to push onto the stack: ");
int data = [Link]();
[Link](data);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice. Please enter a valid choice.");
}
}
}
}
VARIABLE DESCRIPTION:
71 | P a g e
list.
OUTPUT:
72 | P a g e
QUESTION – 24
ALGORITHM:
1. QueueArray Class:
- Private `maxSize`, `front`, `rear`, and integer array
`queueArray`.
- Constructor `QueueArray(size)`: Initialize attributes.
- Method `enqueue(data)`: If `isFull()`, print error, else
increment `rear` and assign data.
- Method `dequeue()`: If `isEmpty()`, print error, else store
data at `front`, increment `front`, return data.
- Method `isEmpty()`: Return `front` equals `rear`.
- Method `isFull()`: Return `rear` one less than `front`.
- Method `display()`: If `isEmpty()`, print empty, else iterate,
print each element.
2. QueueArrayDemo Class:
- Create Scanner.
- Read queue size.
- Create `queue` instance.
- Loop for menu options:
- Read user choice.
- Switch-case:
- Enqueue: Read data, call `[Link](data)`.
- Dequeue: Call `[Link]()`, display dequeued element.
- Display: Call `[Link]()`.
- Exit: Print "Exiting...", close scanner.
- Default: Print "Invalid".
JAVA CODE:
import [Link];
// Implementation of Queue using circular array
class QueueArray
{
private int maxSize;
private int front;
private int rear;
private int[] queueArray;
public QueueArray(int size)
{
maxSize = size;
front = 0;
rear = -1;
queueArray = new int[maxSize];
}
// Enqueue operation: Add an element to the rear of the queue
public void enqueue(int data)
73 | P a g e
{
if (isFull())
{
[Link]("Queue is full. Cannot enqueue.");
return;
}
rear = (rear + 1) % maxSize; // Circular increment
queueArray[rear] = data;
[Link]("Enqueued " + data + " into the queue.");
}
// Dequeue operation: Remove an element from the front of the queue
public int dequeue()
{
if (isEmpty())
{
[Link]("Queue is empty. Cannot dequeue.");
return -1;
}
int dequeued = queueArray[front];
front = (front + 1) % maxSize; // Circular increment
[Link]("Dequeued " + dequeued + " from the queue.");
return dequeued;
}
public boolean isEmpty() // Check if the queue is empty
{
return front == (rear + 1) % maxSize;
}
public boolean isFull() // Check if the queue is full
{
return rear == (front + maxSize - 1) % maxSize;
}
public void display() // Display the elements in the queue
{
if (isEmpty())
{
[Link]("Queue is empty.");
return;
}
[Link]("Queue: ");
int index = front;
while (index != rear)
{
[Link](queueArray[index] + " ");
index = (index + 1) % maxSize; // Circular increment
}
[Link](queueArray[rear] + " ");
[Link]();
}
}
public class QueueArrayDemo
{
74 | P a g e
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the queue: ");
int size = [Link]();
QueueArray queue = new QueueArray(size);
while (true)
{
[Link]("\nMenu:");
[Link]("1. Enqueue");
[Link]("2. Dequeue");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter data to enqueue into the queue: ");
int data = [Link]();
[Link](data);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice. Please enter a valid choice.");
}
}
}
}
VARIABLE DESCRIPTION:
75 | P a g e
queue.
front int Index of the front
element in the queue.
rear int Index of the rear
element in the queue.
queueArray int[] An array to store the
elements of the
queue.
OUTPUT:
76 | P a g e
QUESTION – 25
ALGORITHM:
1. QueueArray Class:
- Private `maxSize`, `front`, `rear`, and an integer array
`queueArray`.
- Constructor `QueueArray(size)`: Initialize attributes.
- Method `enqueue(data)`: Enqueue element if not full, else
print error.
- Method `dequeue()`: Dequeue element if not empty, else print
error and return -1.
- Method `isEmpty()`: Return `front` equals `rear`.
- Method `isFull()`: Return `rear` one less than `front`.
- Method `display()`: Print "empty" or iterate to print
elements.
2. QueueArrayDemo Class:
- Create Scanner.
- Read queue size.
- Create `queue` instance.
- Loop for menu options:
- Read user choice.
- Switch-case:
- Enqueue: Read data, call `[Link](data)`.
- Dequeue: Call `[Link]()`, display dequeued element.
- Display: Call `[Link]()`.
- Exit: Print "Exiting...", close scanner.
- Default: Print "Invalid".
JAVA CODE:
import [Link];
class Node
{
int data;
Node next;
public Node(int data)
{
[Link] = data;
[Link] = null;
}
}
// Implementation of Queue using Linked List
class QueueLinkedList
{
private Node front;
private Node rear;
public QueueLinkedList()
77 | P a g e
{
front = null;
rear = null;
}
// Enqueue operation: Add an element to the rear of the queue
public void enqueue(int data)
{
Node newNode = new Node(data);
if (isEmpty())
{
front = newNode;
rear = newNode;
}
else
{
[Link] = newNode;
rear = newNode;
}
[Link]("Enqueued " + data + " into the queue.");
}
// Dequeue operation: Remove an element from the front of the queue
public int dequeue()
{
if (isEmpty())
{
[Link]("Queue is empty. Cannot dequeue.");
return -1;
}
int dequeued = [Link];
front = [Link];
if (front == null)
{
rear = null;
}
[Link]("Dequeued " + dequeued + " from the queue.");
return dequeued;
}
// Check if the queue is empty
public boolean isEmpty()
{
return front == null;
}
// Display the elements in the queue
public void display()
{
if (isEmpty())
{
[Link]("Queue is empty.");
return;
}
[Link]("Queue: ");
78 | P a g e
Node current = front;
while (current != null)
{
[Link]([Link] + " ");
current = [Link];
}
[Link]();
}
}
public class QueueLinkedListDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
QueueLinkedList queue = new QueueLinkedList();
while (true)
{
[Link]("\nMenu:");
[Link]("1. Enqueue");
[Link]("2. Dequeue");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter data to enqueue into the queue: ");
int data = [Link]();
[Link](data);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice. Please enter a valid choice.");
}
}
}
}
79 | P a g e
VARIABLE DESCRIPTION:
OUTPUT:
80 | P a g e
QUESTION – 26
ALGORITHM:
1. Class CircularQueueArray:
• Initialize maxSize, front, rear, and queueArray.
• Constructor CircularQueueArray(size).
• Method enqueue(data) for adding elements.
• Method dequeue() for removing elements.
• Methods isEmpty() and isFull() for status.
• Method display() for showing contents.
2. Class CircularQueueArrayDemo:
• Scanner for user input.
• Instance of CircularQueueArray called queue.
• Menu loop for Enqueue, Dequeue, Display, Exit.
• Switch-case for operations: Enqueue, Dequeue, Display, Exit.
JAVA CODE:
import [Link];
// Circular Queue implemented using an array
class CircularQueueArray
{
private int maxSize;
private int front;
private int rear;
private int[] queueArray;
public CircularQueueArray(int size)
{
maxSize = size;
front = -1;
rear = -1;
queueArray = new int[maxSize];
}
81 | P a g e
[Link]("Enqueued " + data + " into the circular
queue.");
}
public int dequeue()
{
if (isEmpty())
{
[Link]("Queue is empty. Cannot dequeue.");
return -1;
}
int dequeued = queueArray[front];
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
front = (front + 1) % maxSize;
}
[Link]("Dequeued " + dequeued + " from the circular
queue.");
return dequeued;
}
public boolean isEmpty() // Check if the circular queue is empty
{
return front == -1 && rear == -1;
}
public boolean isFull() // Check if the circular queue is full
{
return (rear + 1) % maxSize == front;
}
public void display() // Display the elements in the circular queue
{
if (isEmpty())
{
[Link]("Circular queue is empty.");
return;
}
[Link]("Circular Queue: ");
int i = front;
while (true)
{
[Link](queueArray[i] + " ");
if (i == rear)
{
break;
}
i = (i + 1) % maxSize;
}
[Link]();
82 | P a g e
}
}
public class CircularQueueArrayDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the circular queue: ");
int size = [Link]();
CircularQueueArray queue = new CircularQueueArray(size);
while (true)
{
[Link]("\nMenu:");
[Link]("1. Enqueue");
[Link]("2. Dequeue");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter data to enqueue into the circular queue:
");
int data = [Link]();
[Link](data);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice. Please enter a valid choice.");
}
}
}
}
VARIABLE DESCRIPTION:
OUTPUT:
84 | P a g e
QUESTION – 27
ALGORITHM:
1. Class DequeueArray:
• Init: maxSize, front, rear, dequeueArray.
• Constructor DequeueArray(size).
• enqueueFront(data) method for adding front.
• enqueueRear(data) method for adding rear.
• dequeueFront() method for removing front.
• dequeueRear() method for removing rear.
• isEmpty() and isFull() methods for status.
• display() method for showing contents.
2. Class DequeueArrayDemo:
• Scanner for user input.
• Instance of DequeueArray called dequeue.
• Menu loop: EnqueueFront, EnqueueRear, DequeueFront,
DequeueRear, Display, Exit.
• Switch-case: EnqueueFront, EnqueueRear, DequeueFront,
DequeueRear, Display, Exit.
JAVA CODE:
import [Link];
// Dequeue implemented using an array
class DequeueArray
{
private int maxSize;
private int front;
private int rear;
private int[] dequeueArray;
public DequeueArray(int size)
{
maxSize = size;
front = -1;
rear = -1;
dequeueArray = new int[maxSize];
}
public void insertFront(int data)
{ // Insert an element at the front of the dequeue
if (isFull())
{
[Link]("Dequeue is full. Cannot insert front.");
return;
}
if (isEmpty())
{
front = 0;
85 | P a g e
rear = 0;
}
else if (front == 0)
{
front = maxSize - 1;
}
else
{
front--;
}
dequeueArray[front] = data;
[Link]("Inserted " + data + " at the front of the
dequeue.");
}
public void insertRear(int data)
{ // Insert an element at the rear of the dequeue
if (isFull())
{
[Link]("Dequeue is full. Cannot insert rear.");
return;
}
if (isEmpty())
{
front = 0;
rear = 0;
}
else if (rear == maxSize - 1)
{
rear = 0;
}
else
{
rear++;
}
dequeueArray[rear] = data;
[Link]("Inserted " + data + " at the rear of the
dequeue.");
}
public void deleteFront()
{ // Delete an element from the front of the dequeue
if (isEmpty())
{
[Link]("Dequeue is empty. Cannot delete front.");
return;
}
[Link]("Deleted " + dequeueArray[front] + " from the
front of the dequeue.");
if (front == rear)
{
front = -1;
rear = -1;
86 | P a g e
}
else if (front == maxSize - 1)
{
front = 0;
}
else
{
front++;
}
}
public void deleteRear()
{ // Delete an element from the rear of the dequeue
if (isEmpty())
{
[Link]("Dequeue is empty. Cannot delete rear.");
return;
}
[Link]("Deleted " + dequeueArray[rear] + " from the
rear of the dequeue.");
if (front == rear)
{
front = -1;
rear = -1;
}
else if (rear == 0)
{
rear = maxSize - 1;
}
else
{
rear--;
}
}
public boolean isEmpty() // Check if the dequeue is empty
{
return front == -1;
}
public boolean isFull() // Check if the dequeue is full
{
return (front == 0 && rear == maxSize - 1) || (rear == front - 1);
}
public void display() // Display the elements in the dequeue
{
if (isEmpty())
{
[Link]("Dequeue is empty.");
return;
}
[Link]("Dequeue: ");
int i = front;
while (true)
87 | P a g e
{
[Link](dequeueArray[i] + " ");
if (i == rear)
{
break;
}
if (i == maxSize - 1)
{
i = 0;
}
else
{
i++;
}
}
[Link]();
}
}
public class DequeueArrayDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the dequeue: ");
int size = [Link]();
DequeueArray dequeue = new DequeueArray(size);
while (true)
{
[Link]("\nMenu:");
[Link]("1. Insert Front");
[Link]("2. Insert Rear");
[Link]("3. Delete Front");
[Link]("4. Delete Rear");
[Link]("5. Display");
[Link]("6. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter data to insert at front: ");
int frontData = [Link]();
[Link](frontData);
break;
case 2:
[Link]("Enter data to insert at rear: ");
int rearData = [Link]();
[Link](rearData);
break;
case 3:
[Link]();
88 | P a g e
break;
case 4:
[Link]();
break;
case 5:
[Link]();
break;
case 6:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice. Please enter a valid choice.");
}
}
}
}
VARIABLE DESCRIPTION:
OUTPUT:
89 | P a g e