0% found this document useful (0 votes)
20 views91 pages

My Computer Science Project

Uploaded by

memertejas
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)
20 views91 pages

My Computer Science Project

Uploaded by

memertejas
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
You are on page 1/ 91

Isc 2024-25

Computer science
Assignment file
Name: TEJAS KESARWANI
Class: xii - ‘A’
Uid:
Index no.:
INDEX

S.No. TOPIC Page Teacher's


No. Remarks
1. Keith Number 1

2. Fascinating Number 3

3. Vampire Number 6

4. Hamming Number 9

5. Bouncy Number 11

6. Goldbach Number 13
7. Lucky Numbers in a Range 16
8. Matrix Multiplication 18
9. Doubly Markov Matrix 21
10. Clockwise Spiral Matrix 25
11. Rotation by 270 degrees clockwise 28
12. Anticlockwise Spiral Matrix 31
13. Sorting Non-Boundary Elements 34
14. Decimal Equivalent 40
15. Snowball string 43
16. Caesar Cipher 46
17. Anagram Words 50
18 Hamming Distance 52
19. Swapping words lexicographically 54
20. Decoding 56
21. Time in words 60
22 Difference between dates 64
23. Checking Date Validity 68
24. Date Display 72
25. Calendar 78

Internal Examiner Signature: External Examiner Signature:


Question 1 Page No:1

Write a program to input a number and check whether it is a keith number or not.A n digit number x is
called Keith number if it appears in a special sequence (defined below) generated using its digits. The
special sequence has first n terms as digits of x and other terms are recursively evaluated as sum of
previous n terms
Input : x = 197
Output : 197 is a Keith Number
197 has 3 digits, so n = 3
The number is Keith because it appears in the special
sequence that has first three terms as 1, 9, 7 and
remaining terms evaluated using sum of previous 3 terms.
1, 9, 7, 17, 33, 57, 107, 197, .....
Algorithm:
1.Convert the input number to a string.
2.Iterate over the string, converting each character to an integer and storing it in an array.
3.Create an array sequenceOfSums with a size twice the number of digits.
4.Copy the extracted digits into the initial positions of sequenceOfSums.
5.Initialize an index i to the number of digits.
6.While the last element in sequenceOfSums is less than the input number:
(i)Calculate the sum of the last numDigits elements in sequenceOfSums.
(ii)Append this sum to the sequenceOfSums array.
(iii)Increment the index i.
7.If the last element in sequenceOfSums is equal to the input number, it's a Keith number. Otherwise,
it's not a Keith Number.
8.Print an appropriate message based on the result of the check.
Program Code:
import java.util.Scanner;

public class KeithNumber {


public static void main(String args[]) { Page No: 2
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();

int len = Integer.toString(num).length();


int[] digits = new int[len];
int[] sequenceOfSums = new int[len * 2]; // Estimated upper bound

// Extract digits and initialize sequence


for (int i = 0; i < len; i++) {
digits[i] = num % 10;
sequenceOfSums[i] = digits[i];
num /= 10;
}

int index = len;


while (sequenceOfSums[index - 1] < num) {
int sum = 0;
for (int i = index - len; i < index; i++) {
sum += sequenceOfSums[i];
}
sequenceOfSums[index] = sum;
index++;
}

if (sequenceOfSums[index - 1] == num) {
System.out.println(num + " is a Keith number.");
for (int i = 0; i < index; i++) {
System.out.print(sequenceOfSums[i] + ", "); Page No:3
}
} else {
System.out.println(num + " is not a Keith number.");
}
}
}
Variable Description:
num: The input number to be checked for being a Keith number.
len: The number of digits in the input number.
digits: An array to store the individual digits of the input number.
sequenceOfSums: An array to store the sequence of sums generated during the Keith number check.
index: An index variable used to track the current position in the sequenceOfSums array.
sum: A temporary variable to store the sum of digits during each iteration.

Sample Input-Output:
Input:12
Output:12 is not a Keith Number.
Question 2:
Write a program to input a number and check whether it is a fascinating number or not.A fascinating
number is a number that, when multiplied by 2 and 3, and then concatenated with the original number,
results in a number containing all digits from 1 to 9 exactly once, regardless of the number of
zeros.For Example:
Multiply 192 by 2: 192 * 2 = 384 and then Multiply 192 by 3: 192 * 3 = 576.Therefore,the sequence
formed is 192384576. It consists of all digits from 1 to 9. So, 192 is a fascinating number.
Algorithm:
1.Prompt the user to enter a three-digit number using Scanner.
2.Check if the entered number is greater than or equal to 100 (three digits). If not, exit.
3.Multiply the input number by 2 and 3, storing the results in p1 and p2 respectively.
4.Convert the original number, p1, and p2 to strings using Integer.toString.
5.Concatenate these strings into a single string named q. Page No:4
6.Iterate through q character by character.
If the character is a space, replace it with another character (typically a space itself) using q.replace
7.Create an integer array arr with the same size as q.Iterate through q character by character.
8.Convert each character to an integer by subtracting its ASCII code for '0'. This removes the leading
ASCII offset for digits.Store the converted integer in the corresponding index of arr.
9.Loop through q again, checking if any character is a space. If found, set a flag (flag) to false and exit
the loop. This indicates missing digits due to spaces.
10.If flag is still true (no missing digits), iterate through numbers 1 to 9 (check_for).For each
check_for value, loop through arr .If the current element in arr matches check_for, set another flag
(flag2) to true.
11.After iterating through arr, if flag2 is still false, it means a digit is missing. Set flag to false and exit
the loop. Otherwise, reset flag2 to false and continue to the next check_for value.
12.If flag is still true after checking all digits, then all digits 1-9 appeared exactly once in q, making it
a fascinating number. Print a message indicating this.
If flag becomes false at any point, the number is not a fascinating number. Print a message indicating
this.
Program Code:
import java.util.Scanner;
class FascinatingNumber
{
public static void main(String args[])
{
System.out.println("Enter any three digit number");
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
if(num>=100)
{
int p1=num*2,p2=num*3;
String q=Integer.toString(num)+Integer.toString(p1)+Integer.toString(p2);
System.out.println(q);
Page No:5
boolean flag=true,flag2=false;
int arr[]=new int[q.length()],counter=0;
for(int i=0;i<q.length();i++)
arr[i]=q.charAt(i)-'0';//converting char to integer by subtracting '0';
for(int i=0;i<q.length();i++)
{
if(q.charAt(i)!=' ')
q=q.replace(q.charAt(i),' ');
else
{
System.out.println("This is not a fascinating number");
flag=false;
break;
}
}
if(flag==true){
for(int check_for=1;check_for<=9;check_for++)
{
for(int i=0;i<q.length();i++)
{
if(arr[i]==check_for )
flag2=true;
}
if(flag2==true)
{
++counter;
flag2=false;
continue;
} Page No:6
else
{
System.out.println("This is not a fascinating number");
break;
}}
if(counter==9)
System.out.println("This is a fascinating number");
}}}}
Variable Description:
num: The input number to be checked for being a fascinating number.
p1: The product of num and 2.
p2: The product of num and 3.
q: The concatenated string of num, p1, and p2.
arr: An array to store the digits of the concatenated string q.
flag: A boolean flag to indicate if all digits 1-9 are present in q.
flag2: A temporary boolean flag used during digit checking.
counter: A counter to keep track of the number of digits found in q.
i: A loop counter variable.
check_for: A variable used to iterate through digits 1-9 during the check.
Sample Input-Output:
Input: Enter any three digit number: 219
Output: 219438657 This is a fascinating number.
Question 3
Write a program to input a number and check whether it is a Vampire Number or not.A vampire
number is a number that, when multiplied by another number of the same length, produces a number
whose digits are exactly those of the two original numbers. For example, 1260 = 21 * 60
Algorithm:
1.Take an integer as input.
2.Determine the number of digits in the input number. Page No: 7
3.Iterate through all possible pairs of numbers with the same number of digits as the input number.For
each pair, calculate their product.

4.Convert both the product and the concatenated original numbers to strings.

5.Sort the characters of both strings.

6.Compare the sorted strings. If they are identical, the input number is a vampire number.

7.Print whether the input number is a vampire number or not.


Program Code:
import java.util.Scanner;
class VampireNumber2
{
public static void main(String args[])
{
System.out.println("Enter the range");
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int arr1[]=new int[2];
int arr2[]=new int[2];
if(m>=1000 && m<=9999 && n>=1000 && n<=9999)
{
for(int i=m;i<=n;i++)
{
arr1[0]=i%10; arr1[1]=(i%100)/10;
arr2[0]=(i/100)%10; arr2[1]=i/1000;
if((arr1[0]*10+arr1[1])*(arr2[0]*10 + arr2[1])==i)
{
System.out.println(i);
continue; Page No: 8
}
if((arr1[0]*10+arr1[1])*(arr2[1]*10 + arr2[0])==i)
{
System.out.println(i);
continue;
}
if((arr1[1]*10+arr1[0])*(arr2[0]*10 + arr2[1])==i)
{
System.out.println(i);
continue;
}
if((arr1[1]*10+arr1[0])*(arr2[1]*10 + arr2[0])==i)
{
System.out.println(i);
continue;
}
if((arr1[0]*10+arr2[1])*(arr1[1]*10 + arr2[0])==i)
{
System.out.println(i);
continue;
}
if((arr2[1]*10+arr1[0])*(arr1[1]*10 + arr2[0])==i)
{
System.out.println(i);
continue;
}
if((arr1[0]*10+arr2[1])*(arr2[0]*10 + arr1[1])==i)
{
System.out.println(i); Page No: 9
continue;
}
if((arr2[1]*10+arr1[0])*(arr2[0]*10 + arr1[1])==i)
{
System.out.println(i);
continue;
}}}}}
Variable Description:
● num: The input number to be checked.
● numDigits: The number of digits in num.
● i, j: Loop counters for iterating through potential factors.
● factor1, factor2: The two factors being considered.
● product: The product of factor1 and factor2.
● numStr, productStr: String representations of num and product.
● sortedNumStr, sortedProductStr: Sorted string representations of numStr and productStr.

Sample Input/Output:

Input: 1260

Output: 1260 is a vampire number.

Question 4

Write a program to input a number and check whether the number is a Hamming number or not.

A Hamming number is a positive integer that can be expressed as 2^x * 3^y * 5^z where x, y, and z

are non-negative integers.

Algorithm:

1.Prompt the user to enter a number using Scanner.

2. Check if the input number is less than or equal to zero (non-positive). If so, it's not a Hamming
. number .

3.Repeatedly divide the number by 2 while it's divisible by 2.

4.Repeat the same process for 3 and 5 (check divisibility and division).
Page No: 10

5.If the final number after all divisions is 1, then the original number is a Hamming number.

All Hamming numbers have only 2, 3, and 5 as prime factors.

Program Code:

class HammingNumber

static int n;

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter any number to check");

int num=sc.nextInt();

n=num;

if(isHamming(n)==true)

System.out.println(num+" "+"is a Hamming Number");

else

System.out.println(num+" "+ "is not a Hamming Number");

static boolean isHamming(int num)

if(num<=0)

return false;

else

while(num%2==0)
num/=2; Page No: 11

while(num%3==0)

num/=3;

while(num%5==0)

num/=5;

return (num==1);

}}}

Variable Description:

num: The input number to be checked.

n: A static variable to hold the original input number (not used in the current logic but present in the
code).

Sample Input/Output:

Input: Enter any number to check: 12

Output: 12 is a Hamming Number

Question 5

A bouncy number is a number whose digits are either strictly increasing or strictly decreasing. For
example, 1345 and 9876 are bouncy numbers, but 1553 and 12321 are not. Given a number,
determine if it is a bouncy number.

Algorithm:

● Prompt the user to enter a number using Scanner class.


● Convert the input number to a string and then to an integer array to access individual digits.
● Iterate through the array from index 0 to the second-last element (length-2). If any element is greater
than the next one, set a flag (flg1) to indicate not increasing.
● Repeat step 3 with a separate flag (flg2), but check if the current element is less than the next one.
● If both flg1 and flg2 are false (meaning neither increasing nor decreasing sequence found), the
number is bouncy.Otherwise, it's not a bouncy number.

Program Code:

import java.util.Scanner;
class BouncyNumber Page No: 12

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter a number");

int num=sc.nextInt(),arr[]=new int[Integer.toString(num).length()],copy_num=num;

for(int i=0;i<Integer.toString(num).length();i++)

arr[i]=Integer.toString(num).charAt(i)-'0'; // converting char to int by ascii trick

boolean flg1=true,flg2=true;

for(int i=0;i<Integer.toString(num).length()-1;i++)

if(arr[i]<=arr[i+1])

continue;

else

flg1=false;

break;

for(int i=0;i<Integer.toString(num).length()-1;i++)

if(arr[i]>=arr[i+1])
continue; Page No: 13

else

flg2=false;

break;

if(flg1==false && flg2==false)

System.out.println("This is a bouncy number");

else

System.out.println("this is not a bouncy number");

Variable Descriptions:

● num: The input number to be checked.


● arr: An array to store the digits of the input number.
● copy_num: A copy of the input number (not strictly necessary in this logic).
● flg1: A flag to indicate if the digit sequence is not strictly increasing.
● flg2: A flag to indicate if the digit sequence is not strictly decreasing.

Sample Input/Output:

Input: Enter a number: 1352

Output: This is a bouncy number.

Question6

Write a program to input a number and check whether it is a Goldbach Number or not.A Goldbach
number is an even integer greater than 2 that can be expressed as the sum of two prime numbers.

Algorithm:

● Read an even integer num from the user.


● Check if num is even and greater than 2. Page No: 14
● Iterate through odd numbers from 3 to num/2:
■ Check if both the current number and num - current number are prime.
■ If both are prime, num is a Goldbach number.
■ Print whether num is a Goldbach number or not.

import java.util.Scanner;

public class GoldbachNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an even integer greater than 2: ");

int num = scanner.nextInt();

if (num <= 2 || num % 2 != 0) {

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

return;

boolean isGoldbach = false;

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

if (isPrime(i) && isPrime(num - i)) {

isGoldbach = true;

System.out.println(num + " = " + i + " + " + (num - i));

break;

if (!isGoldbach) {

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

}
} Page No: 15

public static boolean isPrime(int n) {

if (n <= 1) {

return false;

if (n <= 3) {

return true;

if (n % 2 == 0 || n % 3 == 0) {

return false;

for (int i = 5; i * i <= n; i += 6) {

if (n % i == 0 || n % (i + 2) == 0) {

return false;

return true;

Variable Description:

num: The input even integer.

isGoldbach: A boolean flag to indicate if num is a Goldbach number.

i: Loop counter for iterating through odd numbers.

Sample Input/Output:

Input:
Enter an even integer greater than 2: 24 Page No: 16

Output:

24 = 11 + 13

Question 7

Write a program to input a range within which lucky numbers are to be found. A lucky number is a
number that survives multiple rounds of elimination. We start with a list of consecutive positive
integers. In the first round, we eliminate every second number. In the second round, we eliminate
every third remaining number. This process continues, and the last number remaining is the lucky
number.

Example:

Consider the numbers from 1 to 10.

● Round 1: 1, 3, 5, 7, 9
● Round 2: 1, 3, 7, 9
● Round 3: 1, 7
● Round 4: 7

Here, 7 is the lucky number.

Algorithm:

● Read the starting and ending numbers for the range.


● Create a list to store the numbers from the starting number to the ending number.
● Initialize a counter i to 1.
● While the list has more than one element:
○ Calculate the index of the element to be removed using the formula (index + i - 1) % list.size().
○ Remove the element at the calculated index.
○ Increment the counter i.

Program Code:

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class LuckyNumbers {

public static void main(String[] args) {


Page No: 17

Scanner scanner = new Scanner(System.in);

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

int start = scanner.nextInt();

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

int end = scanner.nextInt();

List<Integer> numbers = new ArrayList<>();

for (int i = start; i <= end; i++) {

numbers.add(i);

int i = 1;

int index = 0;

while (numbers.size() > 1) {

index = (index + i - 1) % numbers.size();

numbers.remove(index);

i++;

System.out.println("Lucky numbers in the range " + start + " to " + end + ": " + numbers.get(0));

Print the remaining element in the list as the lucky number.

Input:

Enter the starting number: 1

Enter the ending number: 10


Output: Page No: 18

Lucky numbers in the range 1 to 10: 7

Question 8

Write a Program to input two double dimensional arrays and multiply them . Then, display the
resultant product. Show an appropriate message if multiplication is not possible.

Algorithm:

1.Prompt the user to enter the number of rows and columns for both matrices.

2.Create two objects of the MatMul class, one for each input matrix.

3.Call the accept method for each object to read the elements of the matrix from the user.

4.Check if the number of columns in the first matrix is equal to the number of rows in the second
matrix. If not, matrix multiplication is not possible.

5.Create a third MatMul object to store the result matrix.

6.Use a nested loop structure to iterate through each element of the resulting matrix.

7.For each element, calculate the dot product of the corresponding row from the first matrix and the
corresponding column from the second matrix.

8.Store the calculated sum in the appropriate position of the result matrix.

9.Display the original first and second matrices using the display method.

10.Display the resulting product matrix using the display method of the third MatMul object.

Program:

class MatMul {

int arr[][], m, n;

MatMul(int mm, int nn) {

m = mm;

n = nn;

arr = new int[m][n];


} Page No: 19

void accept() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter " + (m * n) + " integers");

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

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

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

MatMul multiply(MatMul P, MatMul R) {

MatMul ob = new MatMul(P.m, R.n);

for (int i = 0; i < P.m; i++) {

for (int j = 0; j < R.n; j++) {

for (int k = 0; k < P.n; k++)

ob.arr[i][j] += P.arr[i][k] * R.arr[k][j];

return ob;

void display() {

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

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

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

System.out.println(" ");

}
} Page No: 20

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter rows and columns for the first matrix");

int rows1 = sc.nextInt(), columns1 = sc.nextInt();

MatMul ob1 = new MatMul(rows1, columns1);

ob1.accept(); // Accept values for the first matrix

System.out.println("Enter rows and columns for the second matrix");

int rows2 = sc.nextInt(), columns2 = sc.nextInt();

MatMul ob2 = new MatMul(rows2, columns2);

ob2.accept(); // Accept values for the second matrix

if (columns1 != rows2) {

System.out.println("Matrix multiplication not possible");

return;

MatMul ob3 = new MatMul(rows1, columns2);

ob3 = ob3.multiply(ob1, ob2);

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

ob1.display();

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

ob2.display();

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

ob3.display();

}
Variable Description: Page No: 21

● arr: A 2D integer array within MatMul to store the matrix elements.


● m.n: The number of rows and columns of the matrix (instance variables within MatMul).
● P, R, ob: Objects of the MatMul class representing matrices.

Sample Input/Output:

Input:

Enter rows and columns for the first matrix 2 3

Enter the elements of the first matrix: 1 2 3 4 5 6

Enter rows and columns for the second matrix 3 2

Enter the elements of the second matrix: 1 4 2 5 3 6

Output:

First Matrix:

1 2 3

4 5 6

Second Matrix:

1 4

2 5

3 6

Resultant Matrix:

9 22

14 32

Question 9

Write a program to input a matrix and check whether it is a doubly markov matrix or not. A doubly
markov matrix is one in which all elements are non negative and the sum of each row and column is
equal to one.

Algorithm:
1.Read the dimension n of the square matrix. Page No: 22

2.Read the elements of the matrix from the user.

3.Check if each element is within the range of 0 to 1.

4.Iterate through each row, calculate the sum of elements, and check if it's equal to 1.

5.Iterate through each column, calculate the sum of elements, and check if it's equal to 1.

6.If all rows and columns sum to 1 and all elements are non-negative, the matrix is doubly stochastic.

7.Otherwise, it's not a doubly stochastic matrix.

Program Code:

import java.util.Scanner;

public class DoublyMarkovMatrix {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter n");

int n = sc.nextInt();

if (n >= 3 && n <= 9) {

double[][] arr = new double[n][n];

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

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

System.out.println("Enter element at position(" + (i + 1) + "," + (j + 1) + ")");

arr[i][j] = sc.nextDouble();

if (arr[i][j] < 0 || arr[i][j] > 1) {

System.out.println("Invalid Input: Elements must be between 0 and 1.");

return;
} Page No: 23

boolean isDoublyMarkov = true;

// Check row sums

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

double rowSum = 0;

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

rowSum += arr[i][j];

if (Math.abs(rowSum - 1) > 0.0001) { // Allow for small floating-point errors

isDoublyMarkov = false;

break;

// Check column sums

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

double colSum = 0;

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

colSum += arr[i][j];

if (Math.abs(colSum - 1) > 0.0001) { // Allow for small floating-point errors

isDoublyMarkov = false;

break;
} Page No: 24

if (isDoublyMarkov) {

System.out.println("The given matrix is a doubly stochastic matrix.");

} else {

System.out.println("The given matrix is not a doubly stochastic matrix.");

} else {

System.out.println("Invalid input: n must be between 3 and 9.");

Variable Description:

n: The dimension of the square matrix.

arr: A 2D array to store the matrix elements.

i, j: Loop counters for iterating through the matrix.

sumr: A variable to store the sum of elements in a row.

sumc: A variable to store the sum of elements in a column.

Sample Input:

Enter n:

Enter element at position(1,1):

0.3

Enter element at position(1,2):


0.4 Page No: 25

Enter element at position(1,3):

0.3

Enter element at position(2,1):

0.2

Enter element at position(2,2):

0.5

Enter element at position(2,3):

0.3

Enter element at position(3,1):

0.5

Enter element at position(3,2):

0.1

Enter element at position(3,3):

0.4

Output:

The given matrix is a doubly stochastic matrix.

Question 10

Write a program to create a spiral matrix using the elements which are input by the user.

Algorithm:

● Read an integer n representing the size of the square matrix.


● Create a 2D integer array matrix of size n x n to store the spiral elements.
● Initialize variables:
○ num: Starting value for the elements (1).
○ top, bottom, left, right: Boundaries for filling the matrix.
○ While num is less than or equal to n * n:

Page No: 26

■ Iterate from left to right, assigning num to each element in the top row.
■ Increment top to move to the next row.

■ Iterate from top to bottom, assigning num to each element in the right column.
■ Decrement right to move to the previous column.

■ Iterate from right to left, assigning num to each element in the bottom row.
■ Decrement bottom to move to the previous row.

■ Iterate from bottom to top, assigning num to each element in the left column.
■ Increment left to move to the next column.
○ Increment num for the next element.

Print the elements of the matrix in a tabular format.

Program:

import java.util.Scanner;

public class SpiralMatrix {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a natural number (>= 3): ");

int n = scanner.nextInt();

scanner.close();

if (n < 3) {

System.out.println("Please enter a number greater than or equal to 3.");

return;

int[][] matrix = generateSpiralMatrix(n);

// Print the spiral matrix

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


Page No: 27

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

System.out.printf("%-4d", matrix[i][j]);

System.out.println();

// Function to generate the spiral matrix

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

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

int num = 1;

int top = 0, bottom = n - 1, left = 0, right = n - 1;

while (num <= n * n) {

// Fill top row from left to right

for (int i = left; i <= right; i++) {

matrix[top][i] = num++;

top++;

// Fill right column from top to bottom

for (int i = top; i <= bottom; i++) {

matrix[i][right] = num++;

}
right--; Page No: 28

// Fill bottom row from right to left

for (int i = right; i >= left; i--) {

matrix[bottom][i] = num++;

bottom--;

// Fill left column from bottom to top

for (int i = bottom; i >= top; i--) {

matrix[i][left] = num++;

left++;

return matrix;

Question 11

Write a program to input a square matrix and rotate it by 270 degrees clockwise

Algorithm:

● Read the size of the square matrix n.


● Read the elements of the matrix from the user.
● Call the rotateMatrix function to perform the rotation.
● The function iterates over the matrix in concentric squares, starting from the outermost square and
moving inwards.
● For each square, it swaps the elements in a clockwise direction:
○ Swap Top-left element is with bottom-left.
○ Swap Bottom-left is with bottom-right.
○ Swap Bottom-right is with top-right.
○ Swap Top-right is with the original top-left. Page No: 29

Print the rotated matrix.

Program:

import java.util.Scanner;

public class RotateMatrix {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

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

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

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

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

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

rotateMatrix(matrix);

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

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

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

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

System.out.println();
} Page No: 30

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

int n = matrix.length;

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

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

int temp = matrix[i][j];

matrix[i][j] = matrix[n - 1 - j][i];

matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];

matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];

matrix[j][n - 1 - i] = temp;

}}}}

Variable Description:

n: The size of the square matrix.

matrix: A 2D integer array to store the matrix elements.

i, j: Loop counters used for iterating through the matrix.

temp: A temporary variable used for swapping elements during rotation.

Sample Input/Output:

Input:

Enter the size of the square matrix: 4

Enter the elements of the matrix:

1234

5678

9 10 11 12

13 14 15 16
Output: Page No: 31

13 9 5 1

14 10 6 2

15 11 7 3

16 12 8 4

Question 12

Write a program to form an anticlockwise-spiral matrix by the numbers input by the user.

Algorithm:

● Read the size n of the square matrix.


● Create a 2D integer array matrix of size n x n.
● Initialize variables:
○ num: Starting value for the elements (1).
○ top, bottom, left, right: Boundaries for filling the matrix in a spiral pattern.
○ While num is less than or equal to n * n:

■ Iterate from right to left, assigning num to each element in the top row.
■ Decrement right to move one column left.

■ Iterate from top to bottom, assigning num to each element in the left column.
■ Increment top to move to the next row.

■ Iterate from left to right, assigning num to each element in the bottom row.
■ Decrement bottom to move to the previous row.

■ Iterate from bottom to top, assigning num to each element in the right column.
■ Increment right to move to the next column.
○ Increment num for the next element.

Print the elements of the matrix in a tabular format.

Program:

import java.util.Scanner;
Page No: 32

public class AnticlockwiseSpiralMatrix {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int n = scanner.nextInt();

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

int num = 1;

int top = 0, bottom = n - 1, left = 0, right = n - 1;

while (num <= n * n) {

// Fill top row (right to left)

for (int i = right; i >= left; i--) {

matrix[top][i] = num++;

top++;

// Fill left column (top to bottom)

for (int i = top; i <= bottom; i++) {

matrix[i][left] = num++;

left++;

// Fill bottom row (left to right)

for (int i = left; i <= right; i++) {

matrix[bottom][i] = num++;

bottom--;
// Fill right column (bottom to top) Page No: 33

for (int i = bottom; i >= top; i--) {

matrix[i][right] = num++;

right--;

// Print the spiral matrix

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

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

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

System.out.println();

Variable Description:

n: The size of the square matrix.

matrix: A 2D integer array to store the elements of the spiral matrix.

num: A variable to keep track of the current number to be filled in the matrix.

top, bottom, left, right: Variables to define the boundaries for filling the matrix in a spiral pattern.
These boundaries are adjusted in each iteration of the main loop to control the filling process.

Sample Input/Output:

Input:

Enter the size of the square matrix: 4


Question13 Page No: 34

Given a square matrix, sort its non-boundary elements in ascending order while keeping the boundary
elements unchanged. After sorting, calculate the sum of the diagonal elements of the modified matrix.

Example:

Consider the following 4x4 matrix:

1234

5678

9 10 11 12

13 14 15 16

The non-boundary elements are:

67

10 11

After sorting these elements, the modified matrix becomes:

1234

5678

9 10 11 12

13 14 15 16

The sum of the diagonal elements in the modified matrix is 24 (1 + 8 + 16 + 5).

Algorithm:

● Read the size(M) of the square matrix input by the user.


● Check whether the size is greater than 3 or less than 10 or not.
● Create a copy of the matrix arr into a new 2D array copy_arr.
● Iterate through copy_arr and set boundary elements to 0.
● Create a 1D array sort to store non-boundary elements.
● Iterate through copy_arr and copy non-zero elements to sort.
● Sort the sort array using a sorting algorithm (e.g., bubble sort).
● Iterate through new_arr and:
○ For boundary elements, copy from arr.
○ For non-boundary elements, copy from the sorted sort array.
Page No: 35

● Initialize a variable sum to zero.


● Iterate through the new_arr and add the elements on the main diagonal and anti-diagonal to sum.
● Print the original matrix arr.
● Print the rearranged matrix new_arr.
● Print the sum of diagonal elements.

Program Code:

import java.util.Scanner;

class Sorting_Non_Boundary_Elements

public static void main(String args[])

System.out.println("Enter size of Matrix(M):");

Scanner sc=new Scanner(System.in);

int M=sc.nextInt(),arr[][]=new int[M][M],copy_arr[][]=new int[M][M];

if(M>3 && M<10)

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

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

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

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

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

for(int j=0;j<M;j++)
{

if(i==0 || i==M-1 || j==0 || j==M-1) Page No: 36

copy_arr[i][j]=0;

else

copy_arr[i][j]=arr[i][j];

int sort[]=new int[M*M-(2*M+(M-2)*2)],index=0;

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

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

if(copy_arr[i][j]!=0)

{sort[index]=copy_arr[i][j];

++index;}

index=0;

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

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

if(sort[j]>sort[j+1])

int temp=sort[j];
sort[j]=sort[j+1];

sort[j+1]=temp; Page No: 37

int new_arr[][]=new int[M][M];

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

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

if(i!=0 && i!=M-1 && j!=0 && j!=M-1)

{new_arr[i][j]=sort[index];

++index;

else

new_arr[i][j]=arr[i][j];

System.out.println("ORIGINAL MATRIX:");

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

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

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

}
System.out.println(" ");

} Page No: 38

System.out.println("REARRANGED MATRIX:");

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

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

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

System.out.println(" ");

int sum=0;

System.out.println("DIAGONAL ELEMENTS:");

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

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

if(i==j || M-1-i==j)

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

sum+=new_arr[i][j];

else

System.out.print("\t");

}
System.out.println(" ");

} Page No: 39

System.out.println("Sum of diagonal elements="+sum);

else

System.out.println("OUT OF RANGE");

Variable Description:

● M: Size of the square matrix (user input).


● arr: Original matrix (2D array).
● copy_arr: Temporary matrix for manipulation (2D array).
● sort: Array to store extracted non-boundary elements (1D array).
● new_arr: Rearranged matrix with sorted non-boundary elements (2D array)

Sample Input/Output:

Enter size of Matrix(M): 4

Enter elements in the matrix

9215

8 13 8 4

15 6 3 11

7 12 23 28

ORIGINAL MATRIX

9 2 1 5

8 13 8 4

15 6 3 11

7 12 23 28
REARRANGED MATRIX Page No: 40

9 2 1 5

8 3 6 4

15 8 13 11

7 12 23 8

DIAGONAL ELEMENTS:

9 5

3 6

8 13

7 8

Sum of Diagonal Elements=59

Question 14

Write a program to declare a matrix A[][] of order (M x N) where 'M' is the number of rows and
'N' is the number of columns such that the value of 'M' must be greater than 0 and less than 10 and
the value of 'N' must be greater than 2 and less than 6. Allow the user to input digits (0 - 7) only at
each location, such that each row represents an octal number.

2 3 1 (decimal equivalent of 1st row = 153 i.e. 2x82 + 3x81 + 1x80)

4 0 5 (decimal equivalent of 2nd row = 261 i.e. 4x82 + 0x81 + 5x80)

1 5 6 (decimal equivalent of 3rd row = 110 i.e. 1x82 + 5x81 + 6x80)

Example:Perform the following tasks on the matrix:

1. Display the original matrix.

2.Calculate the decimal equivalent for each row and display it.
Algorithm: Page No: 41

● Read the dimensions of the matrix, M and N, from the user. If M is greater than 10 or N is less than 2
or greater than 6, display the message: “OUT OF RANGE”.
● Read the elements of the matrix, ensuring their value is greater than 0 and less than 7.If not, then
break both the inner and outer loops and then display the message:“Invalid Input”.
● Iterate through each row of the matrix.
● For each row, initialize a sum variable to 0.
● Iterate through each element of the row:
● Calculate the decimal equivalent of the current element based on its position in the row
● Add the calculated decimal equivalent to the sum.
● Print the matrix and its corresponding decimal equivalent for each row.

Program Code:

import java.util.Scanner;

class ISC_2020

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter the value of (M)");

int M=sc.nextInt();

System.out.println("Enter the value of (N)");

int N=sc.nextInt();

if(M>0 && M<10 && N>2 && N<6)

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

int arr[][]=new int[M][N];

boolean flag=true;

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

for(int j=0;j<N;j++) Page No: 42

{arr[i][j]=sc.nextInt();

if(arr[i][j]>=8 || arr[i][j]<0)

{flag=false;

System.out.println("INVALID INPUT");

break;}

if(flag==false)

break;

if(flag==true)

System.out.println("FILLED MATRIX"+"\t"+"\t"+"\t"+"\t"+"\t"+"\t"+"DECIMAL
EQUIVALENT");

int sum=0;

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

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

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

sum+=arr[i][j]*Math.pow(8,(N-1)-j);

System.out.println(sum);

sum=0;
}

} Page No: 43

else

System.out.println("OUT OF RANGE.");

Variable Description:

M: Number of rows in the matrix.

N: Number of columns in the matrix.

arr: 2D array to store the matrix elements.

sum: Variable to store the decimal equivalent of a row.

i, j: Loop counters for iterating through the matrix.

Sample Input/Output:

Input:

Enter the value of (M): 1

Enter the value of (N): 3

Enter the elements of the matrix:

1 5 3

Output:

FILLED MATRIX DECIMAL EQUIVALENT

1 5 3 107

Question 15

Write a program to enter a string and check whether it is a snowball string or not.A snowball string is
one in which all the words are in ascending order of their lengths and also consecutive.
Algorithm: Page No: 44

● Read a string str from the user.


● Check if the last character of the string is a punctuation mark (!, ?, or .). If not, it's invalid input.
● Use a StringTokenizer to split the string into words based on whitespace.
● Get the length of the first word (len1).
● Iterate through the remaining words:
○ Compare the length of each word (len2) with len1 + 1.
○ If any word length doesn't differ by exactly 1 from the previous word, the string is not a
snowball string.

If all word lengths increase by 1 consecutively and the last character is punctuation, the string is a
snowball string. Otherwise, it's not.

Program:

import java.util.Scanner;

import java.util.StringTokenizer;

class SnowBall2

public static void main(String args[])

Scanner s= new Scanner(System.in);

System.out.println("Enter a string");

String str=s.nextLine();

char ch=str.charAt(str.length()-1);

if(ch=='!' || ch=='?' || ch=='.')

StringTokenizer obj= new StringTokenizer(str);

int len1=obj.nextToken().length(),len2=0,n=obj.countTokens();

boolean flg=true;

while(obj.hasMoreTokens()==true)
{

len2=obj.nextToken().length(); Page No: 45

if(len2!=len1+1)

System.out.println("This is not a snowball string");

flg=false;

break;

else

len1=len2;

len2=0;

if(flg==true)

System.out.println("This is a snowball string");

else

System.out.println("Invalid Input");

}}

Variable Description:

str: The input string entered by the user.

ch: The last character of the string.


obj: A StringTokenizer object used to split the string into words. Page No: 46

len1: The length of the first word.

len2: The length of the current word being compared.

n: The total number of words in the string.

flg: A flag variable to track if a non-consecutive word length is found (initially true).

Sample Input-Output:

Input 1 (Snowball String):

Enter a string: This is a snowball!

Output 1:

This is a snowball string

Question 16

Write a program to decode a caesar encryption. The Caesar cipher is a simple substitution cipher
where each letter in the message is shifted a fixed number of positions down the alphabet.

Algorithm:

● Read the encrypted string decode (uppercase letters only).


● Read the keyword key (uppercase letters only).
● Remove duplicate characters from the keyword to create a unique key string new_key.
● Construct the combined alphabet string s2 by:
● Appending characters from new_key.
● Appending remaining characters from the original alphabet string s1 that are not present in
new_key.
● Appending the remaining characters from s1 starting from the end (to handle keywords longer
than 26 letters).
● Iterate through each character in decode:
● If the character is a letter, find its corresponding position in s2.
● Use the corresponding position in s1 to retrieve the decrypted letter.
● Print the decrypted letter.
● If the character is not a letter, print it directly.

Program Code:

import java.util.Scanner;
class CeaserEncryption2 Page No: 47

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter a string to be decoded in UPPERCASE");

String decode=sc.nextLine();

System.out.println("Enter the keyword in UPPERCASE");

String key=sc.nextLine();

String s1="ABCDEFGHIJKLMNOPQRSTUVWXYZ",s2="",new_key="";

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

if(key.charAt(i)!=' ')

new_key+=key.charAt(i);

key=key.replace(key.charAt(i),' ');

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

if(i<new_key.length())

s2+=new_key.charAt(i);

else
{ Page No: 48

boolean flg=false;

char ch=s1.charAt(i-new_key.length());

for(int j=0;j<new_key.length();j++)

if(ch==new_key.charAt(j))

flg=true;

break;

if(flg==false)

s2+=ch;

for(int i=s1.length()-new_key.length();i<26;i++)

s2+=s1.charAt(i);

System.out.println("DECODED STRING:");

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

if(Character.isLetter(decode.charAt(i))==true)

for(int j=0;j<s1.length();j++)

if(decode.charAt(i)==s2.charAt(j))
System.out.print(s1.charAt(j)); Page No: 49

else

System.out.print(decode.charAt(i));

Variable Description:

● decode: The string that needs to be decoded, input by the user.


● key: The keyword provided by the user to create a substitution alphabet.
● s1: A string containing the original alphabet, i.e., "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
● s2: The substitution alphabet created using the unique characters from the key followed by
remaining characters from the original alphabet.
● new_key: A modified version of the key where duplicate characters are removed.
● flg: A boolean flag used to check if a character from the original alphabet (s1) is already
present in new_key.
● ch: A temporary variable used to hold characters while constructing the substitution alphabet
s2.
● i, j: Loop counters used for iterating through strings and performing operations

Sample Input/Output:

Input:

Enter a string to be decoded in UPPERCASE

LIVXEH IRUHV WR WKH WRROV

Enter the keyword in UPPERCASE

SECRET

Output:

DECODED STRING: ATTACK IS COMING SOON


Question 17 Page No:50

Write a program to input two words and check whether they are anagrams or not.Anagrams are words
or phrases that contain the same letters arranged differently, but with the same frequency of each
letter.

Algorithm:

● Read the first word s1 from the user.


● Read the second word s2 from the user.
● Convert both words to character arrays arr1 and arr2 for easier manipulation.
● Iterate through each character ch in arr1:
○ Check if ch exists in arr2.
■ If yes, set a flag flag to true.
○ Reset flag to false if no match is found in arr2.
○ If flag remains false after iterating through arr2 for a character, the words are not anagrams
(break the loop).
○ If the loop completes without breaking, both words have matching characters with the same
frequency, and they are anagrams. Otherwise, they are not anagrams.

Program:

import java.util.Scanner;

public class Anagram {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter first word");

String s1 = sc.nextLine();

char arr1[] = new char[s1.length()];

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

arr1[i] = s1.charAt(i);

System.out.println("Enter second word");

String s2 = sc.nextLine();

char arr2[] = new char[s2.length()];


Page No: 51

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

arr2[i] = s2.charAt(i);

boolean flag = false;

int no_of_same = 0;

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

char ch = arr1[i];

for (int j = 0; j < arr2.length; j++) {

if (ch == arr2[j]) {

flag = true;

break;

if (flag) {

flag = false;

++no_of_same;

continue;

} else {

System.out.println("These words are not anagrams");

break;

if (no_of_same == s1.length()) {

System.out.println("These words are anagrams");


}}} Page No: 52

Variable Description:

s1: The first word entered by the user.

s2: The second word entered by the user.

arr1: Character array representation of s1.

arr2: Character array representation of s2.

isAnagram: Flag indicating if the words are anagrams (true) or not (false).

noOfSame: Counts the number of matching characters found between the words.

Sample Input/Output:

Input:

Enter first word

listen

Enter second word

silent

Output:

These words are anagrams

Question 18

Write a program to enter two strings and calculate their hamming distance. The Hamming distance is
the number of positions at which the corresponding characters in two strings differ.

Algorithm:

● Read the first string s1 from the user.


● Read the second string s2 from the user.
● Verify that both strings have the same length. If not, the Hamming distance cannot be calculated
meaningfully.
● Initialize a variable dist to 0 to store the Hamming distance.
● Iterate through each character position in both strings:
○ Compare the characters at the same position in s1 and s2.
○ If the characters differ, increment dist.
Page No: 53

Print the calculated Hamming distance.

Program Code:

import java.util.Scanner;

public class Hamming_Distance {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter first string");

String s1 = sc.nextLine();

System.out.println("Enter second string");

String s2 = sc.nextLine();

if (s1.length() == s2.length()) {

int dist = 0;

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

if (s1.charAt(i) != s2.charAt(i)) {

dist++;

System.out.println("Hamming distance=" + dist);

} else {

System.out.println("Strings must have the same length to calculate Hamming distance.");

}}}

Variable Description:

s1: The first string entered by the user.


s2: The second string entered by the user. Page No: 54

dist: Variable to store the calculated Hamming distance.

Sample Input-Output:

Input (Equal Length):

Enter first string

abcde

Enter second string

bcdef

Output :

Hamming distance=1

Question 19

Write a program to enter a sentence and arrange the words in lexicographical order. For Example:

Input: zebra dog cat elephant

Output:cat dog elephant zebra

Algorithm:

● Read a string str from the user using Scanner.


● Use StringTokenizer to split the string str into individual words and store them in a String array arr.
● Use nested loops to iterate through adjacent pairs of words in arr.
● For each pair arr[j] and arr[j+1]:
○ Compare them using compareToIgnoreCase to handle case-insensitive sorting.
○ If arr[j] is lexicographically greater than arr[j+1]:
■ Perform a swap:
■ Store arr[j] in a temporary variable temp.
■ Update arr[j] with the value of arr[j+1].
■ Update arr[j+1] with the value of temp.

Program Code:

import java.util.Scanner;
Page No: 55

import java.util.StringTokenizer;

class Swap_words_Lexographically {

public static void main(String args[]) {

System.out.println("Enter a string");

Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

// Split string into words using StringTokenizer

StringTokenizer st = new StringTokenizer(str, ",");

String arr[] = new String[st.countTokens()]; // Create array to store words

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

arr[i] = st.nextToken(); // Store each word in the array

// Iterate through adjacent word pairs

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

for (int j = 0; j < arr.length - i - 1; j++) {

// Compare lexicographically (case-insensitive)

if (arr[j].compareToIgnoreCase(arr[j + 1]) > 0) {

String temp = arr[j]; // Store word in temporary variable

arr[j] = arr[j + 1]; // Swap positions

arr[j + 1] = temp; // Update word in swapped position

// Print the sorted words


for (int i = 0; i < arr.length; i++) { Page No: 56

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

Variable Description:

● str: The input string containing comma-separated words.


● sc: A Scanner object to read user input.
● st: A StringTokenizer object to split the string into words.
● arr: A String array to store the individual words.
● i: Loop counter for outer loop (number of passes).
● j: Loop counter for inner loop (comparing adjacent words).
● temp: A temporary variable to store a word during swapping.

Sample Input/Output:

Input:

Enter a string

apple, banana, Cherry

Output:

apple Banana Cherry

Question 20

An encoded text is decoded by adding two in ASCII the code in each alphabet of encoded text other
than alphabets are ignored and will not be taken into account. For example, the decoded character of
a is C for B is D for C is E. For X is Z. For Y is A, and for Z is B. Whenever KK appears in encoded
text Will be taken as one blank space, if more than one pair of KK is present in the encoded text will
be taken as 1 blank speed and will be taken from beginning. Write a programme to read an encoded
text in capital.( If not, then convert) maximum of 200 characters only from input. Assume there is no
space present in the encoded text and print its decoded text format The first letter of each word
Should be in capital and the rest be in small.( Any numeric data present in the encoded text will be
Page No: 57

ignored. That is, it should not be present in the decoded text .).Test your program for the following
data:

Algorithm:

● Take input string mstring from the user (text to decode) and convert it to uppercase.
● If the length of mstring exceeds 200, display an error message and terminate the program.
● Remove all non-alphabetic characters (anything not between 'A' and 'Z') and store the result in
● For each character in nstring:If two consecutive 'K' characters appear, replace them with a space and
skip the second 'K'.Otherwise, shift the character two positions forward in the alphabet,
wrapping back to 'A' if the value exceeds 'Z'.
● Append the decoded character to tstring.
● Tokenize tstring using delimiters such as spaces, periods, commas, and exclamation marks.
● For each tokenized word:Print the first character in uppercase and the rest in lowercase.Add a space
between words.
● Display the decoded and formatted string.

Program Code:

import java.util.*;

public class HelloWorld {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the text to be decoded in capital:");

String mstring = sc.nextLine().trim().toUpperCase();

// Validate input length

if (mstring.length() > 200) {

System.out.println("ERROR: String too big");

return;

}
StringBuilder nstring = new StringBuilder(); Page No: 58

// Step 1: Filter alphabetic characters only

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

char ch = mstring.charAt(i);

if (ch >= 'A' && ch <= 'Z') {

nstring.append(ch);

StringBuilder tstring = new StringBuilder();

// Step 2: Decode the filtered string

for (int j = 0; j < nstring.length(); j++) {

if (j + 1 < nstring.length() && nstring.charAt(j) == 'K' && nstring.charAt(j + 1) == 'K') {

tstring.append(' '); // Replace 'KK' with a space

j++; // Skip the next 'K'

} else {

char ch = nstring.charAt(j);

int x = ch + 2; // Shift by 2

if (x > 'Z') {

x -= 26; // Wrap around if beyond 'Z'

tstring.append((char) x);
} Page No: 59

// Step 3: Tokenize and format the decoded string

StringTokenizer st = new StringTokenizer(tstring.toString());

StringBuilder finalString = new StringBuilder();

while (st.hasMoreTokens()) {

String word = st.nextToken();

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

if (i == 0) {

finalString.append(word.charAt(i)); // First letter remains uppercase

} else {

finalString.append(Character.toLowerCase(word.charAt(i))); // Rest lowercase

finalString.append(' '); // Add space between words

// Print the final decoded text

System.out.println("Decoded Text:");

System.out.println(finalString.toString().trim()); // Remove trailing space

Variable Description:
● mstring: Input string from the user, converted to uppercase. Page No: 60
● nstring: Filtered version of mstring, containing only alphabetic characters.
● tstring: The decoded string after applying the transformation logic.
● x: The ASCII value of a character, used for shifting operations.
● xa: The character corresponding to the shifted ASCII value.
● st: A StringTokenizer object used to break tstring into words.
● u: Each word extracted from tstring for formatting.

Sample Input/Output:

Input:

Enter the text to be decoded in capital:

KKYJQQPIUJQQVJKKDGZNKKVGZG

Output:

Decoded Text:

Ansur Work And Live

Question 21

Given a time in numbers we can convert it into words.

For example : 5 : 00 —— five o’clock

5 : 10 —— ten minutes past five

5 : 15 —— quarter past five

5 : 30 —— half past five

5 : 40 —— twenty minutes to six

5 : 45 —— quarter to six

5 : 47 —— thirteen minutes to six

Write a program which first inputs two integers, the first between 1 and 12 (both inclusive) and
second between 0 and 59 (both inclusive) and then prints out the time they represent, in words. Your
program should follow the format of the examples above.

1. INPUT :

TIME : 3,0
Page No: 61

OUTPUT : 3 : 00 Three o’ clock

2. INPUT :

TIME : 7,29

OUTPUT : 7 : 29 Twenty nine minutes past seven

Algorithm:

● Input the hours (h) and minutes (m) from the user.
● Check if the input is valid: hours must be between 1 and 12, and minutes must be between 0 and 59.
If invalid, display "Invalid input!" and exit.
● Define an array word[] containing the word representation of numbers from 1 to 29.
● Determine the correct plural form for "minute(s)". If m is 1 or 59, set plu as "minute". Otherwise, set
plu as "minutes".
● Calculate the next hour:
● If h is 12, set a to word[1].
● Otherwise, set a to word[h + 1].

Determine the time in words:

● If m is 0, display "<hour> o'clock".


● If m is 15, display "quarter past <hour>".
● If m is 30, display "half past <hour>".
● If m is 45, display "quarter to <next hour>".
● If m is less than 30, display "<minutes> <plu> past <hour>".
● If m is greater than 30, display "<60 - minutes> <plu> to <next hour>".
● Output the time in the format "<hour>:<minute> ----- <time in words>".

Program Code:

import java.util.*;

public class timeinwords

public static void main(String args[])

{
Page No: 62

Scanner sc= new Scanner(System.in);

System.out.println("enter hours");

int h=sc.nextInt();

System.out.println("enter minutes");

int m=sc.nextInt();

if((h>=1&&h<=12)&&(m>=0&&m<=59))

String word[]={"","one ","two ","three ","four

","five ","six ","seven ","eight ","nine ","ten "," eleven

"," twelve ","

thirteen","fourteen","fifteen","sixteen","seventeen","e

eighteen","nineteen","twenty","twenty one","twenty

two","twenty three","twenty four","twenty

five","twenty six","twenty seven","twenty

eight","twenty nine"};

String plu,a;

if(m==1||m==59)

plu="minute";

else

plu="minutes";

if(h==12)

a=word[1];

else

a=word[h+1];
System.out.print("output: \n"+h+":"+m+"-----"); Page No: 63

if(m==0)

System.out.println(word[h]+" o'clock");

else if(m==15)

System.out.println("quarter past "+word[h]);

else if(m==30)

System.out.println("half past "+word[h]);

else if(m==45)

System.out.println("quarter to"+a);

else if(m<30)

System.out.println(word[m]+" "+plu+" past"+

word[h]);

else

System.out.println(word[60-m]+" "+plu+" to

"+a);

else

System.out.println("invalid input!");

Variable Description:

● h: an integer representing the hour input (1 to 12)


● m: an integer representing the minute input (0 to 59)
● word[]: a string array containing the word representation of numbers from 1 to 29
● plu: a string representing the correct pluralization of "minute" or "minutes"
● a: a string representing the word for the next hour if m is greater than 30
Sample Input/Output: Page No: 64

Input:

Enter hours: 9

Enter minutes: 20

Output:

9:20 ----- twenty minutes past nine

Question 22

Question: Write a program to accept 2 dates in the string format dd/mm/yyyy and find the difference
in days between the 2 dates.

Example:

INPUT: Date 1 : 20/12/2012 Date 2 : 11/02/2013

OUTPUT: Difference = 54 days

The program should include the part for validating the inputs namely the date and the day on 1 st
January of that year.

Algorithm:

● Input the two dates in the format dd/mm/yyyy.


● Extract day, month, and year from both dates using string manipulation.
● Define a function isLeap(y) to check if the year is a leap year.
● Define a function dateValidate(d, m, y) to validate the date.
● Check if the month is between 1 and 12.
● Check if the day is valid for the given month.
● Ensure the year is between 1000 and 9999.
● Define a function dayno(d, m, y) to calculate the day number for the given date.
● Add the number of days for all the months before the given month.
● Add the day number.
● Add the number of days for all the years from 1000 to the given year, considering leap years.
● If both dates are valid, calculate the day numbers for both dates using the dayno function.
● Calculate the absolute difference between the two day numbers and output the result.
● If any date is invalid, output "Invalid Date".

Program Code:

// The class Date_Difference inputs 2 dates and finds


the difference between them Page No: 65

import java.util.*;

class Date_Difference

int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

//function for checking for Leap Year

int isLeap(int y)

if((y%400==0) || ((y%100!=0)&&(y%4==0)))

return 29;

else

return 28;

//function for checking date validation

boolean dateValidate(int d, int m, int y)

month[2]=isLeap(y);

if(m<1 || m>12 || d<1 || d>month[m] || y<1000

|| y>9999)

return false;

else

return true;

//function for finding day number from year = 1 till the

inputted year
int dayno(int d, int m, int y) Page No: 66

int dn=0;

month[2]=isLeap(y);

for(int i=1;i<m;i++)

dn=dn+month[i];

dn=dn+d;

for(int i=1000;i<y;i++)

if(isLeap(i)==29)

dn=dn+366;

else

dn=dn+365;

return dn;

public static void main(String args[])

Scanner sc= new Scanner(System.in);

Date_Difference ob=new Date_Difference();

System.out.print("Enter the 1st date in

(dd/mm/yyyy) format: ");

String date1=sc.nextLine().trim();
int p,q; Page No: 67

//Extracting the day

p=date1.indexOf("/");

int d1=Integer.parseInt(date1.substring(0,p));

//Extracting the month

q=date1.lastIndexOf("/");

int m1=Integer.parseInt(date1.substring(p+1,q));

//Extracting the year

int y1=Integer.parseInt(date1.substring(q+1));

System.out.print("Enter the 2nd date in

(dd/mm/yyyy) format: ");

String date2=sc.nextLine().trim();

p=date2.indexOf("/");

int d2=Integer.parseInt(date2.substring(0,p));

q=date2.lastIndexOf("/");

int m2=Integer.parseInt(date2.substring(p+1,q));

int y2=Integer.parseInt(date2.substring(q+1));

//Validating both the dates

if(ob.dateValidate(d1,m1,y1)==true &&

ob.dateValidate(d2,m2,y2)==true)

int a=ob.dayno(d1,m1,y1);

int b=ob.dayno(d2,m2,y2);

System.out.print("Output : Difference =

"+Math.abs(a-b)+" days.");
} Page No: 68

else

System.out.println("Invalid Date");

Variable Description:

● month[]: An array that stores the number of days in each month.


● isLeap(y): Function that returns 29 if the year is a leap year, otherwise 28.
● dateValidate(d, m, y): Function that checks if the given date is valid.
● dayno(d, m, y): Function that calculates the day number of the given date from year 1.
● p: Integer to store the index of / in the date string for extracting the day.
● q: Integer to store the index of the last / in the date string for extracting the year.
● d1, m1, y1: Integers to store the day, month, and year of the first date.
● d2, m2, y2: Integers to store the day, month, and year of the second date.
● a: Integer to store the day number of the first date.
● b: Integer to store the day number of the second date.

Sample Input/Output:

Enter the 1st date in (dd/mm/yyyy) format: 12/05/2020


Enter the 2nd date in (dd/mm/yyyy) format: 15/08/2023

Output
Output: Difference = 1194 days.

Question 23

Write a program to accept a date in the string format dd/mm/yyyy. Check whether the date entered is
valid or not. If it is valid, then input a certain number of days. Then calculate and print the future date
after adding the given number of days if the future date is valid. If the date entered is invalid, then
display a proper error message.

Example: INPUT: Date : 07 / 04 / 2013 Enter Number of days after : 7

OUTPUT: Entered Date : 07 / 04 / 2013 Future Date : 14 / 04 / 2013

Algorithm:

Algorithm
● Input a date in the format dd/mm/yyyy. Page No: 69
● Extract the day (d), month (m), and year (y) from the date string.
● Define an array month[] to store the number of days in each month, and set February's days to
28 initially.
● Check if the entered year is a leap year using the formula:
○ If a year is divisible by 400, or divisible by 4 but not by 100, it's a leap year. In that case,
set February to 29 days.
● Validate the date:
○ Ensure the month is between 1 and 12.
○ Ensure the day is valid for the given month.
○ Ensure the year is between 0 and 9999.
● If the date is invalid, print "Invalid Date".
● If the date is valid, input the number of days (days) after which the future date is to be
calculated.
● Use a loop to increment the day by one for each iteration until the required number of days is
reached:
○ If the day exceeds the number of days in the current month, reset the day to 1 and
increment the month.
○ If the month exceeds 12, reset the month to 1 and increment the year.
○ If the year changes, check if it's a leap year and adjust the number of days in February
accordingly.
● Print the future date after the loop completes.

Program Code:

import java.util.*;

class FutureDate

public static void main(String args[])

Scanner sc= new Scanner(System.in);

int

month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

System.out.print("Enter the date in (dd/mm/yyyy)

format: ");
String date=sc.nextLine().trim(); Page No: 70

int p,q,count=0;

p=date.indexOf("/");

int d=Integer.parseInt(date.substring(0,p));

q=date.lastIndexOf("/");

int m=Integer.parseInt(date.substring(p+1,q));

int y=Integer.parseInt(date.substring(q+1));

System.out.println("Entered Date: "+date);

if((y%400==0) || ((y%100!=0)&&(y%4==0))) //

Checking for leap year

month[2]=29;

if(m<0 || m>12 || d<0 || d>month[m] || y<0 ||

y>9999) // Performing Date Validation

System.out.println("Invalid Date");

else

System.out.print("Enter number of days after

which future date is to be found: ");

int days=sc.nextInt();

while(count<days)

d++;

count++;
/* If day exceeds the maximum days of a Page No: 71

month then day should start from 1

and month should increase */

if(d>month[m])

d=1;

m++;

/* If month exceeds 12 then month should

start from 1

and year should increase */

if(m>12)

m=1;

y++;

if((y%400==0) || ((y%100!=0)&&(y%4==0)))

month[2]=29;

else

month[2]=28;

System.out.println("Future Date :

"+d+"/"+m+"/"+y);
} Page No: 72

Variable Description:

● month[]: An array storing the number of days in each month.


● p: Integer used to store the position of the first / in the input date string.
● q: Integer used to store the position of the last / in the input date string.
● d: Integer representing the day of the input date.
● m: Integer representing the month of the input date.
● y: Integer representing the year of the input date.
● count: Integer used to count the number of days added.
● days: Integer input by the user to specify how many days into the future the date should be calculated.

Sample Input/Output:

Input:

Enter the date in (dd/mm/yyyy) format: 28/02/2024


Enter number of days after which future date is to be found: 10

Output:
Future Date: 9/3/2024

Question 24

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. Test your program with the following data and some random data:

Example 1 INPUT: DAY NUMBER: 255 YEAR: 2018 DATE AFTER (N DAYS): 22

OUTPUT: DATE: 12 TH SEPTEMBER, 2018 DATE AFTER 22 DAYS: 4 TH OCTOBER, 2018

Example 2 INPUT: DAY NUMBER: 360 YEAR: 2018 DATE AFTER (N DAYS): 45

OUTPUT: DATE: 26 TH DECEMBER, 2018 DATE AFTER 45 DAYS: 9 TH FEBRUARY, 2019


Algorithm: Page No: 73

Leap Year Check (isLeap function):

● Take the year as input.


● If the year is divisible by 400, it is a leap year.
● If the year is divisible by 4 but not 100, it is also a leap year.
● Otherwise, it is not a leap year.

Postfix Calculation (postfix function):

● Take the day number as input.


● Find the last digit of the day number using modulo operation (n % 10).
● If the day ends with 1, add "ST" unless it's 11, then add "TH".
● If the day ends with 2, add "ND" unless it's 12, then add "TH".
● If the day ends with 3, add "RD" unless it's 13, then add "TH".
● For all other cases, add "TH".

Finding Date from Day Number (findDate function):

● Given a day number and year, calculate the exact date (day, month, and year).
● Initialize an array for days in each month (D[]), considering leap years.
● Subtract the days in each month from the input day number until the day number fits into a month.
● Print the result in the format day postfix month, year.

Future Date Calculation (future function):

● Take the current day number, year, and the number of days to be added as input.
● Add the number of days to the current day number.
● If the day exceeds the number of days in the year, subtract the total days in the current year and move
to the next year, adjusting for leap years.
● Repeat until the day number is within the valid range for the current year.
● Call the findDate function to print the future date.

Program Code:

/* The class ISC2019_Q1 inputs a day number, year and number oand prints the current date and the
future date */

import java.util.*;

class ISC2019_Q1
Page No: 74

int isLeap(int y) // function to check for leap year and return {

if((y%400 == 0) || (y%100 != 0 && y%4 == 0))

return 366;

else

return 365;

String postfix(int n) // function to find postfix of the number

int r = n%10;

if(r == 1 && n != 11)

return "ST";

else if(r == 2 && n != 12)

return "ND";

else if(r == 3 && n != 13)

return "RD";

else

return "TH";

void findDate(int d, int y) // function to find the date from da {

int D[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

String MO[] = {"", "JANUARY", "FEBRUARY", "MARCH", "APRIL "AUGUST",


"SEPTEMBER", "OCTOBER", "NOVEMBER if(isLeap(y)==366)

{
D[2] = 29; Page No: 75

int m = 1;

while(d > D[m])

d = d - D[m];

m++;

System.out.println(d+postfix(d)+" "+MO[m]+", "+y);

void future(int d, int y, int n) // function to find future date

int max = isLeap(y);

d = d + n;

if(d>max)

d = d - max;

y++;

findDate(d,y);

public static void main(String args[])

ISC2019_Q1 ob = new ISC2019_Q1();


Scanner sc = new Scanner(System.in); Page No: 77

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

int day = sc.nextInt();

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

int year = sc.nextInt();

int max = ob.isLeap(year);

if(day > max)

System.out.println("DAY NUMBER OUT OF RANGE");

else if(year<1000 || year>9999)

System.out.println("YEAR OUT OF RANGE");

else

System.out.print("Enter the number of days after between int n = sc.nextInt();

if(n<1 || n>100)

System.out.println("DATE AFTER (N DAYS) OUT OF RANG }

else

System.out.print("DATE :\t\t\t");

ob.findDate(day,year);

System.out.print("DATE AFTER "+n+" DAYS :\t");


ob.future(day,year,n); Page No: 78

}}}}

Variable Description:

day (int) – The day number of the year (e.g., 1 represents January 1st, 365 or 366 represents
December 31st).

year (int) – The year (should be between 1000 and 9999).

n (int) – The number of days to be added to the current day.

D[] (int[]) – An array storing the number of days in each month, considering leap years.

MO[] (String[]) – An array storing the names of months for display (e.g., January, February, etc.).

r (int) – The last digit of the day number to determine the correct postfix (ST, ND, RD, TH).

m (int) – The month number (1 for January, 12 for December).

d (int) – The day of the month after calculating from the day number.

Sample Input/Output:

Input : Enter the day number: 100


Enter the year: 2024
Enter the number of days after which future date is to be found: 200

Output : DATE: 10TH APRIL, 2024


DATE AFTER 200 DAYS: 27TH OCTOBER, 2024

Question 25

Write a program to accept the year, month and the weekday name of the 1st day of that month and
generate its calendar. Example:INPUT Year:2016 Month:February 1st day of February : Monday

OUTPUT:

Example:INPUT

Year:2016

Month:Feburary

1st day of February : Monday


OUTPUT : Page No: 79

---------------------------------------------------------

February 2016

---------------------------------------------------------

SUN MON TUE WED THU FRI SAT

----------------------------------------------------------

1 2 3 4 5 6

--------------------------------------------------------

7 8 9 10 11 12 13

--------------------------------------------------------

14 15 16 17 18 19 20

---------------------------------------------------------

21 22 23 24 25 26 27

---------------------------------------------------------

28 29

---------------------------------------------------------

Algorithm:

● Year (y)
● Month name (mname)
● Weekday name of the 1st day (wname)
● Use a function findMaxDay(mname, y) to return the number of days in the month:
○ For February, check if it’s a leap year and set the number of days to 29, otherwise, set it to 28.
○ For other months, return the standard number of days (31 for January, 30 for April, etc.).
Page No: 80

● Use a function findDayNo(wname) to convert the weekday name into a corresponding number (0 for
Sunday, 1 for Monday, etc.).
● Use a function fillCalendar(max, f, mname, y) to create a 2D array for the calendar.
○ max is the number of days in the month.
○ f is the weekday number of the 1st day of the month.
● Start filling the calendar from the correct weekday.
● If the month doesn’t fit into 5 rows, adjust the calendar to make sure all days are displayed properly.
● Use a function printCalendar(A, mname, y) to print the calendar.
● Display the calendar in tabular format with weekdays at the top and days of the month below.
● Display the month and year at the top, followed by the days of the week (Sunday, Monday, etc.).
● Print the calendar in a grid with days placed correctly according to the starting weekday.

Program Code:

* The class CalendarProgram inputs a year, month and the weekdof the 1st day of that month and
generates its calendar */

import java.util.*;

class CalendarProgram

//Function to match the given month and return its maximum d int findMaxDay(String mname, int y)

String months[] = {"","January", "February", "March", "April", "July", "August", "September",


"October", "Novem int D[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

if((y%400==0) || ((y%100!=0)&&(y%4==0)))

D[2]=29;

int max = 0;

for(int i=1; i<=12; i++)

if(mname.equalsIgnoreCase(months[i]))
Page No: 81

max = D[i]; //Saving maximum day of given month

} return max;

//Function to match the given weekday name and return its we int findDayNo(String wname)

String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday "Saturday"};

int f = 0;

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

if(wname.equalsIgnoreCase(days[i]))

f = i; //Saving week day no. given day (e.g. '0' for Sunday }

return f;

//Function for creating the calendar

void fillCalendar(int max, int f, String mname, int y)

int A[][] = new int[6][7];

int x = 1, z = f;

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

{
for(int j=f; j<7; j++) Page No: 82

if(x<=max)

A[i][j] = x;

x++;

}}

f = 0;

for(int j=0; j<z; j++) //Adjustment to bring last (6th) row ele {

A[0][j]=A[5][j];

printCalendar(A, mname, y); //Calling function to print the ca }

//Function for printing the calendar

void printCalendar(int A[][], String mname, int y)

System.out.println("\n\t------------------------------------------------- System.out.println("\t\t\t
"+mname+" "+y);

System.out.println("\t----------------------------------------------------
System.out.println("\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSA
System.out.println("\t----------------------------------------------------

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

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

if(A[i][j]!=0)
System.out.print("\t "+A[i][j]); Page No: 83

else

System.out.print("\t ");

System.out.println("\n\t---------------------------------------------- }

public static void main(String args[])

CalendarProgram ob = new CalendarProgram();

Scanner sc = new Scanner(System.in);

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

int y = sc.nextInt();

System.out.print("Enter the month name (e.g. January) : ");

String mname = sc.next();

System.out.print("Enter the week day name (e.g. Sunday) of String wname = sc.next();

int max = ob.findMaxDay(mname,y);

int f = ob.findDayNo(wname);

ob.fillCalendar(max,f,mname,y);

Variable Description:

● y: The year (integer, 4-digit).


● mname: The name of the month (string, e.g., "January").
● wname: The name of the weekday for the 1st day of the month (string, e.g., "Sunday").
● D[]: Array containing the number of days in each month (adjusted for leap years).
Page No: 84

● days[]: Array containing the names of the days of the week (Sunday, Monday, etc.).
● A[][]: 2D array to store the calendar (6 rows for weeks, 7 columns for days).
● max: The maximum number of days in the given month.
● f: The weekday number (0 for Sunday, 1 for Monday, etc.) of the 1st day of the month.

Sample Input/Output:

Input:

Enter the year: 2023

Enter the month name (e.g., January): March

Enter the weekday name (e.g., Sunday) of the 1st day: Wednesday

Output:

--------------------------------------------------------

MARCH 2023

--------------------------------------------------------

SUN MON TUE WED THU FRI SAT

--------------------------------------------------------

1 2 3 4

--------------------------------------------------------

5 6 7 8 9 10 11

--------------------------------------------------------

12 13 14 15 16 17 18

--------------------------------------------------------

19 20 21 22 23 24 25

--------------------------------------------------------

26 27 28 29 30 31

--------------------------------------------------------

You might also like