0% found this document useful (0 votes)
8 views89 pages

Java Programs for ISBN and Prime Checks

The document contains multiple Java programming tasks including validating ISBN codes, checking for circular primes, finding prime pairs, identifying Prime-Adam integers, calculating factorial using recursion, and converting decimal to binary using recursion. Each task includes an algorithm, Java code implementation, and variable descriptions. The document serves as a comprehensive guide for implementing these algorithms in Java.

Uploaded by

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

Java Programs for ISBN and Prime Checks

The document contains multiple Java programming tasks including validating ISBN codes, checking for circular primes, finding prime pairs, identifying Prime-Adam integers, calculating factorial using recursion, and converting decimal to binary using recursion. Each task includes an algorithm, Java code implementation, and variable descriptions. The document serves as a comprehensive guide for implementing these algorithms in Java.

Uploaded by

Amrita Biswas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

QUESTION 1

Write a program in Java to accept a ten digit code from the user
and check if the code is a valid ISBN.

ALGORITHM:

1. Begin by prompting the user for an ISBN code.


2. Read and store the ISBN code.
3. If the code length is not 10, display "INVALID INPUT" and
terminate.
4. Initialize 's' and 'ctr' to 0 for weighted sum calculation.
5. Iterate through each digit:
a. If digit is 'X', set 't' to 10.
b. Otherwise, convert digit to integer 't'.
c. Add 't' multiplied by 'ctr' to 's'.
d. Decrement 'ctr'.
6. Check if 's' is divisible by 11:
a. If divisible, display sum and "LEAVES NO REMAINDER - VALID
ISBN CODE."
b. If not divisible, display sum and "LEAVES REMAINDER - INVALID
ISBN CODE."
7. End the program.

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

Write a program in Java to accept a positive number N and check


whether it is a circular prime or not. The new numbers formed after
the shifting of the digits should also be displayed.

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:

Variable Data Type Description


in Scanner Used to read input
from the user.
n int Stores the input
integer 'n' to check
for circular prime.
isCircularPrime boolean Keeps track of
whether 'n' is a
circular prime or
not.
c int Counter used to count
divisors during
primality check.
i int Used as a loop
iteration variable.
num int Used to represent the
current number during
iteration.
digitCount int Stores the number of
digits in 'n'.
divisor int Used to calculate the
divisor for circular
rotation.
t1, t2 int Temporary variables
used for digit
extraction.
n2 int Stores a copy of 'n'
for circular
rotation.

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:

Variable Data Type Description


n int Input integer 'n' to
find prime pairs.
a int Used to represent one
of the prime pair
numbers.
b int Used to represent the
other prime pair
number.
i int Loop iteration
variable for finding
prime pairs.
in Scanner Used to read input
from the user.
c int Counter to count
divisors during
primality check.

OUTPUT:

8|P age
QUESTION 4

Write a program to accept two positive integers m and n, where m is


less than n as user input. Display all Prime Adam integers that are
in the range between m and n (both inclusive) and output them along
with the frequency.

ALGORITHM:

1. Begin the program.


2. Prompt for two integers 'm' and 'n'.
3. Read 'm' and 'n'.
4. If 'm' ≥ 'n', display "INVALID INPUT" and end.
5. Create Scanner 'in'.
6. Initiate 'count' as 0 for tracking Prime-Adam integers.
7. Display header "THE PRIME-ADAM INTEGERS ARE:".
8. Use for loop 'i' in range 'm' to 'n':
a. Check if 'i' is Prime-Adam using 'isAdam'.
b. If Prime-Adam, check if 'i' is prime using 'isPrime'.
c. If both, display 'i', increment 'count'.
9. Check 'count':
a. If 0, show "NIL".
b. Else, display 'count'.
10. End program.

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:

Variable Data Type Description


m int Input integer 'm' for
the starting range.
n int Input integer 'n' for
the ending range.
count int Counter for the
number of Prime-Adam
integers.
in Scanner Used to read input
from the user.
i int Loop iteration
variable for the
range check.
num int Temporary variable
for number
manipulation.
sqNum int Temporary variable to
store squared number.
revNum int Temporary variable to
store reversed
number.
sqRevNum int Temporary variable to
store squared
reversed number.

OUTPUT:

11 | P a g e
QUESTION 5

Write a program in BlueJ to find the factorial of a number using


recursion.

ALGORITHM:

1. Import 'BigInteger' from '[Link]'.


2. Define 'factorial' function taking 'num' (int) as input,
returning BigInteger.
3. In 'factorial':
a. If 'num' is 0 or 1, return [Link].
b. Otherwise, return 'num' multiplied by factorial('num' - 1)
(recursive).
c. In main:
i. Create Scanner for input.
ii. Prompt and read positive integer 'number'.
iii. If 'number' < 0, print error.
iv. Else, calculate 'result' using factorial('number').
v. Display 'result'.
4. End program.

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:

Variable Data Type Description


num Integer Input parameter for
the factorial
function. Represents
the number for which
the factorial is to
be calculated.
result BigInteger Stores the result of
the factorial
calculation.
number Integer Stores the positive
integer entered by
the user to
calculate the
factorial.
scanner Scanner Used to read user
input from the
console.

OUTPUT:

13 | P a g e
QUESTION 6

Write a program in BlueJ to convert Decimal to Binary using


recursion.

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:

public class DecimalToBinaryConverter


{ // Recursive function to convert decimal to binary
public static String decimalToBinary(int decimal)
{
if (decimal == 0)
{
return "0"; // Binary representation of 0 is 0
}
else if (decimal == 1)
{
return "1"; // Binary representation of 1 is 1
}
else
{ // Convert the quotient to binary and append the remainder
return decimalToBinary(decimal / 2) + (decimal % 2);
}
}
public static void main(String[] args)
{
[Link] scanner = new [Link]([Link]);
[Link]("Enter a decimal number: ");
int decimalNumber = [Link]();
if (decimalNumber < 0)
{
[Link]("Please enter a non-negative decimal number.");
}
else
{
String binary = decimalToBinary(decimalNumber);
[Link]("Binary representation: " + binary);
}
[Link](); // Close the scanner to prevent resource leakage
}

14 | P a g e
}

VARIABLE DESCIPTION

Variable Data Type Description


decimal Integer Input parameter for
the decimalToBinary
function
representing the
decimal number to be
converted to binary.
binary String Stores the binary
representation of
the decimal number.
scanner Scanner Used to read user
input from the
console.

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:

Variable Data Type Description


m int Input integer 'm' for
the lower range.
n int Input integer 'n' for
the target sum.
number int Stores the found K-
boat number.
count int Keeps track of the
total number of
digits.
in Scanner Used to read input
from the user.
i int Loop iteration
variable for the
range check.
sum int Temporary variable
for digit sum.

17 | P a g e
t int Temporary variable
for iterating through
digits.

OUTPUT:

18 | P a g e
QUESTION 8

Write a program to declare a matrix a[][] of order (m × n) where


'm' is the number of rows and 'n' is the number of columns such
that the values of both 'm' and 'n' must be greater than 2 and less
than 10. Allow the user to input integers into this matrix. Perform
the following tasks on the matrix:
1. Display the original matrix.
2. Sort each row of the matrix in ascending order using any
standard sorting technique.
3. Display the changed matrix after sorting each row.

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:

Variable Data Type Description


m int Input integer 'm' for
the number of rows.
n int Input integer 'n' for
the number of
columns.
a int[][] 2D array to store the
elements of the
matrix.
in Scanner Used to read input
from the user.
i, j, k int Loop iteration
variables for array
operations.
t int Temporary variable
for swapping
elements.

OUTPUT:

21 | P a g e
QUESTION 9

Write a program to declare a single-dimensional array a[] and a


square matrix b[][] of size N, where N > 2 and N < 10. Allow the
user to input positive integers into the single dimensional array.
Perform the following tasks on the matrix:
Sort the elements of the single-dimensional array in ascending
order using any standard sorting technique and display the sorted
elements. Fill the square matrix b[][] in the following format:
If the array a[] = {5, 2, 8, 1} then, after sorting a[] = {1, 2, 5,
8}
Then, the matrix b[][] would fill as below:
1 2 5 8
1 2 5 1
1 2 1 2
1 1 2 5
Display the filled matrix in the above format.

ALGORITHM:

1. Begin by prompting the user for an integer 'n'.


2. Read and store 'n'.
3. If 'n' is not within the range [3, 9], display "MATRIX SIZE
OUT OF RANGE" and terminate.
4. Create a Scanner 'in' for user input.
5. Initialize integer array 'a' of size 'n' and a 2D array 'b' of
size 'n' x 'n'.
6. Collect elements from the user into array 'a'.
7. Sort 'a' using 'sortArray' function.
8. Display sorted 'a' using a loop.
9. Populate 'b' based on sorted 'a' with a pattern: a. For each
row 'r' of 'b': i. Copy first 'r+1' elements from sorted 'a'
to row 'r'. ii. Copy remaining elements in reverse order to
row 'r'.
10. Display filled matrix 'b' through nested loops.
11. End the program.

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:

Variable Data Type Description


n int Input integer 'n' for
the array and matrix
size.
a int[] Array to store the
elements of the
single-dimensional
array.
b int[][] 2D array to store the
elements of the
filled matrix.
in Scanner Used to read input
from the user.
i, j, k int Loop iteration
variables for array
operations.
r int Loop iteration
variable for the 2D
matrix rows.
t int Temporary variable
for swapping
elements.

OUTPUT:

24 | P a g e
QUESTION 10

The result of a quiz competition is to be prepared as follows:


The quiz has five questions with four multiple choices (A, B, C,
D), with each question carrying 1 mark for the correct answer.
Design a program to accept the number of participants N such that N
must be greater than 3 and less than 11. Create a double-
dimensional array of size (Nx5) to store the answers of each
participant row-wise. Calculate the marks for each participant by
matching the correct answer stored in a single-dimensional array of
size 5. Display the scores for each participant and also the
participant(s) having the highest score.

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:

Variable Data Type Description


n int Input integer 'n' for
the number of
participants.
answers char[][] 2D character array to
store participant
answers.
key char[] Character array to
store the answer key.
in Scanner Used to read input
from the user.
i, j int Loop iteration
variables for array
operations.
hScore int Keeps track of the
highest score.
score int[] Integer array to
store participant
scores.

OUTPUT:

27 | P a g e
QUESTION 11

Write a program to declare a square matrix A[][] of order (M × M)


where 'M' must be greater than 3 and less than 10. Allow the user
to input positive integers into this matrix. Perform the following
tasks on the matrix:
1. Sort the non-boundary elements in ascending order using any
standard sorting technique and rearrange them in the matrix.
2. Calculate the sum of both the diagonals.
3. Display the original matrix, rearranged matrix and only the
diagonal elements of the rearranged matrix with their sum.

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:

Variable Data Type Description


m int Input integer 'm' for
the size of the
matrix.
a int[][] 2D integer array to
store the elements of
the matrix.
in Scanner Used to read input
from the user.
i, j, k int Loop iteration
variables for array
operations.
b int[] Temporary 1D integer
array for non-
boundary elements.
sum int Variable to store the
sum of diagonal
elements.

OUTPUT:

31 | P a g e
QUESTION 12

Write a program to declare a square matrix A[ ][ ] of order MxM


where „M‟ is the number of rows and the number of columns, such
that M must be greater than 2 and less than 10. Accept the value of
M as user input. Display an appropriate message for an invalid
input. Allow the user to input integers into this matrix. Perform
the following tasks:
(a) Display the original matrix.
(b) Rotate the matrix 90° clockwise as shown below:
Original matrix Rotated matrix
1 2 3 7 4 1
4 5 6 8 5 2
7 8 9 9 6 3
(c) Find the sum of the elements of the four corners of the matrix.

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:

Variable Data Type Description


m int Input integer 'm' for
the size of the
square matrix.
a int[][] 2D integer array to
store the elements of
the square matrix.
b int[] 1D integer array to
store elements
temporarily for
rotation.
scan Scanner Used to read input
from the user.
i, j, c int Loop iteration
variables for array
operations.
ctr int Counter variable for
1D array indexing.

OUTPUT:

34 | P a g e
QUESTION 13

Write a program to accept a sentence which may be terminated by


either '.', '?' or '!' only. The words are to be separated by a
single blank space and are in UPPER CASE.
Perform the following tasks:
1. Check for the validity of the accepted sentence only for the
terminating character.
2. Arrange the words in ascending order of their length. If two or
more words have thesame length, then sort them alphabetically.
3. Display the original sentence along with the converted sentence.

ALGORITHM:

1. Define 'sortString' function taking 'ipStr' (string) as input,


returning sorted string.
2. Tokenize 'ipStr' using StringTokenizer.
3. Create 'strArr' for tokenized words.
4. Iterate tokens, store in 'strArr'.
5. Sort 'strArr' by word length and lexicographically.
6. Create StringBuffer for concatenated sorted words.
7. Return sorted string after trimming trailing space.
8. In main:
- Read sentence using Scanner.
- Check if last char is '.', '?', or '!', else show "INVALID
INPUT" and exit.
- Remove last punctuation using '[Link](0, len - 1)'.
- Get sorted string using 'sortString', store in 'sortedStr'.
- Display original and sorted sentences.
9. End program.

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

Variable Data Type Description


ipStr String Input parameter for
the sortString
function
representing the
input sentence.
st StringTokenizer Used to tokenize the
input sentence into
words.
wordCount int Stores the number of
words obtained after
tokenization.
strArr String Array An array to store
the words obtained
from tokenization.
i, j int Loop control
variables for
iterations.
t String Temporary variable
used for swapping
strings during
sorting.
sb StringBuffer Used to concatenate
sorted words and
spaces into the
final sorted string.
str String Stores the input
sentence read from
the user.
len int Stores the length of
the input sentence.
sortedStr String Stores the sorted
string obtained
after calling the
sortString function.

OUTPUT:

37 | P a g e
QUESTION 14

Write a program to accept a sentence which may be terminated by


either „.‟, „?‟ or „!‟ only. The words are to be separated by a
single blank space and are in uppercase. Perform the following
tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence into
palindrome words by concatenating the word by its reverse
(excluding the last character).
(c) Display the original sentence along with the converted
sentence.

ALGORITHM:

1. Define 'isPalindrome' function: returns true if input 'word' is


a palindrome.
2. Define 'makePalindrome' function: creates palindrome by
appending reversed chars after first non-repeating.
3. Read, trim, and uppercase sentence.
4. If last char not '.', '?', '!', display "INVALID INPUT" and
exit.
5. Remove last punctuation using 'substring'.
6. Tokenize sentence, create StringBuffer.
7. Iterate tokens:
- Append word if palindrome, else make palindrome and append.
8. Convert StringBuffer to string, trim trailing space.
9. Display original and converted sentences.
10. End program.

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:

Variable Data Type Description


word String A string representing
a word that is being
evaluated for
palindromicity.
palin boolean A boolean flag
indicating whether a
word is a palindrome
or not.
len int An integer
representing the
length of a string.
i int An integer used as an
index in loops for
character comparison.
lastChar char A character
representing the last
character of a given
input string.
sb StringBuffer A mutable string
buffer used to
manipulate and
construct strings.
ipStr String The input sentence
provided by the user.
str String A modified version of
ipStr excluding the
last punctuation
character.
st StringTokenizer A class used to
tokenize the modified
input string str.
isPalinWord boolean A boolean indicating
whether a word in the
sentence is a
palindrome.
palinWord String A palindrome version
of a word generated

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

The names of the teams participating in a competition should be


displayed on a banner vertically, to accommodate as many teams as
possible in a single banner. Design a program to accept the names
of N teams, where 2 < N < 9 and display them in vertical order,
side by side with a horizontal tab (i.e. eight spaces).

ALGORITHM:

1. Define 'isPalindrome' function: returns true if 'word' is a


palindrome.
2. Define 'makePalindrome' function: creates palindrome by
appending reversed chars after first non-repeating.
3. Read, trim, and uppercase sentence.
4. If last char not '.', '?', '!', display "INVALID INPUT" and
exit.
5. Remove last punctuation using 'substring'.
6. Tokenize, create StringBuffer.
7. Iterate tokens:
- If palindrome, append, else make palindrome and append.
8. Convert StringBuffer to string, trim trailing space.
9. Display original and converted sentences.
10. End program.

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

Write a program to accept a sentence which may be terminated by


either '.', '?' or '!' only. The words may be separated by more
than one blank space and are in UPPER CASE.
Perform the following tasks:
1. Find the number of words beginning and ending with a vowel.
2. Place the words which begin and end with a vowel at the
beginning, followed by the remaining words as they occur in the
sentence.

ALGORITHM:

1. Prompt for sentence.


2. Read, trim, and uppercase 'ipStr'.
3. If last char not '.', '?', '!', show "INVALID INPUT" and end.
4. Remove last punctuation, get 'str'.
5. Tokenize 'str'.
6. Create 'sbVowel' and 'sb'.
7. Initialize 'c'.
8. Loop tokens:
- Extract word, get length.
- If first and last chars are vowels, increment 'c', append to
'sbVowel', add space.
- Else, append to 'sb', add space.
9. Concatenate 'sbVowel' and 'sb' to 'newStr'.
10. Display "NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL =
c".
11. Display 'newStr'.
12. Define 'isVowel' function: returns true if 'ch' is vowel ('A',
'E', 'I', 'O', 'U'), ignoring case.
13. End program.

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

Write a program to accept a sentence which may be terminated by


either „.‟ or „?‟ only. The words are to be separated by a single
blank space. Print an error message if the input does not terminate
with „.‟ or „?‟. You can assume that no word in the sentence
exceeds 15 characters, so that you get a proper formatted output.
Perform the following tasks:
(i) Convert the first letter of each word to uppercase.
(ii) Find the number of vowels and consonants in each word and
display them with proper headings along with the words.

ALGORITHM:

1. Prompt: "Enter a paragraph: ".


2. Read 'str'.
3. Get 'l', 'ch'.
4. Print "\nOUTPUT:".
5. If ch not '.', '?' print "INVALID INPUT" and end.
6. Init 'p', 'vowels', 'cons' to 0.
7. Init empty 'tmp'.
8. Modify by capitalizing 1st letter of each word: Loop through
'str', if ch space, extract word 'p' to 'i', capitalize 1st
letter, add to 'tmp', update 'p' to 'i + 1'.
9. Print modified 'tmp'.
10. Print table header: "Word" (spacing), "Vowels", "Consonants".
11. Init 'p' to 0, reset 'vowels', 'cons'.
12. Loop through 'tmp': If ch not space, '.', '?', if ch letter, if
vowel, increment 'vowels', else, increment 'cons'; else (word
complete), extract word 'p' to 'i', print word, spacing, print
'vowels', 'cons', update 'p' to 'i + 1', reset 'vowels','cons'.
13. End program.

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:

Variable Data Type Description


i int Loop iterator
variable.
j int Loop iterator
variable.
vowels int Count of vowels in a
word.
cons int Count of consonants
in a word.
p int Index for tracking
word extraction.
l int Length of the input
paragraph.
str String The modified input
paragraph.
word String A word extracted from
the paragraph.
tmp String Temporary string for
word capitalization.
ch, ch1 char Characters for
processing.
br BufferedReader An instance of
BufferedReader to
read user input.

OUTPUT:

50 | P a g e
QUESTION – 18

Write a program to accept a sentence which may be terminated by


either „.‟ „?‟ or „!‟ only. Any other character may be ignored. The
words may be separated by more than one blank space and are in
UPPER CASE.
Perform the following tasks:
(a) Accept the sentence and reduce all the extra blank space
between two words to a single blank space.
(b) Accept a word from the user which is part of the sentence along
with its position number and delete the word and display the
sentence.

ALGORITHM:

1. Prompt input sentence.


2. Read input, store last character.
3. If last char not '.', '?', '!', print "INVALID INPUT" and exit.
4. Remove spaces via reduceSpaces function:
- Split using \\s+.
- Build using non-empty words in StringBuilder.
5. Prompt word and position.
6. Read word, position.
7. Delete word via deleteWord function:
- Split sentence into words using \\s+.
- Skip word at position.
- Build updated sentence with StringBuilder.
8. Print updated sentence.
9. End program.

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 (![Link](wordToDelete) || 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:

Variable Data Type Description


br BufferedReader An instance of
BufferedReader to
read user input.
inputSentence String The original input
sentence provided by
the user.
lastChar char The last character of
the input sentence.
sentence String The sentence with
reduced extra spaces.
wordToDelete String The word to be
deleted from the
sentence.
wordPosition int The position of the
word to be deleted.
updatedSentence String The sentence after the
specified word is
deleted.
words String[] An array of words split
from the sentence.
sentenceBuilder StringBuilder Used to build the
sentence with reduced
spaces.
count int Counter to track the
occurrence of the word
at a specific position.

OUTPUT:

53 | P a g e
QUESTION – 19

Design a program which accepts your date of birth in dd mm yyyy


format. Check whether the date entered is valid or not. If it is
valid, display “VALID DATE”, also compute and display the day
number of the year for the date of birth. If it is invalid, display
“INVALID DATE” and then terminate the program.

ALGORITHM:

1. Prompt "Enter date of birth (dd mm yyyy): ".


2. Read day, month, year.
3. Check valid ranges:
- Day: 1-31
- Month: 1-12
- Year: > 0
4. Determine max days in month, considering leap year:
- Leap year: divisible by 4, not 100 unless 400.
5. Check valid day for month:
- Day <= max days.
6. Calculate day number of year:
- Accumulate days of past months.
7. If all checks pass, print "VALID DATE" + day number. Else, print
"INVALID DATE" and end.

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:

Variable Data Type Description


in Scanner An instance of
Scanner to read user
input.
day int The entered day of
birth.
month int The entered month of
birth.
year int The entered year of
birth.
isValid boolean Flag to indicate if
the date is valid.
maxDays int[] An array containing
the maximum days in
each month.
dayNumber int The calculated day

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:

Variable Name Data Type Variable Description


year int The input year
provided by the user.
dayNumber int The input day number
provided by the user.
nDays int The input number of
days provided by the
user.
month int The calculated month
corresponding to the
day number.
day int The calculated day
within the month.
futureYear int The future year after
adding the specified
days.
futureMonth int The future month
after adding the
specified days.
futureDay int The future day within
the month after
adding days.
daysInMonth int[] An array storing the
days in each month.
monthNames String[] An array storing the
names of the months.
scanner Scanner A Scanner object to
read user input.

OUTPUT:

60 | P a g e
QUESTION – 21

Caesar Cipher is an encryption technique which is implemented as


ROT13 ('rotate by 13 places'). It is a simple letter substitution
cipher that replaces a letter with the letter 13 places after it in
the alphabets, with the other characters remaining unchanged.

ALGORITHM:

1. Prompt "Enter day number, year, and days 'N': ".


2. Read day, year, 'N'.
3. Check ranges: day (1-366), year (4 digits), 'N' (1-100).
4. Calculate month, day based on day number:
- Init maxDays, loop through months:
- Decrement day by max days until <= current month max days.
5. Check leap year: divisible by 4, not 100 unless 400.
6. Calculate future date after 'N' days:
- Increment day by 'N'.
- If day > max days of month, adjust month, day.
7. Display generated date and future date after 'N' days.
8. End program.

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:

Variable Data Type Description


in Scanner An instance of
Scanner to read user
input.
dayNumber int The entered day
number.
year int The entered year.
nDays int The number of days
after the generated
date.
maxDays int[] An array containing
the maximum days in
each month.
month int The calculated month
based on day number.
isLeapYear boolean Flag to indicate if
the year is a leap
year.
futureDayNumber int The calculated day
number after 'N'
days.
monthName String The name of the
month.
date String The generated date.
futureDate String The date after 'N'

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

Write a Java program to implement STACK using array.

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:

Variable Name Data Type Description


maxSize int Maximum size of the
stack.
top int Index of the top
element in the stack.
stackArray int[] Array to store the
elements of the
stack.
scanner Scanner Scanner object to
read user input.
size int Size of the stack
entered by the user.
data int Data to be pushed
onto the stack.
choice int User's choice from
the menu.

67 | P a g e
stack StackArray Instance of the
StackArray class to
manage the stack.

OUTPUT:

68 | P a g e
QUESTION – 23

Write a Java program to implement STACK using Linked List.

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:

Variable Name Data Type Description


top Node Reference to the top
node of the linked
list stack.
scanner Scanner Scanner object to
read user input.
stack StackLinkedList Instance of the
StackLinkedList
class.
choice int User's choice from
the menu.
data int Data to be pushed
onto the stack.
popped int Popped element from
the stack.
current Node Pointer to traverse
through the linked

71 | P a g e
list.

OUTPUT:

72 | P a g e
QUESTION – 24

Write a Java program to implement QUEUE using array.

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:

Variable Name Data Type Description


scanner Scanner A Scanner object for
reading user input.
size int Size of the queue
entered by the user.
queue QueueArray An instance of the
QueueArray class to
manage the queue.
maxSize int Maximum size of the

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

Write a Java program to implement QUEUE using Linked List.

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:

Variable Name Data Type Description


scanner Scanner A Scanner object for
reading user input.
queue QueueLinkedList An instance of the
QueueLinkedList class
to manage the queue.
front Node Reference to the
front node of the
queue.
rear Node Reference to the rear
node of the queue.

OUTPUT:

80 | P a g e
QUESTION – 26

Write a Java program to implement Circular Queue using Array.

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];
}

public void enqueue(int data)


{
if (isFull())
{
[Link]("Queue is full. Cannot enqueue.");
return;
}
if (isEmpty())
{
front = 0;
}
rear = (rear + 1) % maxSize;
queueArray[rear] = data;

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:

Variable Name Data Type Description


scanner Scanner A Scanner object for
reading user input.
size int The size of the
circular queue
83 | P a g e
entered by the user.
queue CircularQueueArray An instance of the
CircularQueueArray
class to manage the
circular queue.
maxSize int Maximum size of the
circular queue.
front int Index of the front
element.
rear int Index of the rear
element.
queueArray int[] Array to store
circular queue
elements.

OUTPUT:

84 | P a g e
QUESTION – 27

Write a Java Program to implement Dequeue using Array.

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:

Variable Data Type Description


maxSize int Maximum size of the
dequeue.
front int Front pointer
indicating the front
of the dequeue.
rear int Rear pointer
indicating the rear
of the dequeue.
dequeueArray int[] Array to store
dequeue elements.

OUTPUT:

89 | P a g e

You might also like