My Computer Science Project
My Computer Science Project
Computer science
Assignment file
Name: TEJAS KESARWANI
Class: xii - ‘A’
Uid:
Index no.:
INDEX
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
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;
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.
6.Compare the sorted strings. If they are identical, the input number is a vampire number.
Sample Input/Output:
Input: 1260
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
Algorithm:
2. Check if the input number is less than or equal to zero (non-positive). If so, it's not a Hamming
. number .
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.
Program Code:
class HammingNumber
static int n;
int num=sc.nextInt();
n=num;
if(isHamming(n)==true)
else
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:
n: A static variable to hold the original input number (not used in the current logic but present in the
code).
Sample Input/Output:
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:
Program Code:
import java.util.Scanner;
class BouncyNumber Page No: 12
System.out.println("Enter a number");
for(int i=0;i<Integer.toString(num).length();i++)
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;
else
Variable Descriptions:
Sample Input/Output:
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:
import java.util.Scanner;
return;
isGoldbach = true;
break;
if (!isGoldbach) {
}
} Page No: 15
if (n <= 1) {
return false;
if (n <= 3) {
return true;
if (n % 2 == 0 || n % 3 == 0) {
return false;
if (n % i == 0 || n % (i + 2) == 0) {
return false;
return true;
Variable Description:
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:
● Round 1: 1, 3, 5, 7, 9
● Round 2: 1, 3, 7, 9
● Round 3: 1, 7
● Round 4: 7
Algorithm:
Program Code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
numbers.add(i);
int i = 1;
int index = 0;
numbers.remove(index);
i++;
System.out.println("Lucky numbers in the range " + start + " to " + end + ": " + numbers.get(0));
Input:
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.
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;
m = mm;
n = nn;
void accept() {
arr[i][j] = sc.nextInt();
return ob;
void display() {
System.out.print(arr[i][j] + "\t");
System.out.println(" ");
}
} Page No: 20
if (columns1 != rows2) {
return;
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
Sample Input/Output:
Input:
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
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.
Program Code:
import java.util.Scanner;
System.out.println("Enter n");
int n = sc.nextInt();
arr[i][j] = sc.nextDouble();
return;
} Page No: 23
double rowSum = 0;
rowSum += arr[i][j];
isDoublyMarkov = false;
break;
double colSum = 0;
colSum += arr[i][j];
isDoublyMarkov = false;
break;
} Page No: 24
if (isDoublyMarkov) {
} else {
} else {
Variable Description:
Sample Input:
Enter n:
0.3
0.3
0.2
0.5
0.3
0.5
0.1
0.4
Output:
Question 10
Write a program to create a spiral matrix using the elements which are input by the user.
Algorithm:
■ 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.
Program:
import java.util.Scanner;
int n = scanner.nextInt();
scanner.close();
if (n < 3) {
return;
System.out.printf("%-4d", matrix[i][j]);
System.out.println();
int num = 1;
matrix[top][i] = num++;
top++;
matrix[i][right] = num++;
}
right--; Page No: 28
matrix[bottom][i] = num++;
bottom--;
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:
Program:
import java.util.Scanner;
int n = scanner.nextInt();
matrix[i][j] = scanner.nextInt();
rotateMatrix(matrix);
System.out.println("Rotated Matrix:");
System.out.println();
} Page No: 30
int n = matrix.length;
matrix[j][n - 1 - i] = temp;
}}}}
Variable Description:
Sample Input/Output:
Input:
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:
Program:
import java.util.Scanner;
Page No: 32
int n = scanner.nextInt();
int num = 1;
matrix[top][i] = num++;
top++;
matrix[i][left] = num++;
left++;
matrix[bottom][i] = num++;
bottom--;
// Fill right column (bottom to top) Page No: 33
matrix[i][right] = num++;
right--;
System.out.println();
Variable Description:
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:
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:
1234
5678
9 10 11 12
13 14 15 16
67
10 11
1234
5678
9 10 11 12
13 14 15 16
Algorithm:
Program Code:
import java.util.Scanner;
class Sorting_Non_Boundary_Elements
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++)
{
copy_arr[i][j]=0;
else
copy_arr[i][j]=arr[i][j];
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];
for(int i=0;i<M;i++)
for(int j=0;j<M;j++)
{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
else
System.out.println("OUT OF RANGE");
Variable Description:
Sample Input/Output:
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
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.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
int M=sc.nextInt();
int N=sc.nextInt();
boolean flag=true;
for(int i=0;i<M;i++)
{
{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:
Sample Input/Output:
Input:
1 5 3
Output:
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
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
System.out.println("Enter a string");
String str=s.nextLine();
char ch=str.charAt(str.length()-1);
int len1=obj.nextToken().length(),len2=0,n=obj.countTokens();
boolean flg=true;
while(obj.hasMoreTokens()==true)
{
if(len2!=len1+1)
flg=false;
break;
else
len1=len2;
len2=0;
if(flg==true)
else
System.out.println("Invalid Input");
}}
Variable Description:
flg: A flag variable to track if a non-consecutive word length is found (initially true).
Sample Input-Output:
Output 1:
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:
Program Code:
import java.util.Scanner;
class CeaserEncryption2 Page No: 47
String decode=sc.nextLine();
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:
Sample Input/Output:
Input:
SECRET
Output:
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:
Program:
import java.util.Scanner;
String s1 = sc.nextLine();
arr1[i] = s1.charAt(i);
String s2 = sc.nextLine();
arr2[i] = s2.charAt(i);
int no_of_same = 0;
char ch = arr1[i];
if (ch == arr2[j]) {
flag = true;
break;
if (flag) {
flag = false;
++no_of_same;
continue;
} else {
break;
if (no_of_same == s1.length()) {
Variable Description:
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:
listen
silent
Output:
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:
Program Code:
import java.util.Scanner;
String s1 = sc.nextLine();
String s2 = sc.nextLine();
if (s1.length() == s2.length()) {
int dist = 0;
if (s1.charAt(i) != s2.charAt(i)) {
dist++;
} else {
}}}
Variable Description:
Sample Input-Output:
abcde
bcdef
Output :
Hamming distance=1
Question 19
Write a program to enter a sentence and arrange the words in lexicographical order. For Example:
Algorithm:
Program Code:
import java.util.Scanner;
Page No: 55
import java.util.StringTokenizer;
class Swap_words_Lexographically {
System.out.println("Enter a string");
Variable Description:
Sample Input/Output:
Input:
Enter a string
Output:
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.*;
return;
}
StringBuilder nstring = new StringBuilder(); Page No: 58
char ch = mstring.charAt(i);
nstring.append(ch);
} else {
char ch = nstring.charAt(j);
int x = ch + 2; // Shift by 2
if (x > 'Z') {
tstring.append((char) x);
} Page No: 59
while (st.hasMoreTokens()) {
if (i == 0) {
} else {
System.out.println("Decoded Text:");
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:
KKYJQQPIUJQQVJKKDGZNKKVGZG
Output:
Decoded Text:
Question 21
5 : 45 —— quarter 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
2. INPUT :
TIME : 7,29
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].
Program Code:
import java.util.*;
{
Page No: 62
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))
thirteen","fourteen","fifteen","sixteen","seventeen","e
eighteen","nineteen","twenty","twenty one","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)
else if(m==30)
else if(m==45)
System.out.println("quarter to"+a);
else if(m<30)
word[h]);
else
System.out.println(word[60-m]+" "+plu+" to
"+a);
else
System.out.println("invalid input!");
Variable Description:
Input:
Enter hours: 9
Enter minutes: 20
Output:
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:
The program should include the part for validating the inputs namely the date and the day on 1 st
January of that year.
Algorithm:
Program Code:
import java.util.*;
class Date_Difference
int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int isLeap(int y)
if((y%400==0) || ((y%100!=0)&&(y%4==0)))
return 29;
else
return 28;
month[2]=isLeap(y);
|| y>9999)
return false;
else
return true;
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;
String date1=sc.nextLine().trim();
int p,q; Page No: 67
p=date1.indexOf("/");
int d1=Integer.parseInt(date1.substring(0,p));
q=date1.lastIndexOf("/");
int m1=Integer.parseInt(date1.substring(p+1,q));
int y1=Integer.parseInt(date1.substring(q+1));
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));
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:
Sample Input/Output:
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.
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
int
month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
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));
if((y%400==0) || ((y%100!=0)&&(y%4==0))) //
month[2]=29;
System.out.println("Invalid Date");
else
int days=sc.nextInt();
while(count<days)
d++;
count++;
/* If day exceeds the maximum days of a Page No: 71
if(d>month[m])
d=1;
m++;
start from 1
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:
Sample Input/Output:
Input:
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
Example 2 INPUT: DAY NUMBER: 360 YEAR: 2018 DATE AFTER (N DAYS): 45
● 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.
● 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
return 366;
else
return 365;
int r = n%10;
return "ST";
return "ND";
return "RD";
else
return "TH";
int D[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
{
D[2] = 29; Page No: 75
int m = 1;
d = d - D[m];
m++;
d = d + n;
if(d>max)
d = d - max;
y++;
findDate(d,y);
else
if(n<1 || n>100)
else
System.out.print("DATE :\t\t\t");
ob.findDate(day,year);
}}}}
Variable Description:
day (int) – The day number of the year (e.g., 1 represents January 1st, 365 or 366 represents
December 31st).
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).
d (int) – The day of the month after calculating from the day number.
Sample Input/Output:
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
---------------------------------------------------------
February 2016
---------------------------------------------------------
----------------------------------------------------------
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)
if((y%400==0) || ((y%100!=0)&&(y%4==0)))
D[2]=29;
int max = 0;
if(mname.equalsIgnoreCase(months[i]))
Page No: 81
} return max;
//Function to match the given weekday name and return its we int findDayNo(String wname)
int f = 0;
if(wname.equalsIgnoreCase(days[i]))
f = i; //Saving week day no. given day (e.g. '0' for Sunday }
return f;
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];
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----------------------------------------------------
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---------------------------------------------- }
int y = sc.nextInt();
System.out.print("Enter the week day name (e.g. Sunday) of String wname = sc.next();
int f = ob.findDayNo(wname);
ob.fillCalendar(max,f,mname,y);
Variable Description:
● 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 weekday name (e.g., Sunday) of the 1st day: Wednesday
Output:
--------------------------------------------------------
MARCH 2023
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------