Computer Science ISC XII
Computer Science ISC XII
Acknowledgement
1
Amanpreet Kaur XII Science Computer Science
I am also deeply thankful to Sister Anjali Francis, our respected Principal, for providing
a supportive academic environment and the resources necessary to complete this
project successfully.
Index
2
Amanpreet Kaur XII Science Computer Science
______________________________
______________________________
Procedural Programming
3
Amanpreet Kaur XII Science Computer Science
Definition:
Procedural Programming is a programming paradigm that organizes code into a set of
procedures (also called functions, methods, or subroutines).
Each procedure contains a sequence of instructions that are executed step-by-step to
perform a specific task.
Key Features
Advantages
Disadvantages
C
Pascal
FORTRAN
BASIC
Java (when used without OOP features)
4
Amanpreet Kaur XII Science Computer Science
return a + b; // procedure
}
Here:
5
Amanpreet Kaur XII Science Computer Science
6
Amanpreet Kaur XII Science Computer Science
1. Java Virtual Machine (JVM): The JVM is a key part of Java's platform-
independent nature. It converts Java bytecode into machine code that can be
executed on the host machine. The JVM also handles important tasks such as
memory management, garbage collection, and thread management.
2. Java Development Kit (JDK): The JDK includes tools required for Java
development, such as the compiler (`javac`), debugger, and libraries. It
provides everything necessary to write and run Java applications.
3. Java Runtime Environment (JRE): The JRE is the environment in which Java
programs run. It includes the JVM, core libraries, and supporting files. The JRE is
essential for running Java applications but does not include development tools.
7
Amanpreet Kaur XII Science Computer Science
- Web Applications: Java is widely used for building scalable web applications.
Frameworks like Spring and Hibernate simplify development and are popular in the
enterprise world.
- Mobile Applications: Android development relies heavily on Java, making it one of the
top choices for building mobile apps.
- Enterprise Solutions: Java has a strong foothold in enterprise environments, where
reliability and scalability are critical. Technologies like Java Enterprise Edition (Java EE)
are used to build large-scale distributed systems.
Conclusion
Java’s combination of platform independence, object-oriented principles, and
robustness has made it one of the most popular programming languages for over two
decades. Whether for mobile apps, enterprise systems, or web applications, Java
continues to be a key player in software development. Its vast ecosystem, strong
community support, and ongoing improvements ensure that Java remains relevant in
the ever-evolving tech landscape.
8
Amanpreet Kaur XII Science Computer Science
1. Encapsulation
Encapsulation is the bundling of data (fields) and methods (functions) that operate on
the data into a single unit, usually a class. It restricts direct access to some of an
object's components, protecting the internal state from unauthorized modifications.
Encapsulation is achieved through access modifiers like private, protected, and public,
with controlled access provided by getter and setter methods. This helps to maintain
data integrity and enforce boundaries between different components of a program.
Real-world Analogy: Think of encapsulation like a car's dashboard - you can interact
with essential controls (public interface) without needing to understand or access the
complex engine mechanics (private implementation). This abstraction makes the
system both safer and easier to use.
9
Amanpreet Kaur XII Science Computer Science
function, reducing the potential for errors and security vulnerabilities in larger
software systems.
2. Inheritance
Inheritance allows one class (subclass) to inherit fields and methods from another
class (superclass). It enables code reuse and establishes a hierarchical relationship
between classes, where the subclass can extend or modify the behavior of the
superclass. Inheritance in Java is implemented using the extends keyword, allowing
new classes to build upon existing ones without needing to duplicate code.
10
Amanpreet Kaur XII Science Computer Science
3. Polymorphism
Polymorphism enables objects of different types to be treated as objects of a common
superclass. This allows the same method or function to behave differently based on
the object that is calling it. There are two types of polymorphism in Java:
- Compile-time Polymorphism (Method Overloading): Multiple methods have the same
name but different parameters.
- Runtime Polymorphism (Method Overriding): A subclass provides a specific
implementation of a method already defined in its superclass.
4. Abstraction
Abstraction focuses on the “what” rather than the “how,” letting code use clear
contracts while hiding messy details underneath.
11
Amanpreet Kaur XII Science Computer Science
Abstract classes
- Can have abstract methods (no body) and concrete methods (with
implementation).
- Can hold state (fields), constructors, and shared behavior.
- Supports partial abstraction—some methods defined, others left for subclasses.
Interfaces
- Define pure contracts: method signatures, constants; plus default and static
methods.
- A class can implement multiple interfaces (supports multiple inheritance of
type).
- Encourage loose coupling and clean separations of capabilities.
Key idea: clients depend on the abstraction (Payment), while concrete classes handle
the details(bank)—making systems easier to extend and maintain.
12
Amanpreet Kaur XII Science Computer Science
Software
1 Operating systems:
o Windows 10/11 64-bit, Windows Server 2019/2022 (64-bit JVMs only).
o macOS (Apple Silicon and Intel) with supported 64-bit JVMs
o Linux distributions certified for 64-bit JVMs (e.g., Oracle Linux UEK6+;
major distros commonly supported).
1 Java platform:
o Install a 64-bit JDK (Java Development Kit) such as Oracle JDK 21 LTS; it
includes the JRE and tools (javac, java).
1 Optional developer tools:
o IDEs (IntelliJ IDEA, Eclipse, VS Code Java). Newer Eclipse/VS Code Java
stacks require at least Java 21 to run the tooling itself.
Hardware
CPU: Any modern 64-bit processor (x86-64 or Apple Silicon). Oracle certifies only
64-bit JVMs for current releases.
Memory: 2GB minimum workable for simple apps; 4GB+ recommended for
comfortable development and modern IDEs (Oracle tools commonly recommend
4GB for IDEs).
Disk space:
o JDK install ~300–500MB depending on distribution; allow 2–3GB+ for IDEs,
caches, and project dependencies.
Display: 1024×768 or higher recommended for IDEs.
13
Amanpreet Kaur XII Science Computer Science
PROGRAM 01:
Program:
A Composite Magic number is a positive integer which is composite as well as a
magic number.
Composite number: A composite number is a number which has more than two
factors.
Magic number: A number whose digits repeatedly sum to 1 (also called a digital root
of 1).
For example:
Factors of 10 are: 1, 2, 5, 10
For example: 28 = 2+8=10= 1+0=1
Accept two positive integers 'm' and 'n', where m is less than n. Display the number of
composite magic integers that are in the range between m and n (both inclusive) and
output them along with frequency, in the format specified below:
Sample Input:
m=10 n=100
Output: The composite magic numbers are 10,28,46,55,64,82,91,100
Frequency of composite magic numbers: 8
Sample Input:
m=120 n=90
Output: Invalid input
Algorithm:
Step 1: Create class composite MagicNumber.
Step 2: Create main method.
Step 3: Create Scanner class.
Step 4: Print the first number(m).
Step 5: Print the second number(n).
Step 6: If m<1 or n<1 or m<n print it as invalid input.
Step 7: print the composite magic numbers, first initialize the count as 0.
Step 8: for(int i=m;i<=n;i++)
Step 9: Check if the Boolean call for checking is true or false
Step 10: If that’s false, for(int j=2;j<n;j++)
Step 11: If(i%j==0),the boolean call for magic number is true
Step 12: If the number and ‘i’ not equal to 1,int num=i
Step 13: While(num>9)
Step 14: Sum=0
Step 15: While num!=0
Step 16: int d = num % 10
Step 17: num /= 10
Step 18: sum += d
Step 19: Num=sum
Step 20: If(num==1)
Step 21: The print the frequency of the composite magic numbers
Step 22: End of program
14
Amanpreet Kaur XII Science Computer Science
Solution :
//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;
System.out.print("Enter n: ");
int n = in.nextInt();
15
Amanpreet Kaur XII Science Computer Science
}
}
System.out.println();
System.out.println("Frequency of composite magic numbers: " + count);
}
}
16
Amanpreet Kaur 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.
17
Amanpreet Kaur XII Science Computer Science
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. Define isPrime(int num) method:
Step 1.1. Initialize c = 0 to count factors.
Step 1.2. Loop i from 1 to num:
1.2. 1 If num % i == 0, increment c.
Step 1.3. Return true if c == 2 else return false.
18
Amanpreet Kaur XII Science Computer Science
Solution :
//the following program uses constructor and function/member methods to find if a
number is circular prime or not
import java.util.*;
public class CircularPrime
{
public static boolean isPrime(int num) {
int c = 0;
19
Amanpreet Kaur XII Science Computer Science
return c == 2;
}
public static int getDigitCount(int num) {
int c = 0;
while (num != 0) {
c++;
num /= 10;
}
return c;
}
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;
}
boolean isCircularPrime = true;
if (isPrime(n)) {
System.out.println(n);
int digitCount = getDigitCount(n);
int divisor = (int)(Math.pow(10, digitCount - 1));
int n2 = n;
for (int i = 1; i < digitCount; i++) {
int t1 = n2 / divisor;
int t2 = n2 % divisor;
n2 = t2 * 10 + t1;
System.out.println(n2);
if (!isPrime(n2)) {
isCircularPrime = false;
break;
}
}
}
else {
isCircularPrime = false;
}
if (isCircularPrime) {
System.out.println(n + " IS A CIRCULAR PRIME.");
}
else {
System.out.println(n + " IS NOT A CIRCULAR PRIME.");
}
}
}
20
Amanpreet Kaur XII Science Computer Science
21
Amanpreet Kaur XII Science Computer Science
prime.
in scanner Object used to take user input
from the console.
PROGRAM 03:
Program:
Create a class Karprekar as given
Class name : Karprekar
Data members/variables:
Member functions/methods:
(i) numfunctions()- to input number and find its square
(ii) void countdigits( )- to count the digits of the number entered
22
Amanpreet Kaur XII Science Computer Science
Write a MAIN function to create suitable objects of the class and print the details of
the products by calling the suitable methods
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.
Step 2: Compute powTen10^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()
{
23
Amanpreet Kaur XII Science Computer Science
24
Amanpreet Kaur XII Science Computer Science
PROGRAM 04:
25
Amanpreet Kaur XII Science Computer Science
Program:
An abundant number is a number for which the sum of its proper divisors (excluding
the number itself) is greater than the original number. Write a program to input
number and check whether it is an abundant number or not.
Sample input: 12
Sample output: It is an abundant number.
Explanation: Its proper divisors are 1, 2, 3, 4 and 6
Sum = 1 + 2 + 3 + 4 + 6 = 16
Hence, 12 is an abundant number.
Write a MAIN function to create suitable objects of the class and print the details of
the products by calling the suitable methods.
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.
SUMSUM+I
Step 5.2: Increment i by 1.
II+1
Step 6: After loop ends, compare sum with n.
Step 6.1: If sum > n, print n is an abundant number.
DISPLAY(N,” is an abundant number.”)
Step 6.2: Otherwise, print n is not an abundant number.
DISPLAY(N,” is not an abundant number.”)
Step 7: Stop
Solution:
//The following program checks for abundant number and prints output using
constructor/functions/member methods
import java.util.Scanner;
26
Amanpreet Kaur XII Science Computer Science
if (sum > n)
PROGRAM 05:
Program:
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).
27
Amanpreet Kaur XII Science Computer Science
Write a program in java to find whether the input is smith number or not
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 any division is exact,
SET ISCOMPOSITE = TRUE.
Step 5: If n is not composite (i.e., prime or 1), print “n is not a Smith Number” and
stop.
DISPLAY(N, " is not a Smith Number.")
Step 6: Find the sum of digits of n:
Step 6.1: Initialize SUMDIGITS = 0.
Stp 6.2: Extract each digit of n using % and add to sumDigits.
D = T % 10
SUMDIGITS += D
Step 7: Find the sum of digits of prime factors of n:
Step 7.1: Initialize SUMPRIMEDIGITS = 0.
Step 7.2: Factorize n by dividing repeatedly with values of i from 2 to n.
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 (t > 2), add its digits to
sumPrimeDigits.
Step 9: Compare sumDigits and sumPrimeDigits:
Step 9.1: If both are equal, print “n is a Smith Number”.
Step 9.2: Else, print “n is not a Smith Number”.
Step 10: Stop.
Solution:
import java.util.Scanner;
if (n <= 0) {
System.out.println(n + " is not a Smith Number.");
return;
}
28
Amanpreet Kaur XII Science Computer Science
break;
}
}
if (isComposite && n != 1) {
int sumDigits = 0;
int t = n;
while (t != 0) {
int d = t % 10;
sumDigits += d;
t /= 10;
}
int sumPrimeDigits = 0;
t = n;
for(int i = 2; i < t; i++) {
while(t % i == 0) {
t /= i;
int temp = i;
while (temp != 0) {
int d = temp % 10;
sumPrimeDigits += d;
temp /= 10;
}
}
}
if(t > 2) {
while (t != 0) {
int d = t % 10;
sumPrimeDigits += d;
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.");
}
}
}
29
Amanpreet Kaur XII Science Computer Science
PROGRAM 06:
Program:
Hamming numbers are positive integers whose prime factors include 2, 3 and 5 only.
Design a program to accept any positive integer number and check if it is a Hamming
number or not.
Write a MAIN function to create suitable objects of the class and print the details of
the products by calling the suitable methods
Algorithm:
Algorithm:
Step 1: Start
Step 2: Initialize instance variables as:
. Num 0
Step 3: create an object in main method() to call the function ‘check()’ and
‘accept()’
30
Amanpreet Kaur XII Science Computer Science
WHILE N%P 0
PRINT P
N N/P
IF N>1
PRINT X
IF P 2 OR P 3 OR P 5
RESULT TRUE
CONTINUE
ELSE
RESULT FALSE
P++
IF RESULT TRUE
Step 6: Print the output according to the input given by the user
Step 7: STOP
Solution:
//The following program is completed using member methods/functions
import java.util.Scanner;
class Hamming
{
int num;
31
Amanpreet Kaur XII Science Computer Science
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;
}
System.out.println();
if (isHamming)
System.out.println(original + " IS A HAMMING NUMBER.");
else
System.out.println(original + " IS NOT A HAMMING NUMBER.");
}
32
Amanpreet Kaur XII Science Computer Science
33
Amanpreet Kaur XII Science Computer Science
PROGRAM 07:
Program:
Trinomial Triangle: The trinomial triangle is a number triangle of trinomial
coefficients.
It can be obtained by starting
witharowcontainingasingle"1" and the next row containing three 1s and then letting
subsequent row elements be computed by summing the elements above to the left,
directly above, and above to the right:
1
111
12321
1367631
1 4 10 16 19 16 10 4 1
Write a program to accept the number of terms from the user and print the above
pattern – Trinomial triangle. Use recursive technique to print the pattern.
Algorithm :-
Step 1: Start.
Step 2: Initialize number of rows as 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:
For each column j from 1 to 2*rows-1:
Compute value:
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j] + triangle[i-1][j+1].
34
Amanpreet Kaur XII Science Computer Science
Solution:
public class TrinomialTriangle {
public static void main(String[] args) {
int rows = 7; // Change this to generate more rows
int[][] triangle = new int[rows][2 * rows + 1];
// Middle index for centering the triangle
int mid = rows;
// Base case
triangle[0][mid] = 1;
// Generate 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 triangle
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();
}
}
}
35
Amanpreet Kaur XII Science Computer Science
PROGRAM 8:
Program:
Write a Java program to check whether a given number is a Dudeney Number.
A Dudeney Number is a positive integer which is a perfect cube and the sum of its
digits is equal to its cube root.
Example: 512
1. Sum of digits = 5+1+2=85 + 1 + 2 = 85+1+2=8
2. Cube root of 512 = 888
Therefore, 512 is a Dudeney Number.
The program should:
1. Accept a number from the user.
2. Compute the sum of its digits.
3. Compare the cube of the sum with the original number.
4. Display whether the number is a Dudeney Number or not
5.
Algorithm :-
36
Amanpreet Kaur XII Science Computer Science
Step 1: Start.
Step 2: Input a number number.
Step 3: Define a function sum(int a) to calculate the sum of digits of a.
Initialize s = 0.
Repeat while a > 0:
Extract last digit: digit = a % 10.
Add digit to s.
Update a = a / 10.
Return s.
Step 4: In main, call sum(number) to get numsum.
Step 5: If (numsum^3 == number), then print “number is a Dudeney Number”.
Step 6: Else, print “number is not a Dudeney Number”.
Step 7: Stop.
Solution:
import java.util.Scanner;
public class DudeneyNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = in.nextInt();
//Check if n is a perfect cube
int cubeRoot = (int)Math.round(Math.cbrt(n));
if (cubeRoot * cubeRoot * cubeRoot == n) {
//If n is perfect cube then find
//sum of its digits
int s = 0;
int t = n;
while (t != 0) {
int d = t % 10;
s += d;
t /= 10;
}
if (s == cubeRoot) {
System.out.println(n + " is a Dudeney number");
}
else {
System.out.println(n + " is not a Dudeney number");
}
}
else {
System.out.println(n + " is not a Dudeney number");
}
}
}
37
Amanpreet Kaur XII Science Computer Science
PROGRAM 09:
Program:
Unique Prime Number: A prime number who’s all the digits are unique and not
repeated in the number. For example,3,7,13,37...whereas
11, 101... are not unique prime number
Write a program in Java to accept a positive number and check and print it is a Unique
Prime number or non-unique prime number. Use a separate method for prime check
that will use recursive technique to check
the number passed as argument is prime or not and return true or false.
Algorithm:
Step 1: Start.
Step 2: Input an even number num.
Step 3: Check if num is within the range (6 to 50) and divisible by 2.
Step 4: For each a starting from 3 up to num/2:
Compute b = num - a.
Check if both a and b are prime.
38
Amanpreet Kaur XII Science Computer Science
Solution:
//The following program checks whether the number entered is Goldbach number or
not and displays the output
import java.util.*;
public class Goldbach
{
static boolean prime(int num)
{
int c=0;
for(int i=1;i<=num;i++)
{
if(num%i==0)
{
c++;
}
}
if(c==2)
return true;
else
return false;
}
public static void main(String args[])
{
int PrimeCheck=0, num=0;
Goldbach ob=new Goldbach();
Scanner sc=new Scanner(System.in);
System.out.println("Enter any even number b/w 6 and 50");
num=sc.nextInt();
if((num>=6||num<=50)&&(num%2==0))
{
int b=0, a=3;
while(a<=num/2)
{
b=num-a;
if(prime(a)&&prime(b))
{
System.out.println(a+","+b);
}
a+=2;
}
}
}
}
The following is a computer-generated output (call or invoke the main()
function to get output:
39
Amanpreet Kaur XII Science Computer Science
40
Amanpreet Kaur XII Science Computer Science
PROGRAM 10
Program:
Write a Java program to perform Binary Search on a list of numbers.(using recursion)
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:
Compute m = (l + u) / 2 where l = lower index, u = upper index.
If arr[m] == v, return m.
If l > u, return -1 (element not found).
If arr[m] > v, search in left half (l to m-1).
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:
//The following program checks whether the number entered is Disarium
number or not and displays the output
import java.util.*;
41
Amanpreet Kaur XII Science Computer Science
class BinSearch
{
int arr[];
int n;
static Scanner x=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]=x.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 bin_search(int l,int u, int v )
{
int m=(l+u)/2;
if(arr[m]==v)
return m;
else if(l>u)
return -1;
else if (arr[m]>v)
return bin_search(l,m-1,v);
else
return bin_search(m+1,u,v);
}
static void main()
{
BinSearch obj = new BinSearch(5);
obj.fillarray();
obj.sort();
System.out.println(" location: " + obj.bin_search(0,4,20) );
42
Amanpreet Kaur XII Science Computer Science
}
}
43
Amanpreet Kaur XII Science Computer Science
PROGRAM 11:
Program:
Write a program in Java to demonstrate the Unique Prime Factorization Theorem
(Fundamental Theorem of Arithmetic).
The program should:
1. Accept an integer n (>1) from the user.
2. Find the prime factors of n.
Display the product of prime factors, showing that the factorization is unique (order
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:
Print i (as a prime factor).
Divide n by i (n = n / i).
If n is still greater than 1, print the multiplication symbol " × ".
Repeat Step 7 for the same i.
44
Amanpreet Kaur XII Science Computer Science
Solution:
import java.util.Scanner;
45
Amanpreet Kaur XII Science Computer Science
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:
Find the minimum element rMin in that row.
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.
Step 8: If no such element is found in any row, print “No Saddle Point”.
Step 9: Stop.
Solution:
//Saddle Point
import java.util.*;
public class Saddle //Declaring class name
{
int n;
46
Amanpreet Kaur XII Science Computer Science
47
Amanpreet Kaur XII Science Computer Science
for(int k=0;k<m;k++)
{
if( rMin<a[k][j-1])
{
found =true; //To get the minimum element in matrix
break;
}
if(k==m)
{
System.out.println("Saddle point "+i); //To print the saddle point
}
else
{
System.out.println("No saddle point");
}
}
}
}
}
48
Amanpreet Kaur XII Science Computer Science
49
Amanpreet Kaur XII Science Computer Science
PROGRAM 13:
Program:
Write a program in Java to create a Mirror Matrix.
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)
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 gives the mirror image matrix.
Step 8: End
Solution:
import java.util.Scanner;
50
Amanpreet Kaur XII Science Computer Science
51
Amanpreet Kaur XII Science Computer Science
52
Amanpreet Kaur XII Science Computer Science
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:
Fill the four corners of the square matrix with the first character.
Fill the boundary elements except corners with the second character.
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:
@??@
53
Amanpreet Kaur XII Science Computer Science
?##?
?##?
@??@
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.
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.
Else if (i, j) lies on the boundary (first/last row or column) → store ch2.
Solution:
//The following program checks whether the number entered is Disarium
number or not and displays the output
import java.util.*;
class Matrix
54
Amanpreet Kaur XII Science Computer Science
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
55
Amanpreet Kaur XII Science Computer Science
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
56
Amanpreet Kaur XII Science Computer Science
PROGRAM 15:
Program:
Write a program in Java to check whether a given square matrix of order N × N (where
N = 4) is a Wondrous Square.
Algorithm:
Step 1: Start
Step 2: Input the order of the matrix N (fixed as 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
57
Amanpreet Kaur XII Science Computer Science
Solution:
import java.util.Scanner;
if (wondrous) {
System.out.println("Yes, it represents a wondrous square");
}
else {
System.out.println("Not a wondrous square");
}
58
Amanpreet Kaur XII Science Computer Science
int n = arr.length;
int nSq = n * n;
double validSum = 0.5 * n * (nSq + 1);
/*
* seenArr is used to check that
* numbers are not repeated
*/
boolean seenArr[] = new boolean[nSq];
seenArr[arr[i][j] - 1] = true;
rSum += arr[i][j];
cSum += arr[j][i];
}
return true;
}
public static void printPrime(int arr[][]) {
int n = arr.length;
System.out.println("Prime\tRow Index\tColumn Index");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (isPrime(arr[i][j])) {
System.out.println(arr[i][j] + "\t" + i + "\t\t" + j);
}
}
}
59
Amanpreet Kaur XII Science Computer Science
}
public static boolean isPrime(int num) {
int c = 0;
return c == 2;
}
}
The following is a computer-generated output (call or invoke the main()
function to get output:
60
Amanpreet Kaur XII Science Computer Science
61
Amanpreet Kaur XII Science Computer Science
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
62
Amanpreet Kaur XII Science Computer Science
13 places after it in the alphabets, with the other characters remaining unchanged.
ROT13
A/a B/b C/c D/d E/e F/f G/g H/h I/i J/j K/k L/l M/
m
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/ X/x Y/y Z/z
w
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.
Test your program with the sample data and some random data.
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 the necessary variables: str to store the input text, cipher to store the
encrypted text, len to store the length of the input text, and ch to store each
character from the input string.
63
Amanpreet Kaur XII Science Computer Science
Step 3: Create the main class CaesarCipher and define the main() method.
Step 4: Accept user input by prompting the user to enter a plaintext string and storing
the input string in str. Compute its length and store it in len.
Step 5: Validate the input length. If len is less than or equal to 3 or greater than or
equal to 100, print "INVALID LENGTH" and exit the program.
Step 6: Encrypt the plaintext using ROT13 transformation. Initialize an empty string or
StringBuffer to store the cipher text. Traverse through each character of the input
string. If the character is between 'A' to 'M' or 'a' to 'm', shift it forward by 13
positions. If the character is between 'N' to 'Z' or 'n' to 'z', shift it backward by 13
positions. If the character is not an alphabetic character, keep it unchanged. Append
the transformed character to the cipher text.
Step 8: Stop.
Solution:
import java.util.Scanner;
64
Amanpreet Kaur XII Science Computer Science
else {
sb.append(ch);
}
}
import java.io.*;
import java.util.*;
public class CaesarCipher
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
String str=sc.nextLine();
String st="";
int l=str.length();
if(l>3&&l<100)
{
for(int i=0;i<l;i++)
{
char ch=str.charAt(i);
if(ch>='A'&&ch<='M'||ch>='a'&&ch<='m')
{
st=st+ (char)(ch+13);
}
else if(ch>='N'&&ch<='Z'||ch>='n'&&ch<='z')
{
st=st+ (char)(ch-13);
}
else
{
st=st+ch;
}
}
System.out.println("\nThe cipher text is :\n"+st);
}
else
{
System.out.println("Invalid Length");
}
}
}
65
Amanpreet Kaur XII Science Computer Science
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.
66
Amanpreet Kaur XII Science Computer Science
Solution:
import java.util.Scanner;
public class WordFrequency {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
67
Amanpreet Kaur XII Science Computer Science
System.out.println("The word \"" + word + "\" occurs " + count + " time(s).");
}
}
The following is a computer-generated output (call or invoke the main()
function to get output:
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.
68
Amanpreet Kaur XII Science Computer Science
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):
Step 6.1: Extract the next word.
Step 6.2: Convert the word to lowercase.
Step 6.3: Initialize sum = 0.
Step 6.4: For each character in the word:
If the character is an alphabet ('a' to 'z'), add (character – 'a' + 1) to sum.
Step 6.5: Store sum in potentials[count].
Step 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;
69
Amanpreet Kaur XII Science Computer Science
char ch = word.charAt(i);
if (ch >= 'a' && ch <= 'z') {
sum += ch - 'a' + 1;
}
}
return sum;
}
// Input sentence
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
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++;
}
70
Amanpreet Kaur XII Science Computer Science
sc.close();
}
}
71
Amanpreet Kaur XII Science Computer Science
72