Comp Pro
Comp Pro
Class -XI
Sec- D
Subject- Computer
Acknowledgement
I would like to express my special
thanks of gratitude to my computer
teacher Siddharth sir as well as our
principal Manjit batra who gave me
the golden opportunity to do this
wonderful project. Secondly, I would
also like to thank my parents and
friends who helped me a lot in
finalizing this project within the limited
time frame. Lastly, I like to thank all my
supporters who have motivated me to
fulfil their project before the timeline.
Index
s.no. topic remark
1 Program 1
2 Program 2
3 Program 3
4 Program 4
5 Program 5
6 Program 6
7 Program 7
8 Program 8
9 Program 9
10 Program
10
11 Program
11
12 Program
12
13 Program
13
14 Program
14
15 Program
15
import java.util.Scanner;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
return sum;
int sum = 0;
while (n % i == 0) {
sum += digitSum(i);
n /= i;
return sum;
if (isSmithNumber(number)) {
} else {
Algorithm
1. Define a function digitSum that takes an integer as input and calculates
the sum of its digits.
2. Define a function primeFactorDigitSum that takes an integer as input and
calculates the sum of digits of its prime factors obtained through prime
factorization.
3. Define a function isSmithNumber that takes an integer as input and returns
true if it is a Smith number, and false otherwise.
Inside the function, calculate the sum of digits of the input number
using the digitSum function.
Calculate the sum of digits of its prime factors using the
primeFactorDigitSum function.
Return true if both sums are equal, indicating that the number is a
Smith number.
Return false otherwise.
4. In the main program:
Take user input for a number.
Call the isSmithNumber function with the user-input number.
Print whether the entered number is a Smith number or not
VDC
│ Variable/Value│ Data Type │
├───────────────────┼─┤
│ num │ int │
│ digitSumResult │ int │
│ primeFactorSum │ int │
│ isSmithNumber boolea │
│ i (loop variable) │ int|
Q-2 Write a program that inputs the names of people into two different arrays. A
and B. Array A has N numbers of names while Array B has M numbers of names
with no duplicates in either of them Merge array A and B into a single array C.
such that the resultant array is sorted alphabetically Display all the three arrays
A,B, and C sorted alphabetically. Test your program for the given data and some.
import java.util.Scanner;
int n = scanner.nextInt();
arrayA[i] = scanner.next();
int m = scanner.nextInt();
Arrays.sort(arrayC);
return arrayC;
Arrays.sort(sortedArray);
return sortedArray;
Algorithm
a. Declare and initialize array A of size N.
b. Input names into array A.
c. Declare and initialize array B of size M.
d. Input names into array B.
e. Declare and initialize array C of size (N + M).
f. Merge arrays A and B into array C without duplicates.
g. Sort array A alphabetically.
h. Sort array B alphabetically.
i. Sort array C alphabetically.
j. Display sorted arrays A, B, and C.
VDC
│ Variable/Value │ Data Type │
├───────────────────┼───────────┤
│ N │ int │
│ M │ int │
│ arrayA │ String[] │
│ arrayB │ String[] │
│ arrayC │ String[] │
│ scanner │ Scanner │
│ i │ int │
└───────────────────┴───────────
import java.util.Scanner;
return words.length;
int count = 0;
if ("aeiouAEIOU".indexOf(c) != -1) {
count++;
}
return count;
int sentenceCount = 0;
if (inputLine.equals("\"\"\"") || inputLine.endsWith("?")) {
break;
inputText.append(inputLine).append(" ");
sentenceCount++;
}
Algorithm
a. Initialize inputText, sentenceCount, and sentences.
b. Read input until 10 sentences or until encountering """ or "? ".
i. Initialize currentSentence.
ii. Read a line of input and append it to currentSentence.
iii. If the line is """ or ends with "? ", add currentSentence to inputText and increment
sentenceCount.
c. Split inputText into sentences based on """ or "? ".
d. For each sentence in sentences:
i. Count the number of words.
ii. Count the frequency of vowels.
iii. Display the results.
VDC
────────────── ──────────┐
│ Variable/Value │ Data Type │
├───────────┼──── ──────┤
│ inputText │ StringBuilder │
│ sentenceCount int │
│ sentences │ String[] │
│ scanner │ Scanner │
│ inputLine │ String │
│i │ int
Q 4 unique digit integer is a positive integer (without leading zeros) with no
duplicate digits. For example 7. 135, 214 are all unique digit integers whereas
33,3121,300 are not. Given two positive integers m and n where men write a
program to determine how many unique digit integers are there in the range
between m and n (both inclusive) and output them.
import java.util.Scanner;
public class UniqueDigitIntegers {
private static boolean hasUniqueDigits(int number) {
boolean[] visited = new boolean[10]; // Assuming digits 0-9
Algorithm
Input:
- Two positive integers m and n
Procedure:
1. Initialize a variable countUniqueDigitIntegers to 0.
2. For each number i in the range from m to n:
a. Check if i has unique digits using the hasUniqueDigits function.
b. If i has unique digits, increment countUniqueDigitIntegers.
3. Output the count of unique digit integers.
Algorithm Steps:
a. Initialize countUniqueDigitIntegers to 0.
b. For each number i in the range from m to n:
i. If i has unique digits:
- Increment countUniqueDigitIntegers.
c. Output countUniqueDigitIntegers
VDC
┌───────────────────────────
│ Variable │ Data Type │
├───────────────────────────
│m │ int │
│n │ int │
│ countUniqueDigitIntegers │ int │
│i │ int │
└───────────────────────────
Q 5 An interface Data is defined with a data member and a method volume() which
returns the volume of the implementing shape. A super class Base has been defined
to contain the radius of a geometrical shape. Define a sub class CalVol which uses
the properties of the interface Data and the class Base and calculates the volume of a
cylinder. The details of the members of the interface and both the classes are given
below: Data member Interface name double pi Member functions/methods double
volume() Class name Data member rad Member functions/methods Base() void show()
Data initialize pi 3.142 Base to store the radius in decimal parameterized constructor
to initialize the data member. displays the radius with an appropriate message
interface Data
{
double pi = 3.142;
double volume();
}
class Base {
double rad;
Base(double radius) {
rad = radius;
}
void show() {
System.out.println("Radius: " + rad);
}
}
class CalVol extends Base implements Data {
CalVol(double radius) {
super(radius);
}
public double volume() {
return pi * rad * rad;
}
}
public class VolumeCalculator {
public static void main(String[] args) {
CalVol cylinder = new CalVol(5.0);
cylinder.show();
System.out.println("Volume of the cylinder: " + cylinder.volume());
}
}
Algorithm
a. Define interface Data with pi and volume().
b. Define superclass Base with rad and show().
c. Implement show() method in Base class.
d. Define subclass CalVol extending Base and implementing Data.
e. Implement volume() method in CalVol class.
f. In the main program, create an object of CalVol.
g. Display the radius using the show() method.
h. Calculate and display the volume using the volume() method.
VDC
┌────────────────────┐
│ Interface │ Data │
├───────────────────┤
│ Data member│ double p│
│ Member functions │ double volume() │
└────────────────────┴─
┌────────────────────┬──────────────┐
│ Class │ Base │
├────────────────────┼──────────────┤
│ Data member │ double rad │
│ Member functions │ Base() │
│ │ void show() │
└────────────────────┴──────────────┘
┌────────────────────┬
│ Subclass │ CalVol │
├────────────────────
│ Inherits from │ Base │
│ │ implements Data │
│ Constructor │ CalVol(double radius) │
│ │ using super()
import java.util.Scanner;
public class MatrixFill {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter character 1: ");
char char1 = scanner.next().charAt(0);
System.out.print("Enter character 2: ");
char char2 = scanner.next().charAt(0);
System.out.print("Enter character 3: ");
char char3 = scanner.next().charAt(0);
int n = 10;
char[][] matrix = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || i + j == n - 1) {
matrix[i][j] = char3; // Fill both diagonals with character 3
} else if (i < j) {
matrix[i][j] = char1; // Fill upper elements with character 1
} else if (i > j) {
matrix[i][j] = char2; // Fill lower elements with character 2
}
}
}
System.out.println("Filled Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
INPUT: FIRST CHARACTER: "*" SECOND CHARACTER: "?" THIRD CHARACTER: "#
OUTPUT: ?##? ?#? Example 2 ENTER SIZE: 5 INPUT: FIRST CHARACTER: 'S'
SECOND CHARACTER: " THIRD CHARACTER: "@ OUTPUT: !@$@! !@$@!
Example 3 ENTER SIZE: 65
OUTPUT: SIZE OUT OF RANGE
Algorithm
VDC
┌──────────────────────┬──────────────┐
│ Variable │ Data Type │
├──────────────────────┼──────────────┤
│ M[][] │ 2D array of │
│ │ characters │
│ │ (char) │
├──────────────────────┼──────────────┤
│n │ int │
│ char1, char2, char3 │ char │
│ i, j │ int |
___________________________________________________________
import java.util.Scanner;
public class PrimeAdamNumbers {
private static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static boolean isAdamNumber(int num) {
int squareNum = num * num;
int reverseNum = 0, temp = squareNum;
while (temp > 0) {
reverseNum = reverseNum * 10 + temp % 10;
temp /= 10;
}
int squareReverse = reverseNum * reverseNum;
return squareNum == reverseNum * reverseNum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of m: ");
int m = scanner.nextInt();
System.out.print("Enter the value of n (greater than m): ");
int n = scanner.nextInt();
System.out.println("Prime-Adam numbers between " + m + "
and " + n + ":");
for (int i = m; i <= n; i++) {
if (isPrime(i) && isAdamNumber(i)) {
System.out.print(i + " ");
}
}
}
}
INPUT: m-5 n=100
OUTPUT: THE PRIME-ADAM INTEGERS ARE: 11 13 31 FREQUENCY OF
PRIME-ADAM INTEGERS IS:3
Algorithm
a. Initialize an empty list PrimeAdamList.
b. For each number i in the range from m to n:
i. If i is a prime number:
- Calculate the square of i.
- Reverse the digits of i and calculate its square.
- Check if the square of i and the square of its reverse are reverse to each.
- If true, add i to PrimeAdamList.
c. Display the PrimeAdamList.
VDC
┌───────────────────────┬──────────────┐
│ Variable │ Data Type │
├───────────────────────┼──────────────┤
│ m, n │ int │
│i │ int │
│ PrimeAdamList │ List of int │
Q-8 Write a program to declare a matrix A[][] of order (MxN) 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. Example
231 (decimal equivalent of 1st row= 153 i.e. 2x8²+3x8+1x8°) 405
(decimal equivalent of 2nd row= 261 i.e. 4x8 +0x8 +5x8°) 156 (decimal
equivalent of 3rd row= 110 i.e. 1x8+5x8'+6x8°) Perform the following
tasks on the matrix: (a) Display the original matrix.
import java.util.Scanner;
public class OctalMatrixOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int M, N;
do {
System.out.print("Enter the number of rows (M, 0 < M < 10): ");
M = scanner.nextInt();
} while (M <= 0 || M >= 10);
do {
System.out.print("Enter the number of columns (N, 2 < N < 6): ");
N = scanner.nextInt();
} while (N <= 2 || N >= 6);
int[][] A = new int[M][N];
System.out.println("Enter octal digits (0-7) for each location in the
matrix:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print("Enter digit for position A[" + (i + 1) + "][" + (j + 1) +
"]: ");
A[i][j] = scanner.nextInt();
}
}
System.out.println("\nOriginal Matrix:");
displayMatrix(A);
System.out.println("\nDecimal Equivalent for Each Row:");
for (int i = 0; i < M; i++) {
int decimalEquivalent = calculateDecimalEquivalent(A[i]);
System.out.println("Row " + (i + 1) + ": " + decimalEquivalent);
}
}
private static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
private static int calculateDecimalEquivalent(int[] octalRow) {
int decimalEquivalent = 0;
int power = 0;
for (int i = octalRow.length - 1; i >= 0; i--) {
decimalEquivalent += octalRow[i] * Math.pow(8, power);
power++;
}
return decimalEquivalent;
}
}
INPUT: M-3 N-4 DECIMAL EQUIVALENT 100 ENTER ELEMENTS FOR ROW
1:1137 ENTER ELEMENTS FOR ROW 2: 2106 ENTER ELEMENTS FOR ROW
3:0245
OUTPUT: FILLED MATRIX DECIMAL EQUIVALENT 1137 607 sum-512+64+24+7
607 2106 1094 0245 165
Algorithm
a. Declare int M, N
b. Declare int A[][] of order (MxN)
c. For i = 0 to M-1:
i. For j = 0 to N-1:
- Accept an octal digit from the user and store it in A[i][j].
d. Display the original matrix A.
e. For i = 0 to M-1:
i. Set decimalEquivalent = 0
ii. For j = N-1 to 0:
- Calculate decimalEquivalent += A[i][j] * 8^(N-1-j)
iii. Display "Decimal Equivalent of Row i: decimalEquivalent"
VDC
┌───────────────┬──────────────┐
│ Variable │ Data Type │
├───────────────┼──────────────┤
│ M, N │ int │
│ A[][] │ 2D array of │
│ │ int │
│ octalDigit │ int │
│ decimalEqui │ int │
Q-9 Write a program to accept a sentence which may be terminated by either".",?' or 'T'
only. The words are to be separated by a single blank space and are in UPPER case.
Perform the following task: (a) Check for the validity of the accepted sentence only for the
terminating character. (b) Arrange the words in ascending order of their length. If two or
more words have same length then sort them alphabetically. (c) Display the original
sentence along with the converted sentence.
import java.util.Arrays;
public class SentenceProcessing
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence (terminated by '.', '?', or 'T'): ");
String sentence = scanner.nextLine();
if (isValidTerminatingCharacter(sentence))
{
String[] words = sentence.split(" ");
Arrays.sort(words, (a, b) -> {
if (a.length() != b.length()) {
return Integer.compare(a.length(), b.length());
} else {
return a.compareTo(b);
}
});
System.out.println("\nOriginal Sentence: " + sentence);
System.out.println("Converted Sentence: " + String.join(" ", words));
} else {
System.out.println("Invalid terminating character. Please use '.', '?', or
'T'.");
}
}
private static boolean isValidTerminatingCharacter(String sentence) {
char lastChar = sentence.charAt(sentence.length() - 1);
return lastChar == '.' || lastChar == '?' || lastChar == 'T';
}
}
VDC
┌─────────────────────┬───────────────────────────────┐
│ Variable │ Description │
├─────────────────────┼───────────────────────────────┤
│ sentence │ String: Input sentence │
│ isValid │ boolean: Validity indicator │
│ words │ String[]: Array of words │
│ sortedWords │ String[]: Sorted array of words │
└─────────────────────┴───────────────────────────────
import java.util.Scanner;
public class CartonBreakup {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
system.out.print("Enter the number of boxes to be packed (up to 1000): ");
int totalBoxes = scanner.nextInt();
if (totalBoxes <= 0 || totalBoxes > 1000) {
System.out.println("Invalid input. Please enter a valid number of boxes.");
return;
}
calculateCartonBreakup(totalBoxes);
scanner.close();
}
private static void calculateCartonBreakup(int totalBoxes) {
system.out.println("\nBreak-up of Cartons (in descending order of capacity):");
int[] cartonCapacities = {48, 24, 12, 6};
for (int capacity : cartonCapacities) {
int cartonsUsed = totalBoxes / capacity;
if (cartonsUsed > 0) {
System.out.println(capacity + " boxes cartons: " + cartonsUsed);
totalBoxes %= capacity;
}
}
if (totalBoxes > 0) {
System.out.println("6 boxes cartons: " + totalBoxes);
}
}
}
INPUT : N=726
OUTPUT :48 x 15 6x1 720 Remaining boxes 0 Total number of boxes 726 Total
number of cartons 1
Algorithm
1. Accept the number of boxes to be packed (N) from the user.
2. Validate the input: Ensure N is within the range [1, 1000].
a. If N is not within the range, display an error message and end.
3. Initialize an array of carton capacities: [48, 24, 12, 6].
4. Display a message indicating the break-up of cartons in descending order of
capacity.
5. For each carton capacity in the array:
a. Calculate the number of cartons used (cartonsUsed) by dividing N by the
current capacity.
b. If cartonsUsed is greater than 0:
i. Display the break-up for the current capacity: "capacity boxes cartons:
cartonsUsed".
ii. Update N to the remainder after using full cartons of the current
capacity.
5. If there are boxes left (N > 0), display an additional break-up for cartons
of capacity 6: "6 boxes cartons: N"
______________________________________________
VDC
┌────────────────────┬──────────────────────────┐
│ Variable │ Description │
├────────────────────┼──────────────────────────┤
│ totalBoxes │ int: Number of boxes to │
│ │ be packed (input) │
│ cartonCapacities │ int[]: Array of carton │
│ │ capacities [48, 24, │
│ │ 12, 6] │
│ cartonsUsed │ int: Number of cartons │
│ │ used for each │
│ │ capacity │
│ remainingBoxes │ int: Number of boxes │
│ │ remaining after using │
│ │ higher capacity │
import java.util.Scanner;
class Node {
int empid;
String name;
int totalpay;
Node next;
Node(int empid, String name, int totalpay) {
this.empid = empid;
this.name = name;
this.totalpay = totalpay;
this.next = null;
}
}
public class LinkedLitMenuDriven {
private static Node head = null;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nLinked List Menu:");
System.out.println("1. Add Node");
System.out.println("2. Insert Node at Position");
System.out.println("3. Delete Node at Position");
System.out.println("4. Find Node Details");
System.out.println("5. Display All Nodes");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
addNode();
break;
case 2:
insertNode();
break;
case 3:
deleteNode();
break;
case 4:
findNodeDetails();
break;
case 5:
displayAllNodes();
break;
case 0:
System.out.println("Exiting the program. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
} while (choice != 0);
scanner.close();
}
private static void addNode() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Employee ID: ");
int empid = scanner.nextInt();
System.out.print("Enter Name: ");
String name = scanner.next();
System.out.print("Enter Total Pay: ");
int totalpay = scanner.nextInt();
Node newNode = new Node(empid, name, totalpay);
newNode.next = head;
head = newNode;
System.out.println("Node added successfully.");
}
private static void insertNode() {
}
private static void deleteNode() {
}
private static void findNodeDetails() {
}
private static void displayAllNodes() {
Node current = head;
System.out.println("\nEmployee Details (Linked List):");
System.out.println("-----------------------------------");
System.out.printf("%-10s%-20s%-15s\n", "EmpID", "Name", "Total Pay");
System.out.println("-----------------------------------");
VDC
┌───────────────┬───────────────┬──────────────────────────┐
│ Variable │ Data Type │ | Description │
├───────────────┼───────────────┼──────────────────────────┤
│ empid │ int │ | Employee ID │
│ name │ String │ |Employee Name │
│ totalpay │ int │ |Total Pay │
│ next │ Node | │ Reference to Next Node │
└───────────────┴───────────────┴──────────────────────────┘
import java.util.Scanner;
public class FutureDateGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a day number (between 1 and 366): ");
int dayNumber = scanner.nextInt();
System.out.print("Enter the year (4 digits): ");
int year = scanner.nextInt();
System.out.print("Enter an integer 'N' (1 <= N <= 100) for future date: ");
int N = scanner.nextInt();
if (isValidInput(dayNumber, year, N)) {
displayGeneratedDate(dayNumber, year);
calculateAndDisplayFutureDate(dayNumber, year, N);
} else {
System.out.println("Invalid input. Please ensure day number, year, and
N are within the specified limits.");
}
scanner.close();
}
private static boolean isValidInput(int dayNumber, int year, int N) {
return (dayNumber >= 1 && dayNumber <= 366) && (year >= 1000 &&
year <= 9999) && (N >= 1 && N <= 100);
}
private static void displayGeneratedDate(int dayNumber, int year) {
System.out.println("Generated Date: " +
getDateFromDayNumber(dayNumber, year));
}
private static void calculateAndDisplayFutureDate(int dayNumber, int year,
int N) {
int futureDayNumber = dayNumber + N;
String futureDate = getDateFromDayNumber(futureDayNumber, year);
System.out.println"Future Date (" + N + " days after): " + futureDate);
}
private static String getDateFromDayNumber(int dayNumber, int year) {
// Assume a non-leap year for simplicity
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month = 1;
int day = dayNumber; while (month <= 12 && day >
daysInMonth[month]) {
day -= daysInMonth[month];
month++;
}
Algorithm
1. Set month to 1
2. Set day to dayNumber
3. While month <= 12 and day > daysInMonth[month]:
4. Subtract daysInMonth[month] from day
5Increment month
6. Display the generated date in the format "dd-mm-yyyy"
7 Calculate the future date:
8 Set futureDay to dayNumber + N
9 While futureDay > 366:
10. Subtract 366 from futureDay
11 Increment year
12 Repeat steps 5.2-5.3 for the future date to get the month and day
13. Display the future date in the format "dd-mm-yyyy
VDC
+-------------+----------------------------------+---------------------+
| Variable | Description | Constraints |
+-------------+----------------------------------+---------------------+
| dayNumber | Integer | 1 <= dayNumber <= 366|
| year | Integer | | 4-digit positive |
| | integer |
|N | Integer | | 1 <= N <= 100 |
| daysInMonth | Array of integers| | [0, 31, 28, 31, 30, |
| | | 31, 30, 31, 31, 30, |
| | | 31, 30, 31] |
import java.util.Scanner;
public class MatrixOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array (N > 2 and N < 10): ");
int N = scanner.nextInt();
if (N <= 2 || N >= 10) {
System.out.println("Invalid size for N. Exiting program.");
System.exit(0);
}
int[] a = new int[N];
int[][] b = new int[N][N];
System.out.println("Enter positive integers into the array:");
for (int i = 0; i < N; i++) {
System.out.print("Enter element at index " + i + ": ");
a[i] = scanner.nextInt();
}
System.out.println("Sorted elements of the array:");
for (int i = 0; i < N; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println("Filled matrix b[][]:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
b[i][j] = Integer.parseInt(fillMatrixElement(a[i], a[j]));
System.out.print(b[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
private static String fillMatrixElement(int x, int y) {
return String.valueOf(x) + String.valueOf(y);
}
}
Algorithm
1-Input N from the user
2- If N is not in the range (3 to 9), display an error message and exit the
program
3-. Declare and initialize array a of size N
4-Input positive integers into array a from the user
6--Sort the elements of array a in ascending order
7-Display the sorted elements of array a
8-Initialize square matrix b of size N x N
9-Fill the square matrix b according to the specified format
10- Display the filled square matrix b
VDC
Name | Type | Description
------------ |---------------|------------------------------------------
N | Integer | Size of the array and square matrix
a | Array of Int | Single-dimensional array to store positive integers
b | 2D Array of Int| Square matrix of integers
i, j | Integer | Loop variables for iteration
temp | Integer | Temporary variable for sorting
import java.util.Scanner;
public class Decoder {
public static String decodeText(String encodedText) {
StringBuilder decodedText = new StringBuilder();
StringBuilder currentWord = new StringBuilder();
for (String codeStr : encodedText.split("32")) {
try {
int code = Integer.parseInt(codeStr);
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
currentWord.append((char) code);
} else if (code == 32) {
decodedText.append(currentWord.toString().toLowerCase()).append(" ");
currentWord.setLength(0); // Reset current word
}
} catch (NumberFormatException ignored) {
}
}
if (currentWord.length() > 0) {
decodedText.append(currentWord.toString().toLowerCase());
}
return decodedText.toString().trim();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter he encoded text (ASCII codes without spaces): ");
String encodedText = scanner.nextLine();
String decodedText = decodeText(encodedText);
System.out.println("Decoded Text: " + decodedText);
}
}
INPUT :Coded text 10665771011153266797868
OUTPUT: Decoded text James Bond
Algorithm
1. Input:
Accept the encoded text as input.
2. Initialization:
Initialize an empty string for the decoded text.
Initialize an empty string for the current word.
3. Decode Loop:
Split the encoded text based on the code 32 (ASCII for space).
For each code in the split array:
If the code is a valid ASCII code (between 65-90 or 97-122 or
32):
Append the corresponding character to the current
word.
If the code is 32:
Append the lowercase form of the current word to the
decoded text.
Reset the current word.
4. Finalization:
If the current word is not empty, append its lowercase form to the
decoded text.
5. Output:
Print the decoded text.
VDC
+------------------------------------+
| Value Datatypes |
+------------------------------------+
| Variable | Data Type |
+------------------+-----------------+
| encodedText | String |
| decodedText | String |
| currentWord | String |
| ASCII | Integer |
| isValidCode | Boolean |