0% found this document useful (0 votes)
75 views72 pages

Computer Science ISC XII

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)
75 views72 pages

Computer Science ISC XII

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/ 72

Amanpreet Kaur XII Science Computer Science

Name: Amanpreet Kaur


Class: XII Section: Science
Roll No. : 07
Computer Applications
Section: 24-25
Index No. : 1245404/011 UID:

Acknowledgement

1
Amanpreet Kaur XII Science Computer Science

I would like to express my sincere gratitude to Miss Moumita Kabi, my Computer


Science teacher, for her invaluable guidance, constant encouragement, and
constructive feedback throughout the development of this Java programming project.
Her dedication and expertise have greatly enhanced my understanding of the subject
and inspired me to work to the best of my ability.

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.

Lastly, I extend my heartfelt thanks to my school, my classmates, and my family for


their support, motivation, and cooperation during the course of this work.

Index

2
Amanpreet Kaur XII Science Computer Science

Serial No. Program Topic Page


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

Signature of Internal Examiner Signature of External


Examiner

______________________________
______________________________

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

1. Step-by-Step Execution – Follows a top-to-bottom flow of control.


2. Procedures (Functions) – Code is grouped into reusable blocks for specific tasks.
3. Global and Local Variables – Data can be stored globally (accessible to all
procedures) or locally (restricted to a specific procedure).
4. Parameter Passing – Data is passed to procedures as arguments and results are
often returned.
5. Modularity – Large programs are divided into smaller, manageable pieces.

Advantages

 Easy to understand for beginners (similar to how humans give step-by-step


instructions).
 Code reusability through functions.
 Easier debugging as each function can be tested separately.
 Structured approach to problem-solving.

Disadvantages

 Not ideal for very large or complex applications.


 Data security is weaker — global variables can be changed from anywhere.
 Difficult to manage changes in big projects — if data structure changes, all
functions using it may need updating.

Examples of Procedural Programming Languages

 C
 Pascal
 FORTRAN
 BASIC
 Java (when used without OOP features)

Example in Java (Procedural Style)


public class SumExample {
public static int addNumbers(int a, int b) {

4
Amanpreet Kaur XII Science Computer Science

return a + b; // procedure
}

public static void main(String[] args) {


int result = addNumbers(5, 10); // calling the procedure
System.out.println("Sum is: " + result);
}
}

Here:

 addNumbers() is a procedure that adds two numbers.


 The program follows a sequence: define → call → output.

Introduction To Java: An Object-Oriented


Programming

5
Amanpreet Kaur XII Science Computer Science

Java is a powerful, object-oriented programming language that was first developed by


Sun Microsystems in 1995, later acquired by Oracle Corporation. Its creators
aimed to create a language that could run on any platform without requiring
modification. This "write once, run anywhere" (WORA) capability has been one of
Java’s defining characteristics. It is widely used for developing applications across

various domains, including web, mobile, desktop, and enterprise systems .


Key Features of Java

1. Object-Oriented Programming (OOP): Java is built around the concept of


objects, which represent instances of classes. In object-oriented programming,
everything revolves around classes and objects. Core OOP concepts like
inheritance, encapsulation, polymorphism, and abstraction are integral to Java,
making it easier to structure and organize code in a scalable way.

2. Platform Independence: Java code is compiled into bytecode, which is an


intermediate form that can run on any device with a Java Virtual Machine (JVM).
This is one of Java’s biggest advantages. Regardless of the underlying hardware
or operating system, Java applications can run uniformly.

3. Multi-threading: Java supports multi-threading, allowing concurrent execution


of two or more parts of a program to maximize CPU utilization. This makes Java
particularly suitable for applications that need to perform many tasks
simultaneously, such as gaming, network applications, and real-time data
processing.

4. High Performance: Although Java is not as fast as lower-level languages like C


or C++, its performance has improved significantly over the years due to the
introduction of Just-In-Time (JIT) compilation and better optimizations in the JVM.
Modern JVMs analyse the bytecode and optimize it at runtime for better
performance.

Java Architecture and Components

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.

Popular Applications and Use Cases

Java is versatile, and its uses span multiple domains:

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.

The Four Basic Object-Oriented Programming


(OOP) principles in Java

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.

Information Hiding is a key aspect of encapsulation, where internal implementation


details are concealed from external code. This allows developers to modify internal
structures without affecting other parts of the program, promoting loose coupling
between classes.

Practical Benefits include enhanced security through validation in setter methods,


easier debugging since data access points are controlled, and improved code
maintainability. For example, a BankAccount class can encapsulate balance data
privately, ensuring withdrawals only occur through controlled methods that verify
sufficient funds.

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.

Encapsulation also supports the principle of least privilege, where code


components only have access to the minimum data and methods necessary for their

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.

Types of Inheritance include single inheritance (one parent class), multilevel


inheritance (chain of parent-child relationships), and hierarchical inheritance (multiple
subclasses from one parent). Java supports single and multilevel inheritance directly,
while multiple inheritance is achieved through interfaces.

Method Overriding is a crucial feature where subclasses can provide specific


implementations of parent class methods using the @Override annotation. This
enables polymorphism, allowing different subclasses to respond differently to the
same method call while maintaining a consistent interface.

Practical Benefits include reduced code duplication, easier maintenance since


changes to the parent class automatically propagate to child classes, and the ability
to create specialized versions of existing classes without modifying the original code.

10
Amanpreet Kaur XII Science Computer Science

Real-world Example: Consider a Vehicles superclass with common properties like


speed and people-holding capacity. Subclasses like Automobiles, Pulled Vehicles
inherit these properties but can override methods like startVehicle() to implement
vehicle-specific behaviour.

The "is-a" relationship is fundamental to inheritance - a Car is-a Vehicle, ensuring


logical class hierarchies. This relationship supports code extensibility, where new
features can be added to existing class families without disrupting established
functionality.

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.

Why it’s useful:


 Code to an interface or superclass and plug in different implementations without
changing the calling code.
 Improves flexibility, testability, and maintainability—new types can be added
with their own behaviour and existing client code keeps working.
Quick mental model
 Overloading: the compiler picks a method based on the parameters at compile
time.
 Overriding: the JVM picks a method based on the actual object at runtime.

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.

When to use which


- Use an interface for capabilities/roles shared across unrelated classes (e.g.,
Comparable, Runnable).
- Use an abstract class when sharing state, common code, or enforcing a partially
implemented template.

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

Hardware And Software Requirement For


JAVA
Below are practical, up-to-date baselines for running modern Java (JDK 21 LTS). Values
reflect Oracle’s certified OS/JVM notes and common tooling requirements.

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;

public class CompositeMagicNumber


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

System.out.print("Enter n: ");
int n = in.nextInt();

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


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

System.out.println("The composite magic numbers 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 && i != 1) {
int num = i;

while (num > 9) {


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

15
Amanpreet Kaur XII Science Computer Science

}
}
System.out.println();
System.out.println("Frequency of composite magic numbers: " + count);
}
}

The following is a computer-generated output (call or invoke the main()


function to get output:

Variable Description Table

Variable Data Type Description

16
Amanpreet Kaur XII Science Computer Science

n int To store numerical value


m int To store the sum
i int Loop control variable for iterating
through numbers from m to n.
j int Inner loop variable used to check
if i has any divisor other than 1
and itself (to determine if it’s
composite).
num int Stores the current number i while
checking whether it is a magic
number (sum of digits process).
sum int Stores the sum of digits of num
during the magic number check.
count int Counter to store the total number
of composite magic numbers
found between m and n
d int Stores the last digit of num while
summing its digits.
iscomposite boolean Flag to indicate whether the
current number i is composite
(true) or not (false).
in scanner Object used to take user input
from the console.

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.

Step 2. Define getDigitCount(int num) method:


Step 2.1 Initialize c = 0 to count digits.
Step 2.2 While num != 0:
Step 2.2.1 Increment c.

Step 2.2.2 Divide num by 10.


Step 2.3 Return c.

18
Amanpreet Kaur XII Science Computer Science

Step 3. In main method:


Step 3.1 Create Scanner in to take input.
Step 3.2 Display message "ENTER INTEGER TO CHECK (N): ".
Step 3.3 Read integer n from user.
Step 3.4 If n <= 0:
Step 3.4.1 Print "INVALID INPUT".
Step 3.4.2 Exit program.

Step 4. Initialize isCircularPrime = true.

Step 5. If isPrime(n) returns true:


Step 5.1 Print n.
Step 5.2 Find digitCount = getDigitCount(n).
Step 5.3 Calculate divisor = 10^(digitCount - 1).
Step 5.4 Assign n2 = n.
Step 5.5 Loop i from 1 to digitCount - 1:
Step 5.5.1 Calculate t1 = n2 / divisor.
Step 5.5.2 Calculate t2 = n2 % divisor.
Step 5.5.3 Set n2 = t2 * 10 + t1.
Step 5.5.4 Print n2.
Step 5.5.5 If !isPrime(n2):
(a) Set isCircularPrime = false.
(b) Break the loop.

Step 6. Else (if n is not prime):


Step 6.1 Set isCircularPrime = false.

Step 7. If isCircularPrime is true:


Step 7.1 Print "n IS A CIRCULAR PRIME.".
Step 8. Else:
Step 8.1 Print "n IS NOT A CIRCULAR PRIME.".

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;

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


if (num % i == 0) {
c++;
}
}

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

The following is a computer-generated output (call or invoke the main()


function to get output:

Variable Description Table

Variable Data Type Description


c(in IsPrime) int Counts the number of factors of
num (used to determine if it’s
prime).
c(in getDigitCount) int Counts the number of digits in
num.
i int Loop control variable in isPrime()
for checking divisibility.
digitCount int Number of digits in n, used for
rotation logic.
divisor int value equal to 10^(digitCount-1),
used to extract the leftmost digit
during rotation
num int Parameter in isPrime() and
getDigitCount() methods
representing the number to check
for primality or to count digits.
t2 int The remaining digits of the
current number (n2) after
removing t1.

t1 int The leftmost digit of the current


number (n2) in the rotation
process.
isCircularPrime boolean Flag to indicate whether the
given number n is a circular

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

(iii) void checkkaprekar( )- to check whether the number entered is


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

23
Amanpreet Kaur XII Science Computer Science

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

public static void main(String args[])


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

24
Amanpreet Kaur XII Science Computer Science

The following is a computer-generated output (call or invoke the main()


function to get 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:

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.
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.
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;

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

26
Amanpreet Kaur XII Science Computer Science

if (sum > n)

System.out.println(n + " is an abundant number.");


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

The following is a computer-generated output (call or invoke the main()


function to get output):

Variable Description Table


Variable Datatype Description
n int Stores the number entered by the user which is
to be checked for being an abundant number.
sum int Accumulates the sum of all proper divisors of n
(excluding n itself)
i int Loop control variable used to check all numbers
from 1 to n-1 as possible divisors.

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;

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;

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

The following is a computer-generated output (call or invoke the main()


function to get output:

29
Amanpreet Kaur XII Science Computer Science

Variable Description Table

Variable Datatype Description


n int The number entered by the user, to be checked
for Smith property.
isComposite boolean Flag to indicate whether n is composite (true) or
not (false).
t int A temporary copy of n, used for digit extraction
and factorization.
d int Stores the current digit extracted from n or a
factor.
sumPrimeDigi int Stores the sum of digits of all prime factors of n.
ts

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

Step 4: Create a method accept() to input the number(NUM)


Step 5: Call member method check()
IF NUM < 0

30
Amanpreet Kaur XII Science Computer Science

PRINT  Negative number Invalid Input


ELSE
P 2
N  NUM
RESULT  TRUE
PRINT  NUM+ " "
WHILE N>1

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

PRINT  " "


PRINT  NUM+"IS A HAMMIMNG NO. HAMMING NUMBER"
ELSE
PRINT " "
PRINT  NUM+"IS NOT A HAMMIMNG NO. "

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;

public void accept()


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
num = sc.nextInt();
}
public void check()
{

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

int original = num;


boolean isHamming = true;

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

// Divide repeatedly by 2, 3, and 5


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 anything remains (>1), it's not a Hamming number


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)


{

32
Amanpreet Kaur XII Science Computer Science

Hamming obj = new Hamming();


obj.accept();
obj.check();
}
}

The following is a computer-generated output (call or invoke the main()


function to get output:

Variable Description Table

Variable Datatype Purpose


num int Stores the number entered by the user and is used
for factorization.
original int Stores a copy of the original number before it is
modified during factorization.
isHamming boolean Flag to indicate whether the number is a Hamming
number (true or false).
n int Copy original number(num)
firstFactor boolean Used to format the multiplication symbol (×)
properly during factor output.
primes int[] Array containing allowed Hamming number prime
factors (2, 3, and 5).
p int To check hamming condition
obj hamming Object of the Hamming class to call the member
methods accept() and check()
sc scanner To take input via keyboard

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

Step 7: Print the triangle:


For each element, print the number if non-zero, else print spaces for formatting.
Step 8: Stop.

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

The following is a computer-generated output (call or invoke the main()


function to get output:

35
Amanpreet Kaur XII Science Computer Science

VARIABLE DESCRIPTION TABLE

Variable Data type Description


rows int Stores the total number of rows
to be generated in the trinomial
triangle.
triangle int[][] 2D array that holds trinomial
coefficients in triangular form.
mid int Stores the middle index of the
array to align the triangle
properly.
i int Loop control variable for rows.
j int Loop control variable for columns
within each row.

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

The following is a computer-generated output (call or invoke the main()


function to get output:

Variable Description Table

Variable Data type Description


a int Used in the sum() function to hold the
number while calculating digit sum.
num int Stores the last extracted digit of the
number.
s int Stores the running total (sum of digits).
number int The number entered by the user to be
checked for Dudeney property.
numsum int Stores the sum of digits of number.
sc Scanner Scanner object used to take input from the
user.
ob Dudeney Object of class Dudeney to call the sum()
method.

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

If yes, print the pair (a, b).


Step 5: Stop.

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

Variable Description Table

Variable Data type Description


a int First prime number in the pair.
b int Second number in the pair such
that a + b = num.
c int Counter used in prime() function
to count factors of a number.
num int Stores the even number entered
by the user.
PrimeCheck int Declared but unused in your code
(can be removed safely).
sc Scanner Scanner object for user input.

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

}
}

The following is a computer-generated output (call or invoke the main()


function to get output:

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.
x 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 and searching.
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 (used in main).
location int Stores the index where the
searched value is found (or -1 if
not found).

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.

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

44
Amanpreet Kaur XII Science Computer Science

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;
if (n > 1) {
System.out.print(" × "); // Display multiplication sign
}
}
}
}
}

The following is a computer-generated output (call or invoke the main()


function to get output:

45
Amanpreet Kaur XII Science Computer Science

VARIABLE DESCRIPTION TABLE

Variable Data type Description


sc Scanner To take input from user
n int Input number, reduced during
factorization
x Scanner Scanner object to take input from
the user.
temp int Stores the original number for
display
i int Loop counter to test possible
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:
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

int a[][]=new int[n][n]; //Creating array of class


public void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of matrix"); //To iput the size of matrix
n=sc.nextInt();
{
for(int i=0;i<n;i++)
{
System.out.println("Row "+(i+1));
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt(); //To input elements in the matrix
}
}
}
if(n>20) //Condition for invalid input
{
System.out.println("Invalid Input");
return;
}
System.out.println("The original matrix is"); //Printing the original matrix
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.println(a[i][j]);
}
}
}

public void compute() //Method to find saddle point


{
int rMin;
int cIdx;
int m=n;
boolean found =false; //Flag variable to find saddle point
for(int i=0;i<m;i++)
{
rMin=a[i][0];
cIdx=0;

for(int j=1;j<m;j++) //Condition for finding the saddle point


{
if( rMin>a[i][j])
{
rMin=a[i][j]; //To get the minimum element
cIdx=j;

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

public static void main(String args[]) //Declaring the main method


{
Saddle ob=new Saddle(); //Creating object of class
ob.input(); //Calling the member method
ob.compute();
}
}

The following is a computer-generated output (call or invoke the main()


function to get output:

48
Amanpreet Kaur XII Science Computer Science

VARIABLE DESCRIPTION TABLE

VARIABLE DATA TYPE DESCRIPTION


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 Stores the minimum element in
the current row.
cIdx int Column index of the minimum
element in the current row.
m int Copy of matrix size n used in
loops.
found boolean Flag variable to indicate whether
a Saddle Point is found.

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;

public class MirrorMatrix {


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

50
Amanpreet Kaur XII Science Computer Science

// 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++) {
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();
}
}
}

The following is a computer-generated output (call or invoke the main()


function to get output:

51
Amanpreet Kaur XII Science Computer Science

Variable Description Table

Variable Data Type Purpose


N int Order (size) of the square matrix
arr int[][] 2D array to store matrix elements
i int Loop variable used for iterating over matrix
rows
j int Loop variable used for iterating over matrix
columns
sc scanner Used to take user input from the
console.

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.

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:
//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);

// Input matrix size


System.out.println("Enter number of rows M of a square matrix:");
int m = sc.nextInt();

// Check for valid size


if (m <= 0) {
System.out.println("Invalid matrix size. M must be greater than 0.");
sc.close();
return;
}

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

// Input characters for different parts of the matrix


System.out.println("Enter corner elements - 1st character:");
char ch1 = sc.next().charAt(0);

System.out.println("Enter boundary except corner elements - 2nd character:");


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

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


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
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++) {

55
Amanpreet Kaur XII Science Computer Science

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

sc.close(); // Close the scanner to avoid resource leaks


}
}

Variable Description Table

Variable Data Type Purpose


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 used for iterating over matrix
rows
j int Loop variable used for iterating over matrix
columns
sc scanner Used to take user input from the
console.

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.

A Wondrous Square is defined as:


It contains all numbers from 1 to N × N exactly once.
The sum of each row and each column is equal to the same constant (called the
Wondrous Number).

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;

public class WondrousSquare


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

if (n < 2 || n > 10) {


System.out.println("Invalid value of n!");
return;
}

int a[][] = new int[n][n];

System.out.println("Enter elements of the matrix: ");


for (int i = 0; i < n; i++) {
System.out.println("Enter Row "+ (i+1) + " :");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println("The 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 Wondrous
int nSq = n * n;
double validSum = 0.5 * n * (nSq + 1);
boolean wondrous = isWondrous(a);

if (wondrous) {
System.out.println("Yes, it represents a wondrous square");
}
else {
System.out.println("Not a wondrous square");
}

//Print Prime Numbers


printPrime(a);
}

public static boolean isWondrous(int arr[][]) {

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

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

int rSum = 0, cSum = 0;

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


if (arr[i][j] < 1 || arr[i][j] > nSq) {
return false;
}

//Number is not distinct


if (seenArr[arr[i][j] - 1]) {
return false;
}

seenArr[arr[i][j] - 1] = true;

rSum += arr[i][j];
cSum += arr[j][i];
}

if (rSum != validSum || cSum != validSum) {


return false;
}
}

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;

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


if (num % i == 0) {
c++;
}
}

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

Variable Description Table

Variable Data Type Purpose


m int Stores the size of the square matrix
mat char[][] 2D array used to store the matrix elements

61
Amanpreet Kaur XII Science Computer Science

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 used for iterating over matrix
rows
j int Loop variable used for iterating over matrix
columns
sc scanner Used to take user input from the
console.

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 7: Display the cipher text by printing the encrypted message.

Step 8: Stop.

Solution:

//The following program checks whether the number entered is Disarium


number or not and displays the output

import java.util.Scanner;

public class CaesarCipher


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter plain text:");
String str = in.nextLine();
int len = str.length();

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


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

StringBuffer sb = new StringBuffer();


for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
sb.append((char)(ch + 13));
}
else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
sb.append((char)(ch - 13));
}

64
Amanpreet Kaur XII Science Computer Science

else {
sb.append(ch);
}
}

String cipher = sb.toString();


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

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

VARIABLE DESCRIPTION TABLE


Variable Data Type Purpose
str String Stores the input plaintext entered by the
user.
cipher StringBuffer Stores the encrypted text after applying the
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 iterating
through the string.
sc Scanner Used to take user input from the
console.

The following is a computer-generated output (call or invoke the main()


function to get output:

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

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:
Step 7.1: Compare the current word with the given word.
Step 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);

// Step 1: Input sentence


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

// Step 2: Input word to search


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

// Step 3: Convert both to lowercase


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

// Step 4: Split sentence into words


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

// Step 5: Count frequency


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

// Step 6: Display result

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:

Variable Description Table


Variable Data Type Purpose
w String Represents each word in the array during
traversal

word String Stores the word whose frequency is to be


checked
words String[] Array of words obtained by splitting the
sentence
count int Stores the number of times the word occurs
sentence String Stores the input sentence
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.

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;

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++) {

69
Amanpreet Kaur XII Science Computer Science

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

70
Amanpreet Kaur XII Science Computer Science

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

The following is a computer-generated output (call or invoke the main()


function to get output

71
Amanpreet Kaur 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 StringTokeniz Used to break the sentence into words
er (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.

72

You might also like