0% found this document useful (0 votes)
7 views

Comp Pro

comp prog files

Uploaded by

yash98u6
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Comp Pro

comp prog files

Uploaded by

yash98u6
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Name -Yash singh

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

Q-1 A smith number is a composite number, the sum of whose digits is


the sum of the digits of its prime factor obtained as a result of prime
factorization (excluding 1) The first few such numbers
4,22,27,58,85,94,121.

import java.util.Scanner;

public class SmithNumberChecker {

private static int digitSum(int n) {

int sum = 0;

while (n > 0) {

sum += n % 10;

n /= 10;

return sum;

private static int primeFactorDigitSum(int n) {

int sum = 0;

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

while (n % i == 0) {

sum += digitSum(i);
n /= i;

return sum;

private static boolean isSmithNumber(int num) {

return digitSum(num) == primeFactorDigitSum(num);

} public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

system.out.println("Enter a number to check if it's a Smith number:");

int number = scanner.nextInt();

if (isSmithNumber(number)) {

System.out.println(number + " is a Smith number.");

} else {

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

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;

public class MergeAndSortArrays {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of names in array A: ");

int n = scanner.nextInt();

String[] arrayA = new String[n];

System.out.println("Enter names for array A:");

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

arrayA[i] = scanner.next();

System.out.print("Enter the number of names in array B: ");

int m = scanner.nextInt();

String[] arrayB = new String[m];

System.out.println("Enter names for array B:");

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


arrayB[i] = scanner.next();

String[] arrayC = mergeAndSortArrays(arrayA, arrayB);

System.out.println("\nArray A (sorted): " +


Arrays.toString(sortArray(arrayA)));

System.out.println("Array B (sorted): " +


Arrays.toString(sortArray(arrayB)));

System.out.println("Array C (merged and sorted): " +


Arrays.toString(arrayC));

private static String[] mergeAndSortArrays(String[] arrayA, String[] arrayB) {

int totalLength = arrayA.length + arrayB.length;

String[] arrayC = new String[totalLength];

System.arraycopy(arrayA, 0, arrayC, 0, arrayA.length);

System.arraycopy(arrayB, 0, arrayC, arrayA.length, arrayB.length);

Arrays.sort(arrayC);

return arrayC;

private static String[] sortArray(String[] array) {

String[] sortedArray = Arrays.copyOf(array, array.length);

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 │
└───────────────────┴───────────

Q3 A-sentence is terminated by either"""" or "?" followed by space Input a


piece of sentence. Assume that there will be a maximum of 10 sentences
in each block letters.. Write a program to: (1) Obtain the length of the
sentences (measured in words) and the frequency of vowels in each
sentence. (ii)

import java.util.Scanner;

public class SentenceAnalyzer {

private static int countWords(String sentence) {

String[] words = sentence.split("\\s+");

return words.length;

private static int countVowels(String sentence) {

int count = 0;

for (char c : sentence.toCharArray()) {

if ("aeiouAEIOU".indexOf(c) != -1) {

count++;
}

return count;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter a piece of text with up to 10 sentences


(terminate each sentence with \"\"\" or \"? \"):");

StringBuilder inputText = new StringBuilder();

int sentenceCount = 0;

while (sentenceCount < 10) { String inputLine =


scanner.nextLine().trim();

if (inputLine.equals("\"\"\"") || inputLine.endsWith("?")) {

break;

inputText.append(inputLine).append(" ");

sentenceCount++;

String[] sentences = inputText.toString().split("\"\"\"|\\?\\s");

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

String sentence = sentences[i];

int wordCount = countWords(sentence);

int vowelCount = countVowels(sentence);

System.out.println("Sentence " + (i + 1) + ":");

System.out.println(" Word count: " + wordCount);

System.out.println(" Vowel count: " + vowelCount);}}

}
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

while (number > 0) {


int digit = number % 10;
if (visited[digit]) {
return false; // Digit repeated, not unique
}
visited[digit] = true;
number /= 10;
}
return true; // All digits are unique
}
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: ");
int n = scanner.nextInt();
int countUniqueDigitIntegers = 0;
System.out.println("Unique Digit Integers between " + m + " and " + n +
":");
for (int i = m; i <= n; i++) {
if (hasUniqueDigits(i)) {
System.out.print(i + " ");
countUniqueDigitIntegers++;
}
}

System.out.println("\nTotal Unique Digit Integers: " +


countUniqueDigitIntegers);
}
}

Unique Digit Integers between 10 and 50:


Input 10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 34 35 36
37 38 39 40 41 42 43 45 46 47 48 49 50
output Total Unique Digit Integers: 36

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()

Q-6 Given a square matrix M[][] of order 'n'. The maximum


value possible for 'n' is 10. Accept three different characters
from the keyboard and fill the array according to the instruction
given below. Fill the upper and lower elements formed by the
intersection of the diagonals by character 1. Fill the left and
right elements formed by the intersection of the diagonals by
character 2. Fill both the diagonals by character 3.

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

a. Accept char1, char2, and char3 from the keyboard.


b. Initialize a square matrix M of order 'n'.
c. Loop through each element in the matrix M:
i. If i == j or i + j == n - 1, set M[i][j] to char3.
ii. If i < j, set M[i][j] to char1.
iii. If i > j, set M[i][j] to char2.
d. Display the filled matrix M

VDC
┌──────────────────────┬──────────────┐
│ Variable │ Data Type │
├──────────────────────┼──────────────┤
│ M[][] │ 2D array of │
│ │ characters │
│ │ (char) │
├──────────────────────┼──────────────┤
│n │ int │
│ char1, char2, char3 │ char │
│ i, j │ int |
___________________________________________________________

Q-7 A prime adam is a positive integer (without leading zeros) which is


prime as well as an Adam number. Prime Number: A number which has
only two factors. Adam Number: The square of a number and the square
of its reverse and reverse to each other. Example: if n-13 and reverse of
n=31 then (13)²=169 and (31)=961 thus 13 is a adam number. Accept
two positive integers m and n where m is less than n as user input.
Display all Prime-Adam integers that are in the range between m and n
(both inclusive) .

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

INPUT: SELF HELP IS THE BEST HELP.


OUTPUT: SELF HELP IS THE BEST HELP.
IS THE BEST HELP HELP SELF
Algorithm
a. Accept input sentence from the user.
b. Extract the last character of the sentence.
c. If the last character is '.', '?', or 'T', continue; otherwise, display an error
message and end.
d. Split the sentence into an array of words.
e. For each word in the array:
i. Calculate the length of the word.
f. Sort the array of words:
i. If two words have different lengths, sort them based on length in
ascending order.
ii. If two or more words have the same length, sort them alphabetically.
g. Display the original sentence.
h. Display the converted sentence formed by joining the sorted array of
words with a single blank space.

VDC
┌─────────────────────┬───────────────────────────────┐
│ Variable │ Description │
├─────────────────────┼───────────────────────────────┤
│ sentence │ String: Input sentence │
│ isValid │ boolean: Validity indicator │
│ words │ String[]: Array of words │
│ sortedWords │ String[]: Sorted array of words │
└─────────────────────┴───────────────────────────────

Q-10 A company manufactures packing cartons in four sizes,


i.e. cartons to accommodate 6 boxes, 12 boxes, 24 boxes and
48 boxes. Design a program to accept the number of boxes to
be packed (N) by the user (maximum up to 1000 boxes) and
display the break-up of the cartons used in descending order of
capacity (i.e. preference should be given to the highest
capacity available, and if boxes left are less than 6, an extra
carton of capacity 6 should be used.)

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 │

Q-11 Design a Menu Driven Program to perform the following


Task. Each Task should be defined in a separate function. (a)
Add Node in the link list till the user wants (b) Insertion of
new node in the link list at the given position. (c) Deletion of
node in the link list of the given position.. (d) To find the
details of the specified node if it is existing in the link list. (e)
Display the details of all the nodes in tabular form. To
perform the above task you can use the following class
structure for creating node. class Node int empid; String
name; int totalpay Node next

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("-----------------------------------");

while (current != null) {


System.out.printf("%-10d%-20s%-15d\n", current.empid, current.name,
current.totalpay);
current = current.next;
}
}
}
Algorithm
- Set the next of the new node to the current head.
- Update the head to the new node.
- Accept the position and user-input data for the new node.
- Traverse the list to the specified position.
- Insert the new node at the specified position.
- Accept the position of the node to be deleted.
- Traverse the list to the specified position.
- Update the 'next' pointer to skip the node to be deleted.
- Accept the empid of the node to be found.
- Traverse the list to find the node with the specified empid.
- Display the details of the found node.
- Traverse the list.
- Display details of each node in tabular form.
- Initialize head to null.
- Repeat the following until the user chooses to exit:
- Display menu options.
- Accept user choice.
- Call the appropriate function based on the user choice.

VDC

┌───────────────┬───────────────┬──────────────────────────┐
│ Variable │ Data Type │ | Description │
├───────────────┼───────────────┼──────────────────────────┤
│ empid │ int │ | Employee ID │
│ name │ String │ |Employee Name │
│ totalpay │ int │ |Total Pay │
│ next │ Node | │ Reference to Next Node │
└───────────────┴───────────────┴──────────────────────────┘

Q-12 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.

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

return String.format("%02d-%02d-%04d", day, month, year);


}
}
INPUT: DAY NUMBER YEAR 233 2008 DATE AFTER (N) 17
OUTPUT: 20 TH AUGUST 2008 DAY AFTER 17 DAYS 6 SEPTEMBER 2008

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

Q14- Write a program to declare a single dimensional array all and a


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

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

INPUT: N-3 ENTER ELEMENTS OF SINGLE DIMENSION ARRAY: 317


OUTPUT: SORTED ARRAY: 137 FILLED MATRIX 137 131 11

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

Q-15 An encoded text can be decoded by finding actual


character for the given ASCII code in the encoded message.
Write a program to input an encoded text having only sequence
of ASCII values without any spaces. Any code or value which is
not in the range (65-90 or 97-122 or 32 for space) will be
ignored and should not appear in the output message. Decode
the encoded text and print in the form of sentence. The first
alphabet of each word must be in capitals and rest alphabets
will be in small only. Any consecutive sets of code 32 will be
taken as only one blank space.

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 |

You might also like