0% found this document useful (0 votes)
23 views59 pages

Final Project

Uploaded by

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

Final Project

Uploaded by

yabaga3327
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Muskan Agarwal XII Science Computer

Science

COMPUTER APPLICATIONS PROJECT

Name – Utkarsh Agarwal

Class – XII Section – Science

Roll. No. – 54

Index No. –

UID –

Session – 2025-26

1
Muskan Agarwal XII Science Computer
Science

Acknowledgement

I would like to express my sincere gratitude to Miss Moumita Kabi, my Computer Science teacher, for her
invaluable guidance, encouragement, and constructive feedback during the development of this Java
programming project. Her support has strengthened my understanding of programming concepts and given
me the confidence to apply them effectively. Her mentorship has been a constant source of motivation and
inspiration.

I am also deeply thankful to Sister Anjali Francis, our esteemed Principal, for fostering a positive academic
environment and ensuring the availability of resources that made the successful completion of this project
possible. Her support has greatly contributed to my learning experience.

Lastly, I extend my heartfelt appreciation to my school, my classmates, and my family. My school has
provided me with the platform to learn and grow, my classmates have encouraged me with their cooperation,
and my family has stood by me with their constant support and motivation throughout this journey.

2
Muskan Agarwal XII Science Computer
Science

Serial No. Topic Page


Index 01. Procedural Programming
No.
1
02. Introduction To Java 3
03. Features Of Java 3
04. OOP In Java 6
05. Hardware And Software Requirement 10
06. Program 01 - Composite Magic Number
07. Program 02 - Circular Prime
08. Program 03 - Karprekar Number
09. Program 04 - Abundant Number
10. Program 05 - Smith Number
11. Program 06 - Hamming Number
12. Program 07 - Trinomial Triangle
13. Program 08 - Dudeney Number
14. Program 09 - Goldbach Number
15. Program 10 - Binary Search
16. Program 11 - Unique Prime Number
17. Program 12 - Saddle point
18. Program 13 - Mirror Matrix
19. Program 14 - Character Matrix
20. Program 15 - Wondrous Square
21. Program 16 - Caesar Cipher
22. Program 17 - Word Frequency
23. Program 18 - Potential of Word
24. Program 19 - Capitalize and reverse
25. Program 20 - Ascending Potential

Signature of Internal Examiner Signature of External Examiner

______________________________ ______________________________

3
Muskan Agarwal XII Science Computer
Science

Procedural Programming
1. Definition
Procedural programming is a paradigm where code is organized into procedures (functions/methods).
Each procedure contains a set of instructions executed in order to perform a task. While Java is mainly
object-oriented, it also allows procedural programming through static methods and the main() method.
2. Features
 Step-by-step execution using a top-down flow.
 Procedures (methods) group code into reusable units.
 Global and local variables manage data scope.
 Parameter passing allows data exchange between methods.
 Modularity breaks programs into smaller parts.
3. Pros and Cons
Advantages
 Simple and beginner-friendly.
 Code reuse through functions.
 Easier debugging by testing individual methods.
 Provides a clear, structured approach.
Disadvantages
 Hard to scale for large projects.
 Global variables reduce data security.
 Maintenance becomes difficult if data structures change.
4. Examples of Procedural Languages
C, Pascal, FORTRAN, BASIC, and Java (when not using OOP features).
5. Example in Java
public class SumExample {
public static int addNumbers(int a, int b) {
return a + b; // procedure
}

public static void main(String[] args) {


int result = addNumbers(5, 10);
System.out.println("Sum is: " + result);
}
}
👉 Here, addNumbers() is a procedure. The program flow is: define → call → output.

6. Procedural vs OOP in Java


Procedural Object-Oriented
Organized around functions Organized around classes/objects
Data and functions are separate Data and behavior are encapsulated
Best for small programs Best for complex systems

7. Conclusion

4
Muskan Agarwal XII Science Computer
Science

Procedural programming in Java is a simple, function-oriented approach suited for small applications. For
larger systems, Java’s OOP features offer better modularity, security, and maintainability.

Program 01
Program:

A Composite Magic Number is a positive integer that is both composite and a magic number.
 Composite number: An integer with more than two factors.
 Magic number: A number whose digits, when repeatedly summed, eventually reduce to 1 (also
known as having a digital root of 1).
Examples:
 Factors of 12 → 1, 2, 3, 4, 6, 12 (so 12 is composite).
 46 → 4 + 6 = 10 → 1 + 0 = 1 (so 46 is a magic number).
The program accepts two positive integers m and n such that m < n. It finds and displays all composite
magic numbers within the range [m, n] (inclusive) and also prints their count.
Sample Input 1:
m = 20
n = 60
Sample Output 1:
The composite magic numbers are: 28, 46, 55
Frequency of composite magic numbers: 3
Sample Input 2:
m = 100
n = 10
Sample Output 2:
Invalid input range

Algorithm:

Step 1: Start the program and create a class CompositeMagicNumber.


Step 2: Define the main method.
Step 3: Create a Scanner object to take input from the user.
Step 4: Read the starting number m.
Step 5: Read the ending number n.
Step 6: If m < 1 or n < 1 or m > n, print "Invalid input range" and stop the program.
Step 7: Initialize a variable count = 0.
Step 8: Print a message showing the range for composite magic numbers.
Step 9: Repeat steps for each number i from m to n.
Step 10: Check if i is composite by testing divisibility from 2 to i-1.
Step 11: If i is composite, set num = i.
Step 12: While num > 9, calculate the sum of digits of num and replace num with the sum.
Step 13: If the final value of num is equal to 1, print i and increase count by 1.
Step 14: After the loop ends, print the total frequency of composite magic numbers using count.
Step 15: End the program.

Solution:

5
Muskan Agarwal XII Science Computer
Science

//The following program checks whether the number entered is a magic composite number or not and
displays the frequency of composite magic numbers
import java.util.Scanner;

public class CompositeMagicNumber {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);

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


int m = in.nextInt();

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


int n = in.nextInt();

if (m < 1 || n < 1 || m > n) {


System.out.println("Invalid input range");
return;
}

System.out.print("Composite magic numbers between " + m + " and " + n + " are:");
int count = 0;

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


boolean isComposite = false;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isComposite = true;
break;
}
}

if (isComposite) {
int num = i;
while (num > 9) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
if (num == 1) {
count++;
System.out.print(i + " ");
}
}
}

6
Muskan Agarwal XII Science Computer
Science

System.out.println();
System.out.println("Frequency of composite magic numbers

Program Output

Variable Description Table

Variable Data Description


Name Type
in Scanner Used to take input from the user.
m int Stores the starting number of the range.
n int Stores the ending number of the range.
count int Stores the frequency of composite magic numbers.
i int Loop variable for iterating through the range m to n.
isComposite boolean Indicates whether the current number i is composite.
j int Loop variable for checking divisors of i.
num int Stores the current number being reduced to a single digit (magic number
check).
sum int Stores the sum of digits of num during reduction.

7
Muskan Agarwal XII Science Computer
Science

Program 02
Program

Prime Number: A number is said to be prime if it has only two factors 1 and itself.
Circular Prime Number: A prime number that remains prime under cyclic shifts of its digits. When the
leftmost digit is removed and replaced at the end of the remaining string of digits, the generated number is
still prime. The process is repeated until the original number is reached again.
Example:
131
311
113
Hence, 131 is a circular prime.
Accept a positive number N and check whether it is a circular prime or not. The new numbers formed after
the shifting of the digits should also be displayed. Test your program with the following data and some
random data:
Example 1
INPUT:
N = 197
OUTPUT:
197
971
719
197 IS A CIRCULAR PRIME.
Example 2
INPUT:
N = 1193
OUTPUT:
1193
1931
9311
3119
1193 IS A CIRCULAR PRIME.

Algorithm

Step 1: Start the program and declare class CircularPrime with instance variable number.
Step 2: Define a constructor CircularPrime(int number) to initialize this.number = number.
Step 3: Define static method isPrime(int num).
3.1 If num < 2, return false.

8
Muskan Agarwal XII Science Computer
Science

3.2 For each i from 2 to √num, check if num % i == 0.


3.3 If divisible, return false.
3.4 Otherwise, return true.
Step 4: Define static method getDigitCount(int num).

4.2 Else return ⌊log10(num)⌋ + 1.


4.1 If num == 0, return 1.

Step 5: Define instance method checkCircularPrime().


5.1 If isPrime(number) is false, return false.
5.2 Set n2 = number.
5.3 Compute digitCount = getDigitCount(number).
5.4 Compute divisor = 10^(digitCount – 1).
5.5 Print n2.
5.6 For i = 1 to digitCount – 1:
5.6.1 t1 = n2 / divisor
5.6.2 t2 = n2 % divisor
5.6.3 n2 = t2 * 10 + t1
5.6.4 Print n2
5.6.5 If !isPrime(n2) return false
5.7 If loop completes, return true.
Step 6: In main():
6.1 Create a Scanner object in.
6.2 Print "ENTER INTEGER TO CHECK (N):"
6.3 Read integer n = in.nextInt()
6.4 If n <= 0, print "INVALID INPUT" and terminate.
6.5 Create CircularPrime cp = new CircularPrime(n)
6.6 Compute result = cp.checkCircularPrime()
6.7 Print a newline
6.8 If result == true, print "Yes, it is a Circular Prime"
6.9 Else print "No, it is not a Circular Prime"
Step 7: End program

Solution

import java.util.*;

public class CircularPrime {


private int number;

public CircularPrime(int number) {


this.number = number;
}

public static boolean isPrime(int num) {

9
Muskan Agarwal XII Science Computer
Science

if (num < 2) return false;


for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

public static int getDigitCount(int num) {


return (num == 0) ? 1 : (int)Math.log10(num) + 1;
}

public boolean checkCircularPrime() {


if (!isPrime(number)) return false;
int n2 = number;
int digitCount = getDigitCount(number);
int divisor = (int)Math.pow(10, digitCount - 1);
System.out.print(n2 + " ");
for (int i = 1; i < digitCount; i++) {
int t1 = n2 / divisor;
int t2 = n2 % divisor;
n2 = t2 * 10 + t1;
System.out.print(n2 + " ");
if (!isPrime(n2)) return false;
}
return true;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.print("ENTER INTEGER TO CHECK (N): ");
int n = in.nextInt();
if (n <= 0) {
System.out.println("INVALID INPUT");
return;
}
CircularPrime cp = new CircularPrime(n);
boolean result = cp.checkCircularPrime();
System.out.println();
if (result) {
System.out.println("Yes, it is a Circular Prime");
} else {
System.out.println("No, it is not a Circular Prime");
}
}
}

10
Muskan Agarwal XII Science Computer
Science

Program Output

Variable Description Table


Variable Data Type Description
Name
number int Stores the input number to be checked for circular prime
num int Parameter in isPrime() and getDigitCount(), represents the number
being checked
n2 int Stores rotated versions of number while checking for circular prime
digitCount int Stores the number of digits in number
divisor int Used to extract the most significant digit during rotation
t1 int Stores the most significant digit of the current number (n2 / divisor)
t2 int Stores remaining digits after removing the most significant digit (n2 %
divisor)
args String[] Command-line argument array for main() (not used in logic)
in Scanner Used to take input from the user
n int Stores the integer entered by the user in main()
cp CircularPrime Object created to call checkCircularPrime()
result boolean Stores the result of circular prime check (true/false)

Program 03

Program:

Kaprekar Number
A Kaprekar number is a number whose square can be split into two parts that add up to the original
number.
Example:
Number = 45
Square = 2025
Split into 20 and 25 → 20 + 25 = 45
Hence, 45 is a Kaprekar number.

Create a class Karprekar with the following specifications:

11
Muskan Agarwal XII Science Computer
Science

 Class name: Karprekar


 Data members / variables: (to store number, square, etc.)
 Member functions / methods:
1. numfunctions() – to input a number and find its square.
2. void countdigits() – to count the digits of the number entered.
3. void checkkaprekar() – to check whether the number entered is a Kaprekar number or not.

Write a main function to create suitable objects of the class and check for Kaprekar numbers by calling the
appropriate methods.

Sample Input 1:
45
Sample Output 1:
Square of the number: 2025
20 + 25 = 45
Yes, it is a Kaprekar Number
Sample Input 2:
12
Sample Output 2:
Square of the number: 144
14 + 4 = 18
No, it is not a Kaprekar Number

Algorithm:

Algorithm for void main()


Step 1: START.
Step 2: Declare an object from class Karprekar as Karprekar ob←New Karprekar()
Step 3: Call method numfunctions()
Step 4: Call method countdigits()
Step 5: Call method checkkarprekar()
Step 6: END
Algorithm for void numfunctions()
Step 1: START.
Step 2: Prompt the user to enter a number (n) through Scanner class
Step 3: Read input value
Step 4: Compute the square of n (sqnum = n * n)
Step 5: STOP
Algorithm for void countdigits()
Step 1: START.
Step 2: Assign temp = n.
Step 3: Set ctr = 0.
Step 4: while temp != 0:
Step 5: Divide temp by 10 (temp /= 10).
Step 6: Increment ctr by 1 (ctr++).
Step 7: END
Algorithm for void checkkarprekar()
Step 1: START.

12
Muskan Agarwal XII Science Computer
Science

Step 2: Compute powTen10^ctr


Step 3: Calculate the remainder: r  sqnum / powTen
Step 4: Calculate the quotient: q sqnum % powTen
Step 5: If r + q equals to n
Step 6: Print Output (num) is a Karprekar Number
Step 7: Print Output (num) is not a Karprekar Number
Step 8: STOP

Solution:

/*This program checks whether the number entered is karprekar number or not*/
import java.util.Scanner;
public class KaprekarNumberChecker
{
//instance variables for the class
int n, sqnum;
int ctr = 0; // Initialize ctr to zero
//to input number and find its square
void numfunctions()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number to check for Kaprekar");
n = sc.nextInt();//inputs value for n from user
sqnum = n * n;//calculating square of number entered
}
//to count the digits of the number entered
void countdigits() {
int temp = n;
while (temp != 0) {
temp /= 10;
ctr++;
}
}
//to check whether the number entered is Karprekar number or not
void checkkaprekar() {
int powTen = (int) Math.pow(10, ctr);
int r = sqnum / powTen;//calculating the remainder
int q = sqnum % powTen;//calculating the quotient
if (r + q == n) //checking condition
{
System.out.println(n + " is a Kaprekar number");
}
else
{
System.out.println(n + " is not a Kaprekar number");
}
}

13
Muskan Agarwal XII Science Computer
Science

public static void main(String args[])


{
KaprekarNumberChecker ob = new KaprekarNumberChecker();//ob creation for calling //methods
ob.numfunctions();
ob.countdigits();
ob.checkkaprekar();
}
}

Program Output

Variable Description Table

Variable Data Type Description


n int Stores the number entered by the user for
checking whether it is a Kaprekar number.
sqnum int Stores the square of the number n.
ctr int Stores the count of digits in the number n.
Initialized to 0 at the start
temp int Temporary variable used inside
countdigits() method to avoid modifying
the original value of n while counting
digits.

Program 04
Program

An abundant number is a number whose sum of proper divisors (excluding the number itself) is greater
than the number.
Example:
Input: 12

14
Muskan Agarwal XII Science Computer
Science

Proper divisors: 1, 2, 3, 4, 6
Sum = 1 + 2 + 3 + 4 + 6 = 16
Since 16 > 12, 12 is an abundant number.

Algorithm

Step 1: Start
Step 2: Input a number n from the user
Step 3: Initialize sum = 0
Step 4: Set loop counter i = 1
Step 5: Repeat while i < n
Step 5.1: If n % i == 0, then add i to sum
sum ← sum + i
Step 5.2: Increment i by 1
i←i+1
Step 6: After loop ends, compare sum with n
Step 6.1: If sum > n, print "n is an abundant number"
Step 6.2: Otherwise, print "n is not an abundant number"
Step 7: Stop

Solution
import java.util.Scanner;

public class AbundantNumber {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = in.nextInt();
int sum = 0;

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


if (n % i == 0)
sum += i;
}

if (sum > n)
System.out.println(n + " is an abundant number.");
else
System.out.println(n + " is not an abundant number.");
}
}

Program Output

15
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Datatype Description


Name
n int Stores the number entered by the user to be checked for abundance
sum int Holds the sum of all proper divisors of n (excluding n itself)
i int Loop control variable used to check divisors from 1 to n-1

Program 05
Program
Smith Number:
A Smith number is a composite number (not prime) whose sum of digits is equal to the sum of the digits of
its prime factors (counting multiplicity).
Example:
Number = 666
Sum of digits = 6 + 6 + 6 = 18
Prime factors = 2 × 3 × 3 × 37
Sum of digits of prime factors = 2 + 3 + 3 + (3 + 7) = 18
Since both sums match, 666 is a Smith Number.

Algorithm
Step 1: Start
Step 2: Input a number n
Step 3: If n <= 0, print "n is not a Smith Number" and stop
Step 4: Check if n is composite
Step 4.1: Divide n by every number from 2 to n-1
Step 4.2: If n is divisible by any number, set isComposite = true
Step 5: If n is not composite (prime or equal to 1), print "n is not a Smith Number" and stop
Step 6: Find the sum of digits of n
Step 6.1: Initialize sumDigits = 0
Step 6.2: Extract each digit of n using % and add to sumDigits
Step 7: Find the sum of digits of prime factors of n
Step 7.1: Initialize sumPrimeDigits = 0

16
Muskan Agarwal XII Science Computer
Science

Step 7.2: Factorize n by dividing repeatedly with values of i starting from 2


Step 7.3: For each prime factor, break it into digits and add to sumPrimeDigits
Step 8: If any prime factor greater than 2 remains, add its digits to sumPrimeDigits
Step 9: Compare the two sums
Step 9.1: If sumDigits == sumPrimeDigits, print "n is a Smith Number"
Step 9.2: Otherwise, print "n is not a Smith Number"
Step 10: Stop

Solution

import java.util.Scanner;

public class SmithNumber {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int n = in.nextInt();

if (n <= 0) {
System.out.println(n + " is not a Smith Number.");
return;
}

boolean isComposite = false;


for (int i = 2; i < n; i++) {
if (n % i == 0) {
isComposite = true;
break;
}
}

if (isComposite && n != 1) {
int sumDigits = 0;
int t = n;
while (t != 0) {
sumDigits += t % 10;
t /= 10;
}

int sumPrimeDigits = 0;
t = n;
for(int i = 2; i < t; i++) {
while(t % i == 0) {
t /= i;

17
Muskan Agarwal XII Science Computer
Science

int temp = i;
while (temp != 0) {
sumPrimeDigits += temp % 10;
temp /= 10;
}
}
}

if(t > 2) {
while (t != 0) {
sumPrimeDigits += t % 10;
t /= 10;
}
}

if (sumPrimeDigits == sumDigits)
System.out.println(n + " is a Smith Number.");
else
System.out.println(n + " is not a Smith Number.");
} else {
System.out.println(n + " is not a Smith Number.");
}
}
}

Program Output

Variable Description Table

Variable Name Data Type Description


n int The number entered by the user, to be tested for Smith property
isComposite boolean Indicates whether n is composite (true) or not (false)
t int Temporary copy of n, used for digit extraction and factorization
d int Stores the current digit extracted from n or a factor

18
Muskan Agarwal XII Science Computer
Science

sumDigits int Sum of digits of the original number n


sumPrimeDigits int Sum of digits of all prime factors of n

Program 06
Program
A Hamming number is a positive integer whose prime factors consist of only 2, 3, and 5.
Write a program in Java to input any positive integer and check whether it is a Hamming number.
Use a main() method to create an object of the class and call the member methods accept() and check().

Algorithm

Step 1: Start
Step 2: Initialize instance variable: num ← 0
Step 3: In main(), create an object of the class and call methods accept() and check()
Step 4: Define method accept() to input the number into variable num
Step 5: Define method check()
Step 5.1: If num < 0, print "NEGATIVE NUMBER ENTERED. INVALID INPUT" and return
Step 5.2: If num == 0, print "0 IS NOT A HAMMING NUMBER" and return
Step 5.3: Set original ← num
Step 5.4: Set isHamming ← true
Step 5.5: Print original followed by " = "
Step 5.6: Set primes ← {2, 3, 5} and firstFactor ← true
Step 5.7: For each prime p in primes, repeat while num % p == 0:
Step 5.7.1: If firstFactor == false, print " × "
Step 5.7.2: Print p
Step 5.7.3: Set num ← num / p
Step 5.7.4: Set firstFactor ← false
Step 5.8: If num > 1, print " × " + num and set isHamming ← false
Step 5.9: If isHamming == true, print original + " IS A HAMMING NUMBER."
Else, print original + " IS NOT A HAMMING NUMBER."
Step 6: Stop

Solution

import java.util.Scanner;

class Hamming {
int num;

public void accept() {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
num = sc.nextInt();

19
Muskan Agarwal XII Science Computer
Science

public void check() {


if (num < 0) {
System.out.println("NEGATIVE NUMBER ENTERED. INVALID INPUT");
return;
}
if (num == 0) {
System.out.println("0 IS NOT A HAMMING NUMBER");
return;
}

int original = num;


boolean isHamming = true;

System.out.print(original + " = ");

int[] primes = {2, 3, 5};


boolean firstFactor = true;

for (int p : primes) {


while (num % p == 0) {
if (!firstFactor) System.out.print(" × ");
System.out.print(p);
num /= p;
firstFactor = false;
}
}

if (num > 1) {
System.out.print(" × " + num);
isHamming = false;
}

System.out.println();

if (isHamming)
System.out.println(original + " IS A HAMMING NUMBER.");
else
System.out.println(original + " IS NOT A HAMMING NUMBER.");
}

public static void main(String[] args) {


Hamming obj = new Hamming();
obj.accept();

20
Muskan Agarwal XII Science Computer
Science

obj.check();
}
}

Program Output

Variable Description Table

Variable Datatype Description


Name
num int Stores the number entered by the user for checking
original int Stores the copy of the input number before factorization
isHamming boolean Indicates whether the number is a Hamming number (true/false)
primes int[] Array containing allowed Hamming prime factors {2, 3, 5}
firstFactor boolean Helps format factorization output with multiplication symbol (×)
p int Current prime factor being tested from primes
obj Hamming Object of the Hamming class to invoke methods
sc Scanner Used to take input from the user in accept()

Program 07
Program
A Trinomial Triangle is a triangular arrangement of trinomial coefficients.
It is constructed starting with a single 1 in the first row, the second row containing three 1s, and each
subsequent element obtained by summing the values from the previous row: one above-left, one directly
above, and one above-right.
Example (first few rows):
1
111
12321
1367631
1 4 10 16 19 16 10 4 1

21
Muskan Agarwal XII Science Computer
Science

Write a program to accept the number of rows from the user and generate the Trinomial Triangle using
recursion (or iterative array-based logic).

Algorithm
Step 1: Start
Step 2: Input the number of rows → rows
Step 3: Create a 2D array triangle[rows][2*rows+1] to store trinomial coefficients
Step 4: Find the middle index: mid ← rows (to center the triangle)
Step 5: Assign base case: triangle[0][mid] ← 1
Step 6: For each row i from 1 to rows-1:
Step 6.1: For each column j from 1 to 2*rows-1:
triangle[i][j] ← triangle[i-1][j-1] + triangle[i-1][j] + triangle[i-1][j+1]
Step 7: Print the triangle:
Step 7.1: For each element, if non-zero → print number
Step 7.2: Otherwise → print spaces for formatting
Step 8: Stop

Solution
import java.util.Scanner;

public class TrinomialTriangle {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();

int[][] triangle = new int[rows][2 * rows + 1];

// Middle index for centering the triangle


int mid = rows;

// Base case
triangle[0][mid] = 1;

// Generate trinomial triangle


for (int i = 1; i < rows; i++) {
for (int j = 1; j < 2 * rows; j++) {
triangle[i][j] = triangle[i - 1][j - 1]
+ triangle[i - 1][j]
+ triangle[i - 1][j + 1];
}
}

// Print trinomial triangle

22
Muskan Agarwal XII Science Computer
Science

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


for (int j = 0; j < 2 * rows + 1; j++) {
if (triangle[i][j] != 0) {
System.out.print(triangle[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Program Output

Variable Description Table

Variabl Data type Description


e
rows int Stores the total number of rows entered by the user
triangle int[][] 2D array that stores trinomial coefficients in triangular arrangement
mid int Middle index used to align triangle correctly
i int Loop control variable for rows
j int Loop control variable for columns inside each row
sc Scanner Used to take user input for number of rows

Program 08
Program

23
Muskan Agarwal XII Science Computer
Science

A Dudeney Number is a positive integer that is a perfect cube, and the sum of its digits is equal to its cube
root.
Example:
 Input: 512
 Sum of digits = 5 + 1 + 2 = 8
 Cube root of 512 = 8
 Since both are equal → 512 is a Dudeney Number.
Write a program in Java to check whether a given number is a Dudeney Number or not.

Algorithm

Step 1: Start
Step 2: Input a number → number
Step 3: Check if number is a perfect cube:
 Compute cubeRoot = cbrt(number)
 If cubeRoot³ ≠ number, then print → not a Dudeney number, and stop.
Step 4: Compute the sum of digits of number:
 Initialize s = 0
 Repeat while number > 0
Extract digit: digit = number % 10
Add digit to s
Update: number = number / 10
Step 5: If s == cubeRoot, print → it is a Dudeney number
Step 6: Else, print → it is not a Dudeney number
Step 7: Stop

Solution

import java.util.Scanner;

public class DudeneyNumber {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int number = sc.nextInt();

// Check if number is a perfect cube


int cubeRoot = (int)Math.round(Math.cbrt(number));

if (cubeRoot * cubeRoot * cubeRoot == number) {


// Calculate sum of digits
int sum = 0, temp = number;
while (temp > 0) {
int digit = temp % 10;

24
Muskan Agarwal XII Science Computer
Science

sum += digit;
temp /= 10;
}

if (sum == cubeRoot) {
System.out.println(number + " is a Dudeney number");
} else {
System.out.println(number + " is not a Dudeney number");
}
} else {
System.out.println(number + " is not a Dudeney number");
}
}
}
Program Output

Variable Description Table

Variable Data type Description


number int Stores the number entered by the user to be checked
cubeRoo int Stores the cube root of the number (rounded)
t
sum int Accumulates the sum of digits of the number
temp int Temporary copy of the number used for digit extraction
digit int Stores each extracted digit of the number
sc Scanner Scanner object to take input from the user

Program 09
Program

Write a program in Java to check whether a number is a Golden Batch Number. A Golden Batch Number is a
number that is divisible by the sum of its digits.
Algorithm

25
Muskan Agarwal XII Science Computer
Science

Step 1: Start
Step 2: Input a number from the user
Step 3: Initialize sum = 0
Step 4: Set temp = number
Step 5: Repeat while temp != 0:
5.1 sum += temp % 10
5.2 temp /= 10
Step 6: Display the sum of digits
Step 7: If number % sum == 0, then:
7.1 Print “It is a Golden Batch Number”
Else:
7.2 Print “It is not a Golden Batch Number”
Step 8: Stop

Solution

import java.util.Scanner;

public class GoldenBatchNumber {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("Enter a number to check for Golden Batch Number:");


int n = sc.nextInt();

int sum = 0;
int temp = n;
while (temp != 0) {
sum += temp % 10;
temp /= 10;
}

System.out.println("Sum of digits: " + sum);

if (n % sum == 0) {
System.out.println(n + " is a Golden Batch Number");
} else {
System.out.println(n + " is not a Golden Batch Number");
}

sc.close();
}
}

26
Muskan Agarwal XII Science Computer
Science

Program Output

Variable Description Table


Variable Data Type Purpose
n int Stores the number entered by the user to check for Golden Batch Number
sum int Stores the sum of digits of the number
temp int Temporary variable used to calculate sum of digits without modifying n
sc Scanner Used to take user input from the console

Program 10
Program
Write a Java program to perform Binary Search on a list of numbers using recursion. The program should
accept a list of n elements from the user, sort them in ascending order using Bubble Sort, and then accept a
value to be searched. The binary search technique should be implemented recursively to determine whether
the value exists in the list. If the value is found, the program should display its position; otherwise, it should
indicate that the value is not present in the array.

Algorithm

Step 1: Start.
Step 2: Input the number of elements n.
Step 3: Read n elements into an array arr.
Step 4: Sort the array in ascending order using Bubble Sort.
Step 5: Input the value v to be searched.
Step 6: Perform binary search recursively:
6.1 Compute m = (l + u) / 2 where l = lower index, u = upper index.
6.2 If arr[m] == v, return m.
6.3 If l > u, return -1 (element not found).

27
Muskan Agarwal XII Science Computer
Science

6.4 If arr[m] > v, search in left half (l to m-1).


6.5 Otherwise, search in right half (m+1 to u).
Step 7: If result ≠ -1, print location of v. Otherwise, print that v is not found.
Step 8: Stop.

Solution

import java.util.*;

class BinSearch {
int arr[];
int n;
static Scanner sc = new Scanner(System.in);

BinSearch(int nn) {
n = nn;
}

void fillArray() {
arr = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
}

void sort() {
int t;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
}

int binSearch(int l, int u, int v) {


if (l > u) return -1;
int m = (l + u) / 2;
if (arr[m] == v) return m;
else if (arr[m] > v) return binSearch(l, m - 1, v);

28
Muskan Agarwal XII Science Computer
Science

else return binSearch(m + 1, u, v);


}

public static void main(String[] args) {


System.out.print("Enter the number of elements: ");
int size = sc.nextInt();

BinSearch obj = new BinSearch(size);


obj.fillArray();
obj.sort();

System.out.print("Enter the value to search: ");


int v = sc.nextInt();

int location = obj.binSearch(0, size - 1, v);

if (location != -1) {
System.out.println(v + " found at position: " + (location + 1));
} else {
System.out.println(v + " not found in the array.");
}
}
}
Program Output

29
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Data type Description


arr[] int[] Stores the list of numbers entered by the user
n int Number of elements in the array
sc Scanner Scanner object to take input from the user
t int Temporary variable used for swapping during sorting
i, j int Loop control variables used in sorting
l int Lower index in the binary search
u int Upper index in the binary search
m int Middle index of the current search interval
v int The value to be searched in the array
size int Stores user input for number of elements
location int Stores the index where the searched value is found (or -1 if not
found)

Program 11

30
Muskan Agarwal XII Science Computer
Science

Program
Write a program in Java to demonstrate the Unique Prime Factorization Theorem (Fundamental
Theorem of Arithmetic). The program should accept an integer n (greater than 1) from the user, find its
prime factors, and display the product of those prime factors. This shows that the factorization of any integer
greater than 1 into prime numbers is unique (the order of factors does not matter).

Algorithm

Step 1: Start.
Step 2: Input an integer n (where n > 1).
Step 3: Store the original value of n in a variable temp.
Step 4: Display the message: "Unique Prime Factorization of n = ".
Step 5: Set i = 2.
Step 6: Repeat steps 7–10 while i ≤ temp.
Step 7: If n is divisible by i, then:
7.1 Print i (as a prime factor).
7.2 Divide n by i (n = n / i).
7.3 If n is still greater than 1, print the multiplication symbol " × ".
7.4 Repeat Step 7 for the same i.
Step 8: Otherwise, increase i by 1 (i = i + 1).
Step 9: Continue until n becomes 1.
Step 10: Stop the loop.
Step 11: End.

Solution

import java.util.Scanner;

public class UniquePrimeFactorization {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Step 1: Input number


System.out.print("Enter an integer greater than 1: ");
int n = sc.nextInt();

int temp = n; // Store original value


System.out.print("Unique Prime Factorization of " + n + " = ");

// Step 2: Prime factorization


for (int i = 2; i <= temp; i++) {
while (n % i == 0) {
System.out.print(i);
n = n / i;

31
Muskan Agarwal XII Science Computer
Science

if (n > 1) {
System.out.print(" × "); // Display multiplication sign
}
}
}
}
}
Program Output

Variable Description Table

Variabl Data type Description


e
sc Scanner Scanner object to take input from the user
n int Input number, reduced step by step during factorization
temp int Stores the original number for display purposes
i int Loop counter used to test possible prime factors

Program 12
Program
Write a Java program to find the Saddle Point in a square matrix.
A Saddle Point is an element of a matrix that is:
1. The minimum element in its row, and
2. The maximum element in its column.
If such an element exists, print it as the Saddle Point; otherwise, display “No Saddle Point”.

Algorithm

Step 1: Start.
Step 2: Input the size of the matrix n.
Step 3: If n > 20, print “Invalid Input” and stop.
Step 4: Create a 2D array a[n][n] and input all elements.
Step 5: Print the original matrix.
Step 6: For each row i of the matrix:
6.1 Find the minimum element rMin in that row.
6.2 Store its column index cIdx.
Step 7: Check the entire column cIdx:
If rMin is greater than or equal to every element in column cIdx, then rMin is a Saddle Point.
Print the Saddle Point and stop.
Step 8: If no such element is found in any row, print “No Saddle Point”.
Step 9: Stop.

32
Muskan Agarwal XII Science Computer
Science

Solution

import java.util.*;

public class Saddle {


int n;
int[][] a;

// Method to input the matrix


public void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the matrix: ");
n = sc.nextInt();

if (n > 20) { // Condition for invalid input


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

a = new int[n][n];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}

System.out.println("The original matrix is:");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}

// Method to find the Saddle Point


public void compute() {
boolean found = false;

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


// Find the minimum element in row i
int rMin = a[i][0];
int cIdx = 0;

33
Muskan Agarwal XII Science Computer
Science

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


if (a[i][j] < rMin) {
rMin = a[i][j];
cIdx = j;
}
}

// Check if rMin is the maximum in its column


boolean isSaddle = true;
for (int k = 0; k < n; k++) {
if (a[k][cIdx] > rMin) {
isSaddle = false;
break;
}
}

if (isSaddle) {
System.out.println("Saddle Point: " + rMin);
found = true;
break;
}
}

if (!found) {
System.out.println("No Saddle Point");
}
}

public static void main(String[] args) {


Saddle ob = new Saddle();
ob.input();
ob.compute();
}
}
Program Output

34
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Data Description


type
i, j, k int Loop control variables for traversing rows and columns
a[][] int[][] 2D array to store elements of the matrix
n int Size of the square matrix
rMin int Minimum element in the current row
cIdx int Column index of the minimum element in the current row
isSaddle boolean Flag variable to check if the element is a Saddle Point
found boolean Indicates whether a Saddle Point has been found

Program 13
Program

Write a program in Java to create a Mirror Matrix.


The program should:
1. Accept a square matrix of order N × N (where N > 2 and N < 10).
2. Generate and display the mirror image of the matrix (reflected about the vertical axis).

35
Muskan Agarwal XII Science Computer
Science

Algorithm

Step 1: Start.
Step 2: Input the order of the matrix N (where 2 < N < 10).
Step 3: Declare a 2D array arr[N][N].
Step 4: Input all the elements of the matrix.
Step 5: Display the original matrix.
Step 6: For each row i from 0 to N-1:
For each column j from 0 to N-1:
Print the element at arr[i][N-1-j].
Step 7: This forms the mirror image matrix.
Step 8: Stop.

Solution

import java.util.Scanner;

public class MirrorMatrix {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Step 1: Input order of matrix


System.out.print("Enter the order N of the matrix (3-9): ");
int N = sc.nextInt();

if (N <= 2 || N >= 10) {


System.out.println("Invalid size! N must be between 3 and 9.");
return;
}

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

// Step 2: Input elements


System.out.println("Enter elements of the matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
arr[i][j] = sc.nextInt();
}
}

// Step 3: Display Original Matrix


System.out.println("\nOriginal Matrix:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {

36
Muskan Agarwal XII Science Computer
Science

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

// Step 4: Display Mirror Matrix


System.out.println("\nMirror Matrix:");
for (int i = 0; i < N; i++) {
for (int j = N - 1; j >= 0; j--) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
Program Output

37
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Data Purpose


Type
N int Order (size) of the square matrix
arr int[][] 2D array to store matrix elements
i int Loop variable for traversing rows

38
Muskan Agarwal XII Science Computer
Science

j int Loop variable for traversing columns


sc Scanner Used to take user input from the console

Program 14
Program

Write a program to declare a character matrix M[N][N], where N must be greater than 3 and less than 10.
Accept three different characters from the user and fill the array as follows:
1. Fill the four corners of the square matrix with the first character.
2. Fill the boundary elements except corners with the second character.
3. Fill the non-boundary elements with the third character.
If the entered size is not in the range 4–9, display "SIZE OUT OF RANGE".
Example 1:
INPUT: N = 4
FIRST CHARACTER: @
SECOND CHARACTER: ?
THIRD CHARACTER: #

OUTPUT:
@??@
?##?
?##?
@??@
Example 2:
INPUT: N = 5
FIRST CHARACTER: A
SECOND CHARACTER: C
THIRD CHARACTER: X

OUTPUT:
ACCCA
CXXXC
CXXXC
CXXXC
ACCCA
Example 3:
INPUT: N = 15
OUTPUT: SIZE OUT OF RANGE

Algorithm

Step 1: Start.
Step 2: Input size m of the matrix.
Step 3: If m < 4 OR m > 9, print "SIZE OUT OF RANGE" and stop.

39
Muskan Agarwal XII Science Computer
Science

Step 4: Input 3 characters ch1, ch2, ch3.


Step 5: Initialize a 2D character array mat[m][m].
Step 6: Loop through the matrix using i and j:
 If (i, j) is a corner position → store ch1.
 Else if (i, j) lies on the boundary (first/last row or column) → store ch2.
 Else → store ch3.
Step 7: Print the matrix row by row.
Step 8: Stop.

Solution

import java.util.*;

class Matrix {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);

// Input matrix size


System.out.print("Enter the size of the square matrix (4-9): ");
int m = sc.nextInt();

// Check for valid size


if (m < 4 || m > 9) {
System.out.println("SIZE OUT OF RANGE");
sc.close();
return;
}

char[][] mat = new char[m][m];

// Input characters for different parts of the matrix


System.out.print("Enter 1st character (corners): ");
char ch1 = sc.next().charAt(0);

System.out.print("Enter 2nd character (boundary except corners): ");


char ch2 = sc.next().charAt(0);

System.out.print("Enter 3rd character (non-boundary): ");


char ch3 = sc.next().charAt(0);

// Fill the matrix


for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
// Fill corners with ch1

40
Muskan Agarwal XII Science Computer
Science

if ((i == 0 || i == m - 1) && (j == 0 || j == m - 1)) {


mat[i][j] = ch1;
}
// Fill non-corner boundary elements with ch2
else if (i == 0 || j == 0 || i == m - 1 || j == m - 1) {
mat[i][j] = ch2;
}
// Fill the rest with ch3
else {
mat[i][j] = ch3;
}
}
}

// Print the matrix


System.out.println("\nMatrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}

sc.close();
}
}
Program Output

41
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variabl Data Type Purpose


e
m int Stores the size of the square matrix
mat char[][] 2D array used to store the matrix elements
ch1 char Character used for corner elements
ch2 char Character used for boundary elements except corners
ch3 char Character used for non-boundary (inner) elements
i int Loop variable for matrix rows
j int Loop variable for matrix columns
sc Scanner Used to take user input from the console

42
Muskan Agarwal XII Science Computer
Science

Program 15
Program

Write a program in Java to check whether a given square matrix of order N × N is a Wondrous Square.
A Wondrous Square is defined as:
1. It contains all numbers from 1 to N × N exactly once.
2. The sum of each row and each column is equal to the same constant (called the Wondrous
Number).

Algorithm

Step 1: Start
Step 2: Fix N = 4.
Step 3: Declare a 2D array arr[N][N].
Step 4: Input all elements of the matrix.
Step 5: Check if the matrix contains all numbers from 1 to N × N exactly once.
If not, print “Not a Wondrous Square” and stop.
Step 6: Calculate the sum of the first row. Store it as wondrousSum.
Step 7: For each row i:
Find the sum of row i.
If the sum ≠ wondrousSum, print “Not a Wondrous Square” and stop.
Step 8: For each column j:
Find the sum of column j.
If the sum ≠ wondrousSum, print “Not a Wondrous Square” and stop.
Step 9: If all checks pass, print “It is a Wondrous Square with wondrous sum = …”.
Step 10: End

Solution

import java.util.Scanner;

public class WondrousSquare {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter size:");
int n = in.nextInt();
int[][] a = new int[n][n];

// Input
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {

43
Muskan Agarwal XII Science Computer
Science

a[i][j] = in.nextInt();
}
}

// Display matrix
System.out.println("\nThe Matrix is:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}

// Check if Wondrous
if (isWondrous(a)) {
int wondrousSum = 0;
for (int j = 0; j < n; j++) {
wondrousSum += a[0][j]; // sum of first row
}
System.out.println("\nIt is a Wondrous Square with wondrous sum = " + wondrousSum);
} else {
System.out.println("\nNot a Wondrous Square");
}

in.close();
}

// Method to check Wondrous property


public static boolean isWondrous(int arr[][]) {
int n = arr.length;
int nSq = n * n;

// 1. Check distinct numbers from 1 to n*n


boolean[] seen = new boolean[nSq + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int val = arr[i][j];
if (val < 1 || val > nSq || seen[val]) {
return false;
}
seen[val] = true;
}
}

// 2. Calculate wondrous sum from first row

44
Muskan Agarwal XII Science Computer
Science

int wondrousSum = 0;
for (int j = 0; j < n; j++) {
wondrousSum += arr[0][j];
}

// 3. Check rows
for (int i = 0; i < n; i++) {
int rowSum = 0;
for (int j = 0; j < n; j++) {
rowSum += arr[i][j];
}
if (rowSum != wondrousSum) return false;
}

// 4. Check columns
for (int j = 0; j < n; j++) {
int colSum = 0;
for (int i = 0; i < n; i++) {
colSum += arr[i][j];
}
if (colSum != wondrousSum) return false;
}

return true;
}
}

Program Output

45
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Data Type Purpose


n int Order of the square matrix (fixed as 4)
a int[][] 2D array used to store matrix elements
i int Loop variable for iterating rows
j int Loop variable for iterating columns
val int Stores current element being checked
wondrousSu int Stores required constant sum of rows/columns
m

46
Muskan Agarwal XII Science Computer
Science

seen boolean[] Used to track whether each number from 1 to 16 is present exactly once
in Scanner Used to take input from user

Program 16
Program

Caesar Cipher is an encryption technique which is implemented as ROT13 ("rotate by 13 places"). It is a


simple letter substitution cipher that replaces a letter with the letter 13 places after it in the alphabets, with
the other characters remaining unchanged.
ROT13 Mapping:
A ↔ N, B ↔ O, C ↔ P, D ↔ Q, E ↔ R, F ↔ S, G ↔ T, H ↔ U, I ↔ V, J ↔ W, K ↔ X, L ↔ Y, M ↔ Z
a ↔ n, b ↔ o, c ↔ p, d ↔ q, e ↔ r, f ↔ s, g ↔ t, h ↔ u, i ↔ v, j ↔ w, k ↔ x, l ↔ y, m ↔ z
Write a program to accept a plain text of length L, where L must be greater than 3 and less than 100.
Encrypt the text if valid as per the Caesar Cipher.
Example 1
INPUT:
Hello! How are you?
OUTPUT:
The cipher text is:
Uryyb! Ubj ner lbh?
Example 2
INPUT:
Encryption helps to secure data.
OUTPUT:
The cipher text is:
Rapelcgvba urycf gb frpher qngn.
Example 3
INPUT:
You
OUTPUT:
INVALID LENGTH

Algorithm

Step 1: Start
Step 2: Declare variables: str (input text), cipher (encrypted text), len (length of text), ch (character for
processing).
Step 3: Accept user input string and store in str. Compute its length as len.
Step 4: If len <= 3 or len >= 100, print "INVALID LENGTH" and stop.
Step 5: Otherwise, initialize an empty string cipher.
Step 6: For each character ch in str:
6.1 If ch is between 'A'–'M' or 'a'–'m', shift it forward by 13.

47
Muskan Agarwal XII Science Computer
Science

6.2 Else if ch is between 'N'–'Z' or 'n'–'z', shift it backward by 13.


6.3 Else, leave it unchanged.
6.4 Append the transformed character to cipher.
Step 7: Print the encrypted cipher text.
Step 8: Stop

Solution

import java.util.Scanner;

public class CaesarCipher {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter plain text: ");


String str = sc.nextLine();
int len = str.length();

if (len <= 3 || len >= 100) {


System.out.println("INVALID LENGTH");
return;
}

StringBuilder cipher = new StringBuilder();

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


char ch = str.charAt(i);

if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
cipher.append((char)(ch + 13));
}
else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
cipher.append((char)(ch - 13));
}
else {
cipher.append(ch); // Non-alphabetic characters unchanged
}
}

System.out.println("The cipher text is:");


System.out.println(cipher.toString());

sc.close();
}

48
Muskan Agarwal XII Science Computer
Science

}
Program Output

Variable Description Table

Variabl Data Type Purpose


e
str String Stores the input plaintext entered by the user
cipher StringBuilder Stores the encrypted text after applying ROT13 cipher
len int Stores the length of the input string
ch char Stores each character of the input string during processing
i int Loop control variable used for traversing the string
sc Scanner Used to take user input from the console

Program 17
Program

Write a program in Java to accept a sentence and a word from the user and find the frequency of occurrence
of the given word in the sentence.

Algorithm

Step 1: Start
Step 2: Input a sentence from the user.
Step 3: Input the word to be searched in the sentence.
Step 4: Convert the sentence and the word into lowercase form (to ignore case differences).
Step 5: Split the sentence into individual words using space as a delimiter.
Step 6: Initialize a counter variable count to 0.
Step 7: Repeat for each word in the array of words:

49
Muskan Agarwal XII Science Computer
Science

7.1 Compare the current word with the given word.


7.2 If both are equal, increment count by 1.
Step 8: After the loop ends, display the value of count.
Step 9: Stop

Solution

import java.util.Scanner;

public class WordFrequency {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

System.out.println("Enter the word to find its frequency:");


String word = sc.nextLine();

sentence = sentence.toLowerCase();
word = word.toLowerCase();

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

int count = 0;
for (String w : words) {
if (w.equals(word)) {
count++;
}
}

System.out.println("Frequency of word: "+count);

}
}
Program Output

50
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variabl Data Type Purpose


e
sentence String Stores the input sentence
word String Stores the word whose frequency is to be checked
words String[] Array of words obtained by splitting the sentence
w String Represents each word in the array during traversal
count int Stores the number of times the word occurs
sc Scanner Used to take user input from the console

Program 18
Program

Write a program in Java to input a sentence. Calculate the potential of each word and display it. The
potential of a word is the sum of the positions of its alphabets in the English alphabetic order (i.e., a = 1, b =
2, …, z = 26). Finally, display the potentials of all words in ascending order.

Algorithm

Step 1: Start
Step 2: Input a sentence from the user.
Step 3: Tokenize the sentence into individual words using StringTokenizer with delimiters like space,
comma, period, semicolon, etc.
Step 4: Initialize an integer array potentials[100] to store the potential values of words.
Step 5: Initialize count = 0.
Step 6: Repeat while there are more tokens (words):

51
Muskan Agarwal XII Science Computer
Science

6.1 Extract the next word.


6.2 Convert the word to lowercase.
6.3 Initialize sum = 0.
6.4 For each character in the word:
If the character is an alphabet ('a' to 'z'), add (character – 'a' + 1) to sum.
6.5 Store sum in potentials[count].
6.6 Increment count by 1.
Step 7: Display each word along with its potential.
Step 8: Sort the array potentials using Bubble Sort in ascending order.
Step 9: Print the sorted list of potentials.
Step 10: Stop

Solution

import java.util.Scanner;
import java.util.StringTokenizer;

public class WordPotentialTokenizer {

// Function to calculate potential of a word


public static int getPotential(String word) {
int sum = 0;
word = word.toLowerCase(); // Convert to lowercase
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch >= 'a' && ch <= 'z') {
sum += ch - 'a' + 1;
}
}
return sum;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

// Use StringTokenizer with common delimiters


StringTokenizer st = new StringTokenizer(sentence, " ,.;:!?");

// Assuming max 100 words


int[] potentials = new int[100];

52
Muskan Agarwal XII Science Computer
Science

int count = 0;

System.out.println("\nWord potentials:");
while (st.hasMoreTokens()) {
String word = st.nextToken();
int pot = getPotential(word);
potentials[count] = pot;
System.out.println(word + ": " + pot);
count++;
}

// Sort potentials using simple bubble sort


for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (potentials[i] > potentials[j]) {
int temp = potentials[i];
potentials[i] = potentials[j];
potentials[j] = temp;
}
}
}

// Print sorted potentials


System.out.println("\nSorted potentials:");
for (int i = 0; i < count; i++) {
System.out.print(potentials[i] + " ");
}

sc.close();
}
}

Program Output

53
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Data Type Purpose


sentence String Stores the sentence entered by the user
word String Stores each individual word extracted from the sentence
potentials int[] Array to store the potential values of all words (maximum 100 words)
st StringTokenizer Used to break the sentence into words (tokens)
sc Scanner Used to take user input from the console
pot int Stores the potential value of the current word
sum int Used inside getPotential() to calculate the sum of letter positions
count int Stores the number of words processed from the sentence
ch char Stores the current character of a word while calculating potential
i, j int Loop control variables used for sorting the potentials array
temp int Temporary variable used for swapping during bubble sort

Program 19
Program

Write a program in Java to input a sentence, capitalize the first letter of each word, and display the sentence
in reverse order of words.

Algorithm

54
Muskan Agarwal XII Science Computer
Science

Step 1: Start
Step 2: Input a sentence from the user
Step 3: Tokenize the sentence into individual words using StringTokenizer with space and punctuation as
delimiters
Step 4: Initialize an array words[100] to store capitalized words and count = 0
Step 5: While there are more tokens:
5.1 Extract the next word
5.2 Capitalize the first letter of the word and convert the rest to lowercase
5.3 Store the capitalized word in words[count]
5.4 Increment count by 1
Step 6: Print the words in reverse order from words[count-1] to words[0]
Step 7: Stop

Solution

import java.util.Scanner;
import java.util.StringTokenizer;

public class CapitalizeReverseSentence {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

StringTokenizer st = new StringTokenizer(sentence, " ,.;:!?");


String[] words = new String[100];
int count = 0;

while (st.hasMoreTokens()) {
String word = st.nextToken();
word = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
words[count] = word;
count++;
}

System.out.println("\nReversed sentence:");
for (int i = count - 1; i >= 0; i--) {
System.out.print(words[i] + " ");
}

sc.close();
}

55
Muskan Agarwal XII Science Computer
Science

Program Output

Variable Description Table

Variable Data Type Purpose


sentence String Stores the sentence entered by the user
st StringTokenizer Breaks the sentence into words
words String[] Stores all capitalized words
count int Stores the number of words processed
word String Stores the current word during processing
sc Scanner Reads user input from the console
i int Loop control variable used for reversing and printing words

Program 20
Program

Write a program in Java to input a sentence, calculate the frequency of each word, and display the words in
ascending order of their frequency.

Algorithm

Step 1: Start
Step 2: Input a sentence from the user
Step 3: Tokenize the sentence into words using StringTokenizer with delimiters like space, comma, period,
semicolon, etc.

56
Muskan Agarwal XII Science Computer
Science

Step 4: Initialize an array words[100] to store the words and count = 0


Step 5: While there are more tokens:
5.1 Extract the next word and convert it to lowercase
5.2 Store the word in words[count]
5.3 Increment count by 1
Step 6: Initialize arrays freq[100] to store frequencies
Step 7: For each word, count its occurrences in words[] and store in freq[]
Step 8: Sort words[] based on corresponding freq[] in ascending order
Step 9: Display each word along with its frequency
Step 10: Stop

Solution

import java.util.Scanner;
import java.util.StringTokenizer;

public class WordFrequencyAscending {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

StringTokenizer st = new StringTokenizer(sentence, " ,.;:!?");


String[] words = new String[100];
int[] freq = new int[100];
int count = 0;

while (st.hasMoreTokens()) {
words[count] = st.nextToken().toLowerCase();
count++;
}

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


freq[i] = 1;
for (int j = i + 1; j < count; j++) {
if (words[i].equals(words[j])) {
freq[i]++;
words[j] = ""; // mark duplicate as empty
}
}
}

57
Muskan Agarwal XII Science Computer
Science

for (int i = 0; i < count - 1; i++) {


for (int j = i + 1; j < count; j++) {
if (!words[i].equals("") && !words[j].equals("") && freq[i] > freq[j]) {
int tempFreq = freq[i];
freq[i] = freq[j];
freq[j] = tempFreq;

String tempWord = words[i];


words[i] = words[j];
words[j] = tempWord;
}
}
}

System.out.println("\nWords in ascending order of frequency:");


for (int i = 0; i < count; i++) {
if (!words[i].equals("")) {
System.out.println(words[i] + ": " + freq[i]);
}
}

sc.close();
}
}

Program Output

58
Muskan Agarwal XII Science Computer
Science

Variable Description Table

Variable Data Type Purpose


sentence String Stores the sentence entered by the user
st StringTokenize Breaks the sentence into words
r
words String[] Stores all words from the sentence
freq int[] Stores frequency of each word
count int Stores the number of words processed
sc Scanner Reads user input from the console
i, j int Loop control variables for counting and sorting
tempWord String Temporary variable for swapping words during sorting
tempFreq int Temporary variable for swapping frequencies during sorting

59

You might also like