Download as pdf or txt
Download as pdf or txt
You are on page 1of 481

A TEXT BOOK OF

ISC
COMPUTER
SCIENCE
In accordance with the latest syllabus prescribed by the Council for the
Indian School Certificate Examinations, New Delhi.

A TEXT BOOK OF

ISC
COMPUTER
SCIENCE
CLASS XI
VOLUME

By
Rupa Pandit
MCA, Head of Dept. (Computer Science)
The Assembly of God Church School (Kolkata)

OSWAL PUBLISHERS
1/12, Sahitya Kunj, M. G. Road, Agra-282 002
No Part of this book can be reproduced in any form or by any means without the
prior written permission of the publisher.

Edition : 2019

OSWAL PUBLISHERS
Head office : 1/12, Sahitya Kunj, M. G. Road, Agra-282 002
Phone : (0562) 2527771-4, +91 75340 77222
E-mail : contact@oswalpublishers.com, sales@oswalpublishers.com
Website : www.oswalpublishers.com
Facebook link : https://www.facebook.com/oswalpublishersindia
Available at : amazon.in, Flipkart, snapdeal, paytm
Printed at : Upkar Printing Unit, Agra
Preface

This book introduces each topic fundamentally and gradually explains


advanced concepts to help students learn the curriculum in an interesting
manner. Clear language coupled with lucid flow and applicable examples have
been meticulously put together to make it easy for students to grasp each topic.
Explanations can be brief or detailed. However, every explanation has one
common aim to make the topic understandable. Special care has been taken to
cover the areas where students may face difficulty and a plethora of examples
have been demonstrated to solve the problems. Effort has been put to help
embed concepts for life and not with a rote learning attitude.
Plenty of worked out exercises, programs and the algorithmic details cater
to the needs of all kinds of students. The book keeps the spirit of learning as
a base. Explanations have been kept close to the working method. Efforts have
been put into solving the actual doubts that are encountered while learning.
We welcome all the constructive suggestions that will help to improve the
pedagogy of the subject title. Please feel free to mail your opinions & queries
at oswalpublishers@gmail.com.
— PUBLISHER

Acknowledgement
I would like to thank the Almighty without whose guidance and blessings
this book would have never been a reality and the team of Oswal Publishers for
their constant support throughout the project. A huge amount of gratitude to my
family, friends and all my dear students for their continuous love and support.
— AUTHOR
SYLLABUS CLASS XI
COMPUTER SCIENCE (868)
Aims (Conceptual) (3) To create awareness of ethical issues related
(1) To understand algorithmic problem to computing and to promote safe, ethical
behavior.
solving using data abstractions, functional
and procedural abstractions, and object (4) To make students aware of future trends in
based and object oriented abstractions. computing.
(2) To understand : (a) how computers
represent, store and process data at Aims (Skills)
different levels of abstraction that mediate To devise algorithmic solutions to
between the machine and the algorithmic problems and to be able to code, validate,
problem solving level and (b) how they document, execute and debug the solution
communicate with the outside world. using the Java programming system.

CLASS XI
There will be two papers in the subject : numbers (when programming is discussed). For
Paper I : Theory............. 3 hours…70 marks addition and subtraction (1’s complement and
2’s complement) use the analogy with decimal
Paper II : Practical....... 3 hours…30 marks numbers, emphasize how carry works (this will
be useful later when binary adders are discussed).
PAPER I –THEORY – 70 MARKS 2. Encodings
Paper 1 shall be of 3 hours duration and be divided (a) Binary encodings for integers and real
into two parts. numbers using a finite number of bits
Part I (20 marks) : This part will consist of (sign-magnitude, 2’s complement,
compulsory short answer questions, testing knowledge, mantissa-exponent notation).
application and skills relating to the entire syllabus. Signed, unsigned numbers, least and most
significant bits. Sign-magnitude represen-
Part II (50 marks) : This part will be tation and its shortcomings (two represen-
divided into three Sections, A, B and C. Candidates tations for 0, addition requires extra
will be required to answer two questions out of step); two’s-complement representation.
three from Section A (each carrying 10 marks) and Operations (arithmetic, logical, shift),
two questions out of three from Sections B (each discuss the basic algorithms used for the
carrying 10 marks) and two questions out of three arithmetic operations. Floating point
from Section C (each carrying 5 marks). Therefore, a representation: normalized scientific
total of six questions are to be answered in Part II. notation, mantissa-exponent represen-
tation, binary point (discuss trade-off
SECTION A between size of mantissa and exponent).
Single and double precision.
Basic Computer Hardware and Software
(b) Characters and their encodings (e.g.,
1. Numbers ASCII, ISCII, Unicode).
Representation of numbers in different Discuss the limitations of the ASCII code in
bases and interconversion between them representing characters of other languages.
(e.g., binary, octal, decimal, hexadecimal). Discuss the Unicode representation for
Addition and subtraction operations for the local language. Java uses Unicode,
numbers in different bases. so strings in the local language can be
Introduce the positional system of representing used (they can be displayed if fonts are
numbers and the concept of a base. Discuss available) – a simple table lookup for
the conversion of representations between local language equivalents for Latin (i.e.,
different bases using English or pseudo code. English) character strings may be done.
These algorithms are also good examples for More details on Unicode are available at
defining different functions in a class modelling www.unicode.org.
3. Propositional logic, hardware imple- Difference between object and class
mentation, arithmetic operations should be made very clear. BlueJ
(a) Propositional logic, well formed (www.bluej.org) and Greenfoot
(www.greenfoot.org) can be used for
formulae, truth values and inter-
this purpose.
pretation of well formed formulae,
truth tables. (b)
Analysis of some real-world
programming examples in terms of
Propositional variables; the common logical
objects and classes.
connectives (~ (not)(negation),  (and)
(conjunction),  (or)(disjunction), ⇒ Use simple examples like a
(implication), ⇔ (equivalence)); calculator, date, number etc. to
definition of a well-formed formula (wff); illustrate how they can be treated as
representation of simple word problems as objects that behave in certain well-
defined ways and how the interface
wff (this can be used for motivation); the
provides a way to access behaviour.
values true and false; interpretation of a
Illustrate behaviour changes by adding
wff; truth tables; satisfiable, unsatisfiable
new methods, deleting old methods or
and valid formulae.
modifying existing methods.
(b) Logic and hardware, basic gates (AND,
(c) Basic concept of a virtual machine;
NOT, OR) and their universality, other Java Virtual Machine (JVM);
gates (NAND, NOR, XOR, XNOR); half compilation and execution of
adder, full adder. Java programs (the javac and java
Show how the logic in (a) above can programs).
be realized in hardware in the form of The JVM is a machine but built as a
gates. These gates can then be combined program and not through hardware.
to implement the basic operations for Therefore it is called a virtual machine.
arithmetic. Tie up with the arithmetic To run, JVM machine language
operations on integers discussed earlier in 2 programs require an interpreter. The
(a). advantage is that such JVM
machine language programs (.class files)
are portable and can run on
SECTION B
any machine that has the java
The programming element in the syllabus is program.
aimed at algorithmic problem solving and
not merely rote learning of Java syntax. The (d) Compile time and run time errors;
Java version used should be 5.0 or later. For basic concept of an exception, the
programming, the students can use any text Exception class, try-catch, throw,
editor and the javac and java programs or throws and finally.
any other development environment: for Differentiate between compile time and
example, BlueJ, Eclipse, NetBeans etc. BlueJ is run time errors. Run time errors crash
strongly recommended for its simplicity, ease
the program. Recovery is possible by the
of use and because it is very well suited for an
use of exceptions. Explain how an
‘objects first’ approach.
exception object is created and passed
4. Introduction to Object Oriented up until a matching catch is found. This
Programming using Java behaviour is different from the one
Note that topics 5 to 12 should be introduced where a value is returned by
almost simultaneously along with Classes a deeply nested method call.
and their definitions.
6. Primitive values, Wrapper classes,
5. Objects Types and casting
(a) Objects as data (attributes) + Primitive values and types: byte, int,
behaviour (methods or methods); short, long, float, double, boolean, char.
object as an instance of a class. Corresponding wrapper classes for
each primitive type. Class as type of 9. Methods and Constructors
the object. Class as mechanism for user Methods and Constructors (as
defined types. Changing types through abstractions for complex user defined
user defined casting and automatic type operations on objects), methods as
coercion for some primitive types.
mechanisms for side effects; formal
Ideally, everything should be a class; primitive arguments and actual arguments in
types are defined for efficiency reasons; each methods; different behaviour of primitive
primitive type has a corresponding wrapper and object arguments. Static methods and
class. Classes as user defined types. In some variables. The this operator. Examples
cases types are changed by automatic of algorithmic problem solving using
coercion or casting – e.g., mixed type methods (number problems, finding roots
expressions. However, casting in general is of algebraic equations etc.).
not a good idea and should be avoided, if
possible. Methods are like complex operations where
the object is implicitly the first argument.
7. Variables, Expressions Operator this denotes the current object.
Variables as names for values; named Methods typically return values. Illustrate
constants (final), expressions (arithmetic the difference between primitive values and
and logical) and their evaluation object values as arguments (changes made
(operators, associativity, precedence). inside methods persist after the
Assignment operation; difference call for object values). Static definitions as
between left-hand side and right-hand class variables and class methods visible
side of assignment. and shared by all instances. Need for
Variables denote values; variables are already static methods and variables. Introduce the
defined as attributes in classes; variables main method – needed to begin execution.
have types that constrain the values it Constructor as a special kind of method; the
can denote. Difference between variables new operator; multiple constructors with
denoting primitive values and object values different argument structures; constructor
– variables denoting objects are references to returns a reference to the object.
those objects. The assignment operator = is
10. Arrays, Strings
special. The variable on the LHS of =
denotes the memory location while Structured data types – arrays (single
the same variable on the RHS denotes the and multi-dimensional), strings. Example
contents of the location e.g., i=i+2. algorithms that use structured data
types (searching, finding maximum/
NOTE : Library functions for solving
minimum, sorting techniques, solving
expressions may be used as and when
systems of linear equations, substring,
required.
concatenation, length, access to char in
8. Statements, Scope string, etc.).
Statements; conditional (if, if else, if else Storing many data elements of the same
if, switch case) ternary operator, looping type requires structured data types – like
(for, while, do while), continue, break; arrays. Access in arrays is constant time
grouping statements in blocks, scope and and does not depend on the number of
visibility of variables. elements. Sorting techniques (bubble,
Describe the semantics of the conditional selection, insertion), Structured data types
and looping statements in detail. Evaluation can be defined by classes – String. Introduce
of the condition in conditional statements. the Java library String class and the basic
operations on strings (accessing individual
Nesting of blocks. Variables with block
scope, method scope, class scope. Visibility characters, various substring operations,
rules when variables with the same name are concatenation, replacement, index of
defined in different scopes. operations).
SECTION C 13. Implementation of algorithms to solve
problems
11. Basic input/output Data File Handling
(Binary and Text) The students are required to do lab
assignments in the computer lab
(a) Basic input/output using Scanner
concurrently with the lectures. Progra-
and Printer classes.
mming assignments should be done
Input/output exceptions. Tokens in an such that each major topic is covered
input stream, concept of whitespace, in at least one assignment. Assignment
extracting tokens from an input stream problems should be designed so that
(String Tokenizer class). The Scanner they are sufficiently challenging and
class can be used for input of various make the student do algorithm design,
types of data (e.g., int, float, char address correctness issues, implement
etc.) from the standard input stream. and execute the algorithm in Java and
Similarly, the Printer class handles debug where necessary.
output. Only basic input and output
Self-explanatory.
using these classes should be covered.
14. Packages
Discuss the concept of a token (a
delimited continuous stream of Definition, creation of packages,
characters that is meaningful in the importing user defined packages,
application program – e.g., words in a interaction of objects across packages.
sentence where the delimiter is the blank Java Application Programming Interface
character). This naturally leads to (API), development of applications using
the idea of delimiters and in particular user defined packages.
whitespace and user defined characters
15. Trends in computing and ethical issues
as delimiters. As an example show how
the StringTokenizer class allows one (a) Artificial Intelligence, Internet of
to extract a sequence of tokens from a Things, Virtual Reality and
string with user defined delimiters. Augmented Reality.
(b) Data File Handling. Brief understanding of the above and
their impact on Society.
Need for Data file, Input Stream, Output
Stream, Byte Stream (FileInputStream (b) Cyber Security, privacy, netiquette,
and FileOutputStream), Character spam, phishing.
Stream (FileReader, FileWriter), Brief understanding of the above.
Operations - Creation, Reading,
(c) Intellectual property, Software
Writing, Appending, and Searching.
copyright and patents and Free
12. Recursion Software Foundation.
Concept of recursion, simple recursive Intellectual property and corresponding
methods (e.g., factorial, GCD, binary laws and rights, software as intellectual
search, conversion of representations of property.
numbers between different bases). Software copyright and patents and the
Many problems can be solved very elegantly difference between the two; trademarks;
by observing that the solution can be software licensing and piracy. free
composed of solutions to ‘smaller’ versions Software Foundation and its position on
of the same problem with the base version software, Open Source Software, various
having a known simple solution. Recursion types of licensing (e.g. GPL, BSD).
can be initially motivated by using recursive Social impact and ethical issues should
equations to define certain methods. These be discussed and debated in class. The
definitions are fairly obvious and are easy to important thing is for students to
understand. The definitions can be directly realise that these are complex issues
converted to a program. Emphasize that any and there are multiple points of view
recursion must have a base case. Otherwise, on many of them and there is no single
the computation can go into an infinite loop. ‘correct’ or ‘right’ view.
PAPER II : PRACTICAL – 30 MARKS 2. Creating an expert system for medical
diagnosis on the basis of symptoms and
This paper of three hours duration will be
prescribe a suitable treatment.
eveluated internally by the school.
The paper shall consist of three programming 3. Creating a security system for age-
problems from which a candidate has to appropriate access to social media.
attempt any one. The practical consists of the 4. Simulate Adders using Arduino
two parts : Controllers and Components.
(1) Planning Session 5. Simulate a converter of Binary to Decimal
(2) Examination Session number systems using Arduino
Controllers and Components.
The total time to be spent on the Planning
session and the Examination session is three 6. Develop a console-based application
hours. A maximum of 90 minutes is permitted using Java for Movie Ticket
for the Planning session and 90 minutes for Reservation.
the Examination session. Candidates are to 7. Develop a console-based application
be permitted to proceed to the Examination using Java to encrypt and decrypt a
Session only after the 90 minutes of the message (using cipher text, Unicode-
Planning Session are over. exchange, etc).
Planning Session 8. Develop a console-based application
The candidates will be required to prepare an using Java to find name of the bank and
algorithm and a hand-written Java program branch location from IFSC.
to solve the problem. 9. Develop a console-based application
Examination Session using Java to calculate taxable income
(only direct tax).
The program handed in at the end of the
Planning session shall be returned to the 10. Develop a console-based application
candidates. The candidates will be required using Java to develop a simple text editor
to key-in and execute the Java program on (text typing, copy, cut, paste, delete).
seen and unseen inputs individually on
the Computer and show execution to the EVALUATION
examiner. A printout of the program listing, Marks (out of a total of 30) should be
including output results should be attached distributed as given below :
to the answer script containing the algorithm
and handwritten program. This should be Continuous Evaluation
returned to the examiner. The program Candidates will be required to submit a work
should be sufficiently documented so that the
file containing the practical work related to
algorithm, representation and development
programming assignments done during the
process is clear from reading the program.
Large differences between the planned year and ONE project.
program and the printout will result in loss of
marks. Programming assignments done 10
throughout the year marks
Teachers should maintain a record of all the
assignments done as part of the practical
work throughout the year and give it due Project Work (based on any topic 5
credit at the time of cumulative evaluation at from the syllabus) marks
the end of the year. Students are expected
to do a minimum of twenty assignments Terminal Evaluation
for the year and ONE project based on the Solution to programming problem 15
syllabus.
on the computer Marks
List of suggested projects : List
(Marks should be given for choice
PRESENTATION / MODEL BASED/
of algorithm and implementation
APPLICATION BASED
strategy, documentation, correct output on
1. Creating an expert system for road-traffic known inputs mentioned in the question
management (routing and re-routing paper, correct output for unknown inputs
of vehicles depending on congestion). available only to the examiner).
CONTENTS
1A. Numbers 13 – 33

1B. Arithmetic Operations 34 – 62

2. Encodings 63 – 83

3. Propositional Logic 84 – 101

4. Logic Gates 102 – 118

5. Introduction to Java 119 – 134

6. Java Statements 135 – 159

7. Exception Handling 160 – 174

8. Methods (Functions) 175 – 197

9. Program Tools and Arrays 198 – 226

10. Array Applications Sort and Search 227 – 243

11. Strings and Library Methods 244 – 300

12. Data File Handling 301 – 338

13. Recursive Functions 339 – 348

14. Packages 349 – 359

15. Social Context of Computing and Ethical Issues 360 – 371

16. Algorithm 372 – 379

17. Programs and Algorithms. 380 – 477


NUMBERS
1A

l Numbers

l Base of a Number System


l Generating Numbers in a Number system
l Number Chart
l Relationship between numbers of various Number Systems
l Conversion of Numbers from one base to another

NUMBERS
Numbers are used for counting. They are made up of symbols, which are called
digits. Digits are finite, but numbers are infinite. So, digits are used in an orderly
combination to represent numbers even when they get exhausted.
After the last digit has been used, the next number is made by combining the first two
digits. That’s why when 1 digit numbers are over, two digit numbers appear. Similarly
when two digit numbers exhaust, three digit numbers are introduced, and so on.

BASE OF A NUMBER SYSTEM


Base of a number system states how many single digits are present for use. The most
commonly used number system is decimal number system, where the base is 10. For base
10, there are 10 single digits available for use, which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
There are other bases too, namely – binary, octal, hexadecimal to name a few.
In binary number system, the base is 2. In this system, there are only 2 digits, which
are 0 and 1.
In octal number system, the base is 8 as there are 8 digits, which are 0 1 2 3 4 5 6 7.
In hexadecimal number system, the base is 16 as there are 16 digits, which are 0 1
2 3 4 5 6 7 8 9 A B C D E F.
ISC COMPUTER SCIENCE – XI

GENERATING NUMBERS IN A NUMBER SYSTEM

The numbers are generated by reusing the digits in combination, when single digits
are exhausted. In the various number systems, 10 appears at different levels depending
on the number of digits present in that number system.
In binary number system, digits exhaust after 1 [0 1]. Thus, 10 appears after 1. So,
the sequence of numbers are :
0 1 10 11 100 101 110 111 1000……
In octal number system, digits exhaust after 7 [ 0 1....6 7]. Thus, 10 appears after 7.
So, the sequence of numbers is : 0 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21
.....75 76 77 100 101…
In decimal number system, digits exhaust after 9 [ 0 1...7 8 9]. Thus, 10 appears
after 9. So, the sequence of numbers is : 0 1 2 3 4 5 6 7 8 9 10 11 12…17 18 19 20
…98 99 100 101…
In hexadecimal number system, digits exhaust after F [ 0 1...8 9 A B…E F]. Thus,
10 appears after F. So, the sequence of numbers is : 0 1 2 3…8 9 A B…F 10 11 12 13
14…19 1A.....1F 20 21…28 29 2A 99 9A 9B…9F A0 A1 A2…BF C0 E FF 100 101…
Note : Digit combination begins only after the digits are exhausted.
An Observation :
Look at the following digital representations. Each digit has a value before and after
it. For various bases, the total number of digits is different.
Can you tell how does a number get incremented or decremented ?

8 D F 9

9 E 0 A

A F 1 B

EXAMPLES :
Q. 1. For the following numbers, write the next 5 numbers in the given number
system.
(i) (5)8 (ii) (11)2
(iii) (19)16 (iv) (76)8
(v) (9C)16
Ans. The next 5 numbers are :
(i) (5)8 – 6 7 10 11 12
(ii) (11)2 – 100 101 110 111 1000
(iii) (19)16 – 1A 1B 1C 1D 1E
(iv) (76)8 – 77 100 101 102 103
(v) (9C)16 – 9D 9E 9F A0 A1

14
NUMBERS

Q. 2. For the following numbers, write the previous 5 numbers in the given number
system.
(i) (11)8 (ii) (10101)2
(iii) (AA)16 (iv) (100)8
(v) (12)16
Ans. The previous 5 numbers are :
(i) (11)8 – 10 7 6 5 4
(ii) (10101)2 – 10100 10011 10010 10001 10000
(iii) (AA)16 – A9 A8 A7 A6 A5
(iv) (100)8 – 77 76 75 74 73
(v) (12)16 – 11 10 F E D

NUMBER CHART

Binary Octal Decimal Hexadecimal


0 0 0 0
1 1 1 1
10 2 2 2
11 3 3 3
100 4 4 4
101 5 5 5
110 6 6 6
111 7 7 7
1000 10 8 8
1001 11 9 9
1010 12 10 A
1011 13 11 B
1100 14 12 C
1101 15 13 D
1110 16 14 E
1111 17 15 F
10000 20 16 10
10001 21 17 11
10010 22 18 12
10011 23 19 13
10100 24 20 14
… … … …

15
ISC COMPUTER SCIENCE – XI

RELATIONSHIP BETWEEN NUMBERS


OF VARIOUS NUMBER SYSTEMS
The same value is represented with different combination of digits in different
number systems.
For example : 3 in decimal system is 11 in binary number system.
10 in octal system is 8 in decimal number system.
10 in decimal system is A in hexadecimal number system.
20 in octal system is 10 in hexadecimal number system.
Note : The reason behind different number systems having same value represented
differently is the difference in the number of digits present in each number
system.
Note : Binary number system is useful for representing bits of computer signals,
which can be either 0 or 1.
Note : Hexadecimal number system is useful for representing huge numbers. The
computer memory is numbered in hexadecimal system.

CONVERSION OF NUMBERS FROM


ONE BASE TO ANOTHER

S. No. Base From Base To


I Binary
II Decimal Octal
III Hexadecimal
IV Binary
V Octal Decimal
VI Hexadecimal
VII Octal
Binary
VIII Hexadecimal
IX Octal
Binary
X Hexadecimal
XI Octal Hexadecimal
XII Hexadecimal Octal

I. CONVERSION FROM DECIMAL TO BINARY :


Integer Value Conversion
To convert an integer decimal number to binary, divide the decimal number
continuously by 2. The corresponding binary number can be obtained by tracing the
remainders in reverse order.
16
NUMBERS
The following examples show the method.
During calculation, the number being divided is replaced by the quotient. The
process of finding remainder carries on till the quotient does not become 0.
Ex 1. (19)10 = (?)2

Binary base Number Process Remainder


2 19 19/2 Q = 9 R = 1 1
2 9 9/2 Q=4 R=1 1
2 4 4/2 Q=2 R=0 0
2 2 2/2 Q=1 R=0 0
2 1 1/2 Q=0 R=1 1
0
The corresponding binary number is the remainders in reverse order.
Thus, (19)10 = (10011)2
Ans : 10011
Ex 2. (24)10 = (?)2

Binary base Number Remainder


2 24 0
2 12 0
2 6 0
2 3 1
2 1 1
0

The corresponding binary number is the remainders in reverse order.


Thus, (24)10 = (11000)2
Ans. 11000
Fractional Value Conversion
A fractional value has two parts – integer part and fractional part. The conversion
takes place separately for the integer part and for the fractional part.
Conversion of integer part is the same as shown above.
Conversion of fractional part is done by continuous multiplication of the fractional
part by 2. In this process, the integer generated (either 0 or 1) is taken aside and the rest
of the fractional part is multiplied by 2. The process stops when the fractional part’s
result is 0 or becomes recursive.

Note : For the integer conversion part, the remainders are taken in reverse order and
for the fractional part, the quotients are taken in forward order.

17
ISC COMPUTER SCIENCE – XI
Ex 3. (30.25)10 = (?)2
The integer part — [Same as shown before, (30)10 = (11110)2]
Remainder
Binary base Number
Integer
2 30 0
2 15 1
2 7 1
2 3 1
2 1 1
0
The fractional part :

Binary base Number Process Integer


.25 * 2 = 0.5
2 0.25 0
I = 0 F = 0.5
.5 * 2 = 1.0
2 0.5 1
I = 1 F = 0.0
2 0.0
So, (.25 )10 = (.01)2
Final Ans : (30.25)10 = (11110.01)2
Ex 4. (12.2)10 = (?)2
In this case, the fractional part gives a recurring answer.
The integer part—(12)10 = (1100)2
Binary base Number Remainder
2 12 0
2 6 0
2 3 1
2 1 1
0
The fractional part—(0.2)10 = (0.0011)2 [recurring] [the table shows the working]

Binary base Number Process Integer


2 0.2 .2 * 2 = 0.4 ; I = 0 F = 0.4 0
2 0.4 .4 * 2 = 0.8 ; I = 0 F = 0.8 0
2 0.8 .8 * 2 = 1.6 ; I = 1 F = 0.6 1

18
NUMBERS

2 0.6 .6 * 2 = 1.2 ; I = 1 F = 0.2 1


2 0.2 .2 * 2 = 0.4 ; I = 0 F = 0.4 0 (repeats)
[Ans : (12.2)10 = (1100.0011)2, recurring]
Ex 5. (25.375)10 = (?)2
For the integer Part (25)
Binary base Number Remainder
2 25 1
2 12 0
2 6 0
2 3 1
2 1 1
0
The fractional part – (0.2)10 = (0.0011)2 [recurring] [the table shows the working]

Binary base Number Process Integer

.375 * 2 + 0.75 ;
2 0.375 0
1 = 0 F = 0.75
.75 * 2 = 1.5 ;
2 0.75 1
I = 0 F = 0.5
.5 * 2 = 1.0;
2 0.5 1
I = 1 F = 0.0
2 0.0
Ans : (25.375 )10 = (11001.011)2
II. CONVERSION FROM DECIMAL TO OCTAL :
Integer Value Conversion
To convert an integer decimal number to octal, divide the decimal number
continuously by 8 till it becomes 0. The corresponding octal number can be obtained by
tracing the remainders in reverse order.
Ex 1. (125)10 = (?)8

Octal base Number Process Remainder

8 125 125/8 Q = 15 R = 5 5

8 15 15/8 Q=1 R=7 7

8 1 1/8 Q=0 R=1 1

8 0

19
ISC COMPUTER SCIENCE – XI

Ans : (175)8
Ex 2. (100)10 = (?)8
Octal base Number Process Remainder

8 100 100/8 Q = 12 R = 4 4

8 12 12/8 Q=1 R=4 4

8 1 1/8 Q=0 R=1 1

8 0

Ans : (144)8
Fractional Value Conversion
To convert the fractional part, multiply it with 8. Keep aside the integer generated
(digit value between 0 to 7), and the next fractional part is multiplied by 8. The process
stops when the fractional part’s result is 0 or the value becomes recurring.
Ex 3. (90.25)10 = (?)8
The integer part — [Same as shown before, (90)10 = (132)8]
The fractional part—
Octal base Number Process Integer
.25 * 8 = 2.00
8 0.25 2
I = 2 F = 0
8 0.0
So, (.25 )10 = (.2)8
Final Ans : (90.25)10 = (132.2)8
Ex 4. (80.175)10 = (?)8
The integer part — [Same as shown before, (80)10 = (120)8]
The fractional part is recurring. — (.175 )10 = (1.3146 )2 [the table shows the working]

Octal base Number Process Integer


.175 * 8 = 1.400
8 0.175 1
I = 1 F = 0.4
.4 * 8 = 3.2
8 0.4 3
I = 3 F = 0.2
.2 * 8 = 1.6
8 0.2 1
I = 1 F = 0.6
.6 * 8 = 4.8
8 0.6 4
I = 4 F = 0.8
.8 * 8 = 6.4
8 0.8 6
I = 6 F = 0.4

20
NUMBERS

.4 * 8 = 3.2
8 0.4 3 [ repeats]
I = 3 F = 0.2
Final Ans : (80.175 )10 = (120. 3146)8
III. CONVERSION FROM DECIMAL TO HEXADECIMAL
Integer Value Conversion
To convert an integer decimal number to hexadecimal, divide the decimal number
continuously by 16 till it becomes 0. The corresponding hexadecimal number can be
obtained by tracing the remainders in reverse order.
Ex 1. (76)10 = (?)16 

Hexadecimal base Number Process Remainder


16 76 76/16 Q = 4 R = 12(C) C
16 4 4/16 Q = 0 R = 4 4
16 0
Ans : (76)10 = (4C)16
Ex 2. (50)10 = (?)16

Hexadecimal base Number Process Remainder

16 50 50/16 Q = 3 R = 2 2

16 3 50/16 Q = 0 R = 2 3
16 0

Ans : (50)10 = (32)16


Fractional Value Conversion
To convert the fractional part, multiply it with 16. Keep aside the integer generated
(digit value between 0 to 7), and the next fractional part is multiplied by 16. The process
stops when the fractional part’s result is 0 or the value becomes recurring.
Ex 3. (100.25)10 = (?)16
The integer part—[Same as shown before, (100)10 = (64)16]
The fractional part—

Hexadecimal base Number Process Integer


.25 * 16 = 4.00
16 0.25 4
I = 4 F = 0
16 0.0
So, (.25)10 = (.4)16
Final Ans : (100.25)10 = (64.4)16

21
ISC COMPUTER SCIENCE – XI

Ex 4. (175.125)10 = (?)16
The integer part — (175)10 = (AF)16

Hexadecimal base Number Process Remainder


175/16
16 175 F
Q = 10 R = 15 (F)
10/16
16 10 A
Q = 0 R = 10 (A)
16 0
The fractional part—
Hexadecimal base Number Process Integer
.125 * 16 = 2.000
16 0.125 2
I=2F=0
16 0.0

So, (.125)10 = (2)16


Final Ans : (175.125)10 = (AF.2)16
IV. CONVERSION FROM BINARY TO DECIMAL :
Integer Value Conversion
To convert an integer binary number to decimal, multiply the digits of the binary
number by 2n, where n begins with 0 for the digit in unit’s place and increase by 1 each
time for the next digit with higher place value. Finally, add all these products.
The following diagram shows the order in which the power of base 2 is raised.

1 0 1 1 0 0 1
26 25 24 23 22 21 20
The following examples show the method:
Ex 1. (1011001)2 = (?)10
(1 0 1 1 0 0 1)2 → 1 × 20 + 0 × 21 + 0 × 22 + 1 × 23 + 1 × 24 + 0 × 25 + 1 × 26
→ 1 × 1 + 0 × 2 + 0 × 4 + 1 × 8 + 1 × 16 + 0 × 32 + 1 × 64
→ 1 + 0 + 0 + 8 + 16 + 0 + 64
→ (89)10
Ans : (89)10
Ex 2. (111010)2 = (?)10
The following diagram shows the order in which the power of base 2 is raised.
1 1 1 0 1 0
25 24 23 22 21 20
(1 1 1 0 1 0)2 → 1 × 20 + 1 × 21 + 0 × 22 + 1 × 23 + 1 × 24 + 1 × 25

22
NUMBERS

→ 0 × 1 + 1 × 2 + 0 × 4 + 1 × 8 + 1 × 16 + 1 × 32
→ 0 + 2 + 0 + 8 + 16 + 32
→ (58)10
Ans : (58)10
Fractional Value Conversion
To convert the fractional part of a binary number to decimal, multiply the digits that
appear after the decimal point by 2p, where p begins with –1 and goes on decreasing by 1.
Note : The following diagram shows the order in which the power of base 2 is raised :
1 1 0 . 1 1
2 1 0 -1
2 2 2 2 2-2
Ex 3. (110.11)2 = (?)10
( 1 1 0 . 1 1 )2 → ( 0 × 20 + 1 × 21 + 1 × 22 ) + (1 × 2-1 + 1 × 2-2)
→ ( 0 × 1 + 1 × 2 + 1 × 4 ) + ( 1 × 0.5 + 1 × 0.25)
→ (0 + 2 + 4) + (0.5 + 0.25)
→ (6.75)10
Ans : (6.75)10
Ex 4. (10110.01)2 = (?)10
(1 0 1 1 0 0 1)2 → (0 × 20 + 1 × 21 + 1 × 22 + 0 × 23 + 1 × 24) + (0 × 2–1 + 1 × 2–2)
→ (0 × 1 + 1 × 2 + 1 × 4 + 0 × 8 + 1 × 16) + (0 × 0.5 + 1 × 0.25)
→ (0 + 2 + 4 + 0 + 16) + (0 + 0.25)
→ (22.25)10
Note : The following diagram shows the order in which the power of base 2 is raised.
1 0 1 1 0 · 0 1
24 23 22 21 20 2–1 2–2
Ans : (22.25)10
V. CONVERSION FROM OCTAL TO DECIMAL :
Integer Value Conversion
To convert an integer octal number to decimal, multiply the digits of the octal
number by 8n, where n begins with 0 for the digit in unit’s place and increases by 1 each
time for the next digit with higher place value. Finally, add all the products.
The following diagram shows the order in which the power of base 8 is raised :
2 4 5
82 81 80
The following examples show the method :
Ex 1. (245)8 = (?)10
(245)2 → 5 × 80 + 4 × 81 + 2 × 82
→ 5 × 1 + 4 × 8 + 2 × 64
→ 5 + 32 + 128

23
ISC COMPUTER SCIENCE – XI

→ (165)10
Ans : (165)10
Ex 2. (426)8 = (?)10
The following diagram shows the order in which the power of base 8 is raised :
4 2 6
2 1
8 8 80
(426)8 → 6 × 80 + 2 × 81 + 4 × 82
→ 6 × 1 + 2 × 8 + 4 × 64
→ 6 + 16 + 256
→ (278)10
Ans : (278)10
Fractional Value Conversion
The process of converting the fractional part of an octal number to decimal is by
multiplying the digits that appear after the decimal point by 8p, where p begins with -1
and goes on decreasing by 1.
The following diagram shows the order in which the power of base 8 is raised :
4 0 . 4 2
1 0 -1
8 8 8 8-2
Ex 3. (40.42)8 = (?)10
(40.42)8 → (0 × 80 + 4 × 81) + (4 × 8–1 + 2 × 8-2)
→ (0 × 1 + 4 × 8) + (4 × 0.125 + 2 × 0.015625)

→ (0 + 32) + (0.5 + 0.03125)

→ (32.53125)10

Ans : (32.53125)10
Ex 4. (77.64)8 = (?)10
The following diagram shows the order in which the power of base 8 is raised :
7 7 · 6 4
1 0 –1
8 8 8 8–2
(77.64)8 → (7 × 80 + 7 × 81) + (6 × 8–1 + 4 × 8–2)
→ (7 × 1 + 7 × 8) + (6/8 + 4/64)

→ (7 + 56) + (0.75 + 0.0625)

→ (63.8125)10
Ans : (63.8125)10
VI. CONVERSION FROM HEXADECIMAL TO DECIMAL :
Integer Value Conversion
To convert an integer hexadecimal number to decimal, multiply the digits of the
hexadecimal number by 16n, where n begins with 0 for the digit in unit’s place and
increases by 1 each time for the next digit with higher place value. Finally, add all these

24
NUMBERS

products.
The following diagram shows the order in which the power of base 16 is raised :
8 C
1
16 160
The following examples show the method :
Ex 1. (8C)16 = (?)10
(8 C)16 → C × 160 + 8 × 161
→ 12 × 1 + 8 × 16
→ 12 + 128
→ (140)10
Ans. : (140)10
Ex 2. (CAFE)16 = (?)10
(CAFE)16 → E × 160 + F × 161 + A × 162 + C × 163
→ 14 × 160 + 15 × 161 + 10 × 162 + 12 × 163
[hexadecimal digits are converted for calculation]
→ 14 × 1 + 15 × 16 + 10 × 256 + 12 × 4096
→ 14 + 240 + 2560 + 49152
→ (51966)10
Ans : (51966)10
Fractional Value Conversion
The process of converting the fractional part of a hexadecimal number to decimal is
by multiplying the digits that appear after the decimal point by 6p, where p begins with
-1 and goes on decreasing by 1.
Ex 3. (100.4)16 = (?)10
Note : The following diagram shows the order in which the power of base 16 is
raised :
1 0 0 . 4
2 1 0
16 16 16 16–1
(100.4)16 → (0 × 160 + 0 × 161 + 1 × 162) + (4 × 16–1)
→ (0 × 1 + 0 × 16 + 1 × 256) + (4 × 0.0625)
→ (0 + 0 + 256) + (0.25)
→ (256.25)10
Ans. (256.25)10
Ex 4. (100D.C)16 = (?)10
Note : The following diagram shows the order in which the power of base 16 is
raised :
1 0 0 D · C
3 2 1 0
16 16 16 16 16–1
(100D.C)16 → (D × 160 + 0 × 161 + 0 × 162 + 1 × 163) + (C × 16–1)

25
ISC COMPUTER SCIENCE – XI

→ (D × 1 + 0 × 16 + 0 × 256 + 1 × 163) + (12/16)


→ (13 + 0 + 0 + 4096) + (0.75)
→ (4109.75)10
Ans : (4109.75)10
VII. CONVERSION FROM BINARY TO OCTAL :
Number systems, octal (8 = 23) and binary (2 = 21) are related in such a way that
each octal digit can be replaced by corresponding 3 binary digits. The following table is
given for reference.
Octal Binary Octal Binary
0 000 4 100
1 001 5 101
2 010 6 110
3 011 7 111
Integer Value Conversion
To convert a binary number to octal, three digits of the binary number have to be
grouped and replaced by one octal digit. The digit grouping takes place from the right
side. Leading 0s can be pinned if required.
Ex 1. (110101)2 = (?)8
(110101)2 → 110 101
→ (65)8
Ans : (110101)2 = (65)8
Ex 2. (11101010)2 = (?)8
(11101010)2 → 011 101 010
→ (3 5 2)8
Ans : (11101010)2 = (352)8
Fractional Value Conversion
To convert the fractional part, three digits of the binary number have to be grouped
and replaced by one octal digit, where grouping starts from the point’s position. Following
0s can be pinned if required.
Ex 3. (1101.0111)2 = (?)8
(1101.0111)2 → 0 0 1 1 0 1 . 0 1 1 1 0 0
→ (15.34)8
Ans : (1101.0111)2 = (15.34)8
Ex 4. (11010111.01011)2 = (?)8
(11010111.01011)2 → 0 1 1 0 1 0 1 1 1 . 0 1 0 1 1 0
→ (327.26)8
Ans : (11010111.01011)2 = (327.24)8

26
NUMBERS

VIII. CONVERSION FROM BINARY TO HEXADECIMAL :


Number systems, hexadecimal (16 = 24) and binary (2 = 21) are related in such a
way that each hexadecimal digit can be replaced by corresponding 4 binary digits. The
following table is given for reference :
Hexadecimal Binary Hexadecimal Binary
0 0000 8 1000
1 0001 9 1001
2 0010 A 1010
3 0011 B 1011
4 0100 C 1100
5 0101 D 1101
6 0110 E 1110
7 0111 F 1111
Integer Value Conversion
To convert a binary number to hexadecimal, four digits of the binary number have
to be grouped and replaced by one hexadecimal digit. The digit grouping takes place
from the right side. Leading 0s can be put if required.
Ex 1. (110101)2 = (?)16
(1110101)2 → 0 1 1 1 0 1 0 1
→ (75)16

Ans : (110101)2 = (75)16
Ex 2. (111101010)2 = (?)8
(111101010)2 → 0 0 0 1 1 1 1 0 1 0 1 0
→ (1EA)16

Ans : (111101010)2 = (1EA)16
Fractional Value Conversion
To convert the fractional part, four digits of the binary number have to be grouped
and replaced by one hexadecimal digit, where grouping starts from the point’s position.
Subsequent 0s can be put if required.
Ex 3. (11101.00101)2 = (?)16
(11101.00101)2 → 0 0 0 1 1 1 0 1 . 0 0 1 0 1 0 0 0
→ (1D.28)16

Ans : (11101.00101)2 = (1D.28)16
Ex 4. (1100100111.110101)2 = (?)16
(1100100111.110101)2 → 0 0 1 1 0 0 1 0 0 1 1 1 . 1 1 0 1 0 1 0 0
→ (327.D4)16

Ans : 1100100111.110101)2 = (327.D4)16

27
ISC COMPUTER SCIENCE – XI

IX. CONVERSION FROM OCTAL TO BINARY :


As discussed in article VII (Conversion from Binary to Octal), one octal digit can
replace corresponding three binary digits using the number chart. An Octal number can
be converted to Binary by replacing each digit by the corresponding three digit binary
number.
Octal Binary Octal Binary
0 000 4 100
1 001 5 101
2 010 6 110
3 011 7 111

Ex 1. (7314)8 = (?)2
(7314)8 → 7 3 1 4
→ 111 011 001 100
→ (111011001100)2
Ans : (7314)8 = (111011001100)2
Ex 2. (263.54)8 = (?)2
(263.54)8 → 2 6 3 . 5 4
→ 010 110 011 . 101 100
→ (10110011 . 1011)2

 [Truncating leading and following 0s.]
Ans : (263.54)8 = (10110011.1011)2
Ex 3. (10436.24)8 = (?)2
(10436.24)8 → 1 0 4 3 6 . 2 4
→ 001 000 100 011 110 . 010 100
→ (1000100011110.0101)2
Ans : (10436.24)8 = (1000100011110.0101)2
Ex 4. (1011.01)8 = (?)2
(1011.01)8 → 1 0 1 1 · 0 1
→ 001 000 001 001 . 000 001
Ans : (1000001001.000001)2

X. CONVERSION FROM HEXADECIMAL TO BINARY :


As discussed in article VIII (Conversion from Binary to Hexadecimal), one
hexadecimal digit can replace corresponding four binary digits using the number chart.
A Hexadecimal number can be converted to Binary by replacing each digit by the
corresponding four digit binary number.

28
NUMBERS

Hexadecimal Binary Hexadecimal Binary


0 0000 8 1000
1 0001 9 1001
2 0010 A 1010
3 0011 B 1011
4 0100 C 1100
5 0101 D 1101
6 0110 E 1110
7 0111 F 1111

Ex 1. (9AD8)16 = (?)2
(9AD8)8 → 9 A D 8
→ 1001 1010 1101 1000

→ (1001101011011000)2

Ans : (9AD8)16 = (1001101011011000)2
Ex 2. (428.28)16 = (?)2
(428.28)16 → 4 2 8 . 2 8
→ 0100 0010 1000 . 0010 1000
→ (10000101000.00101)2 
 [Truncating leading and following 0s.]
Ans : (428.28)16 = (10000101000.00101)2
Ex 3. (FADE.CAB)16 = (?)2
(FADE.CAB)16 → F A D E . C A B
→ 1111 1010 1101 1110 . 1100 1010 1011
Ans : (1111101011011110.110010101011)2
XI. CONVERSION FROM OCTAL TO HEXADECIMAL :
Conversion from Octal to Hexadecimal can be done in two ways :
(i) Convert the Octal number to Binary then convert the Binary number to
Hexadecimal. [Both the intermediate conversion using the number chart has
been shown in previous articles].
(ii) Convert the Octal number to Decimal then convert the Decimal number to
Hexadecimal.
Ex 1. (53.5)8 = (?)16
Method I – (octal) → (binary) → (hexadecimal)
(53.5)8 = (?)2[(octal) → (binary)]
(53.5)8 → 5 3 . 5
→ 101 011 . 101
→ (101011.101)2

29
ISC COMPUTER SCIENCE – XI

(101011.101)2 = (?)16[(binary)  (hexadecimal)]


(101011.101)2 → 0 0 1 0 1 0 1 1 . 1 0 1 0
→ 2 B . A
→ (2B.A)16
Ans : (53.5)8 = (2B.A)16
Method II – (octal) → (decimal) → (hexadecimal)
(53.5)8 = (?)10 [(octal) → (decimal)]
(53.5)8 → 3 × 8 + 5 × 81 + 5 × 8-1
0

→ 3 × 1 + 5 × 8 + 5 × 0.125
→ 3 + 40 + 0.625
→ (43.625)10
(43.625)10 = (?)16[(decimal) → (hexadecimal)]
The integer part–

Hexadecimal base Number Process Remainder


16 43 43/16 Q = 2 R = 11 (B) B
16 2 2/16 Q = 0 R = 2 2
16 0
Thus, (43)10 = (2B)16
The fractional part–

Hexadecimal base Number Process Integer


.625 * 16 = 10.00
16 0.625 A
I = 10 (A) F = 0
16 0.0
Thus, (.625)10 = (0.A)16
After combining – (43.625)10 → (2B.A)16
Final Ans : (53.5)8 = (2B.A)16
XII. CONVERSION FROM HEXADECIMAL TO OCTAL
Conversion from Hexadecimal to Octal can be done in two ways (similar to the
previous conversion) :
(i) Convert the Hexadecimal number to Decimal then convert the Decimal number
to Octal.
(ii) Convert the Hexadecimal number to Binary then convert the Binary number
to Octal. [Both the intermediate conversion using the number chart has been
shown in previous articles].
Ex 1. (2C.8)16 = (?)8
Method I – (hexadecimal) → (decimal) → (octal)
(2C.8)16 = (?)10[(hexadecimal) → (decimal)]
(2C.8)16 → C × 160 + 2 × 161 + 8 × 16–1
30
NUMBERS

→ 12 × 1 + 2 × 16 + 8 × 0.0625

→ 12 + 32 + 0.5
→ (44.5)10
(44.5)10 = (?)8[(decimal) → (octal)]
The integer part —

Octal base Number Process Remainder


8 44 44/8 ; Q=5 R=4 4
8 2 5/8 ; Q=0 R=5 5
8 0
Thus, (44)10 = (54)8
The fractional part —

Octal base Number Process Integer


8 0.5 .5 * 8 = 4.0 ; I = 4 F = 0 4
8 0.0

Thus, (.5)10 = (0.4)8 (44.5)10 → (54.4)8


Final Ans : (2C.8)16 = (54.4)8
Method II – (hexadecimal) → (binary) → (octal)
(2C.8)16 = (?)2[(hexadecimal) → (binary)]
(2C.8)16 → 2 C . 8
→ 0010 1100 . 1000
→ (101100.1)2
(101100.1)2 = (?)8 [ (binary) → (octal) ]
(101100.1)2 → 1 0 1 1 0 0 . 1 0 0
→ 5 4 . 4
→ (54.4)8
Finall Ans : (2C.8)16 = (54.4)8
RECAP
1. Number System and number of digits in that Number System :
(i) Binary 2 0 1
(ii) Octal 8 0 1 2 3 4 5 6 7
(iii) Decimal 10 0 1 2 3 4 5 6 7 8 9
(iv) Hexadecimal 16 0 1 2 3 4 5 6 7 8 9 A B C D E F

31
ISC COMPUTER SCIENCE – XI

2. Conversion Clues :

Base From (F) Base To (T) Clue (not details)


I Binary Continuous division by
base-to T for integer part.
II Decimal Octal
Multiply the fraction part
III Hexadecimal with T.
IV Binary Multiplication of digits
with base-from F raised to
V Octal Decimal
power 0 onwards (right to
VI Hexadecimal left).

VII Octal
Binary Digit replacement.
VIII Hexadecimal
3 binary digits = 1 octal
IX Octal digit.
Binary
X Hexadecimal
4 binary digits = 1
XI Octal Hexadecimal hexadecimal digit.
XII Hexadecimal Octal

EXERCISE

1. Perform the following conversions :


(a) (100.1)2 = ( ? )10 from binary to decimal
(b) (100.01)2 = ( ? )8 from binary to octal
(c) (1101.101)2 = ( ? )16 from binary to hexadecimal
(d) (55.3)8 = ( ? )10 from octal to decimal
(e) (74.62)8 = ( ? )2 from octal to binary
(f) (55.5)8 = ( ? )16 from octal to hexadecimal
(g) (246.2)10 = ( ? )8 from decimal to octal
(h) (48.5)10 = ( ? )2 from decimal to binary
(i) (864.22)10 = ( ? )16 from decimal to hexadecimal
(j) (1A.C)16 = ( ? )8 from hexadecimal to octal
(k) (CF.8)16 = ( ? )10 from hexadecimal to decimal

32
NUMBERS

(l) (FEDA.3B)16 = ( ? )2 from hexadecimal to binary


(m) (1024.75)10 = ( ? )16 from decimal to hexadecimal
(n) (400.C)16 = ( ? )8 from hexadecimal to octal
(o) (2000.6)8 = ( ? )10 from octal to decimal
2. Arrange the following as instructed :
(a) (12)8 ; (100)8 ; (11)8 ; (77)8 in ascending order
(b) (AA)16 ; (FF)16 ; (99)16 ; (100)16 in descending order
(c) (B)16 ; (1001)2 ; (10)8 ; (16)10 in ascending order
(d) (100)8 ; (100)2 ; (100)16 ; (100)10 in descending order
(e) (14)8 ; (1001)2 ; (7)16 ; (10)10 in ascending order
qq

33
ARITHMETIC
1B OPERATIONS

l Addition and Subtraction of Numbers of various Bases


 Binary Arithmetic
@ Binary Addition
@ Binary Multiplication
@ Binary Subtraction 
@ Borrow
@ Sign bit representation of a binary number
@ 1’s Complement Subtraction
@ 2’s Complement Subtraction
 Division
 Octal Arithmetic – Addition and Subtraction
 Hexadecimal Arithmetic – Addition and Subtraction
 Complement of a number (any Base)
 Subtraction using Complement Method (any Base)

ADDITION AND SUBTRACTION OF


NUMBERS OF VARIOUS BASES

I. BINARY ARITHMETIC
Binary Addition
In any number system, the concept of addition states that “adding unit value (1) to
any number returns the next number in the number line”. Refer to the Number Chart.
In binary number system :
0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 10
10 + 1 = 11 11 + 1 = 100 1 + 1 + 1 = 11
Two large numbers can also be added by adding the corresponding digits. An
addition of two numbers may generate a carry [concept of carry is explained below].
Carry’s position is on the left of the largest number of digits, among the numbers to be
ARITHMETIC OPERATIONS

added. For example, let the numbers to be added are 11 and 1. Largest number of digits
is 2. The carry’s position will be 3rd from right.
Ex 1. 100011 + 1100
Ans.
1 0 0 0 1 1
+ 1 1 0 0
1 0 1 1 1 1

Note :
l In the answer, the 7th digit (on extreme left) is called the carry. The above addition
generates no carry.

Ex 2. 110110 + 1100
Ans.
1 1 1

1 1 0 1 1 0
+ 1 1 0 0
1 0 0 0 0 1 0

Note :
l This addition generates a carry.

Addition of Fractions
(i) Make both the numbers have equal number of digits by putting leading and
following 0s.
(ii) Start addition from the fractional part, without disturbing the position of the
point.
Ex 3. 10110111.11001 + 10100.101
Ans.
1 1 1 1 1 1
1 0 1 1 0 1 1 1 . 1 1 0 0 1
+ 0 0 0 1 0 1 0 0 . 1 0 1 0 0
1 1 0 0 1 1 0 0 . 0 1 1 0 1

Note :
l In this addition, fractional part generates a carry. The integer part does not generate
any carry.

35
ISC COMPUTER SCIENCE – XI

Ex 4. 1110111.101 + 1100110.111001
Ans :
1 1 1 1 1 1 1
1 1 1 0 1 1 1 . 1 0 1 0 0 0
+ 1 1 0 0 1 1 0 . 1 1 1 0 0 1
1 1 0 1 1 1 1 0 . 1 0 0 0 0 1

Note :
l In this addition, fractional part generates a carry and the integer part also generates
a carry.

BINARY MULTIPLICATION
Multiplication is a repetitive addition. Binary Multiplication is similar to that in
decimal system. In binary number system,
0*0=0 0 * 1 = 0 1 * 0 = 0 1*1=1
Ex 1. 1110111 * 110
Ans :

1 1 1 0 1 1 1
× 1 1 0
1 1 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 0 1 1 1 x
1 1 1 0 1 1 1 x x
1 0 1 1 0 0 1 0 1 0

Ex 2. 101011 * 1010
Ans :
1 0 1 0 1 1
× 1 0 1 0
1 1
0 0 0 0 0 0
1 0 1 0 1 1 x
0 0 0 0 0 0 x x
1 0 1 0 1 1 x x x
1 1 0 1 0 1 0 1 0

36
ARITHMETIC OPERATIONS

BINARY SUBTRACTION
There are three methods of performing Binary Subtraction :
(i) Method of Borrow.
(ii) One’s Complement Method.
(iii) Two’s Complement Method.
(i) Method of Borrow
In any number system, the concept of subtraction states that “subtracting unit value (1)
from any number returns the previous number in the number line”. In binary number system,
0–0=0 1 – 0 = 1 1–1=0 10 – 1 = 1 11 – 1 = 10
In subtraction of large numbers, digits of the second numbers can be subtracted from
the corresponding digits of the first number. Subtraction of two numbers may require a
borrow [concept of borrow is explained below].
Concept of Borrow :
(i) Each value in 10’s place is equal to 10 values in 1’s place.
(ii) Each value in 100’s place is equal to 10 values in 10’s place, and so on.
(iii) If 1 is borrowed from 10’s place then 10 is added to 1’s place.
(iv) If 1 is borrowed from 100’s place then 10 is added to 10’s place and so on.
Example of decimal subtraction using the method of borrow :
Ex 1. (243)10 – (87)10 = (176)10
(i)
2 6 3 – Num1
– 8 7 – Num2
(ii)
–1 +10
2 6 3 – Num1
– 8 7 – Num2

(iii)
2 5 13 – Num1
– 8 7 – Num2
6
(iv)
–1 +10
2 5 13 – Num1
– 8 7 – Num2
6

37
ISC COMPUTER SCIENCE – XI

(v)
1 15 13 – Num1
– 8 7 – Num2
1 7 6
Ans : (176)10
Ex 2. (100)2 – (1)2
Ans. The binary subtraction steps using method of borrow are shown below :
(i)
1 0 0 – Num1
– 1 – Num2

(ii)

10–1 +10
0 0 0 – Num1

– 1  – Num2

(iii)

+1
0 0 10  – Num1
– 1  – Num2

(iv)

0 1 10 – Num1
– 1 –  Num2
1 1 Result

Verification : In every subtraction, (Result + Num2) should be equal to Num1.

(v) Verification

1 1

1 1 – Result
+ 1 – Num2
1 0 0 – Num1

Ans : (11)2

38
ARITHMETIC OPERATIONS

Ex. 3. (1100101 – 11110)2 


(i)
1 1 0 0 1 0 1 – Num1
– 1 1 1 1 0 – Num2
(ii)
–1 +10
1 1 0 0 1 0 1  – Num1
– 1 1 1 1 0  – Num2
1 1
(iii)
–1 +10
–1
1 1 0 0 1 10 1  – Num1
– 1 1 1 1 0  – Num2
1 1 1
(iv)
–1 +10
–1 +10
1 1 0 0 0 0 1  – Num1
– 1 1 1 1 0  – Num2
1 1 1
(v)
–1 +10
–1
1 1 0 1 10 0 1  – Num1
– 1 1 1 1 0  – Num2
0 1 1 1
(vi)

1 0 1 1 10 0 1  – Num1
– 1 1 1 1 0  – Num2
1 0 0 0 1 1 1

39
ISC COMPUTER SCIENCE – XI

(vii) Verification
1 1 1 1
1 1 1 1 0 – Num2
– 1 0 0 0 1 1 1 – Result
1 1 0 0 1 0 1

Ans : (1000111)2

Subtraction of Fractions
Similar to addition, put leading and following 0s and make both numbers have
equal number of digits.
Ex. 4. (100.001 – 10.01)2
Ans. The subtraction steps :
(i)
1 0 0 . 0 0 1 – Num1
– 0 1 0 . 0 1 0 – Num2
.

(ii)

–1 +10

1 0 0 . 0 0 1 – Num1
– 0 1 0 . 0 1 0 – Num2
. 1

(iii)

–1 +10
–1
1 0 0 . 0 10 1 – Num1
– 0 1 0 . 0 1 0 – Num2
. 1 1

(iv)

–1 +10
–1
1 0 0 . 1 10 1 – Num1
– 1 0 . 0 1 – Num2
. 1 1 1

40
ARITHMETIC OPERATIONS

(v)
–1 +10
–1
1 0 1 . 1 10 1 – Num1
– 1 0 . 0 1 – Num2
1 . 1 1 1
(vi)

0 1 1 . 1 10 1 – Num1
– 1 0 . 0 1 – Num2
0 0 1 . 1 1 1 Result
Ans : (1.111)2
Result Verification – In every subtraction, (Result + Num2) should be equal to Num1.
(vi) Verification
1 1 1 1
1 . 1 1 1  – Result
+ 1 0 . 0 1  – Num 2
1 0 0 . 0 0 1 – Num 1
Ans : (1.111)2
Ex. 5. (1001.101 – 10101.01)2
Ans. (Num1<Num2), so the result is negative. Calculate (big – small).
(i)
1 0 1 0 1 . 0 1 0  – Num1
– 1 0 0 1 . 1 0 1  – Num2
.

–1 +10
1 0 1 0 1 . 0 1 0 – Num1
– 1 0 0 1 . 1 0 1 – Num2
. 1
(ii)
–1 +10
1 0 1 0 1 . 0 0 10 – Num1
– 1 0 0 1 . 1 0 1  – Num2
. 0 1

41
ISC COMPUTER SCIENCE – XI

(iii)
–1 +10
1 0 1 0 0 . 10 0 10 – Num1
– 1 0 0 1 . 1 0 1 – Num2
. 1 0 1
(iv)
–1
1 0 1 0 10 10 0 10 – Num1
– 1 0 0 1 . 1 0 1 – Num2
1 . 1 0 1
(v)
–1 +10
–1
1 0 1 0 10 . 10 0 10 – Num1
– 1 0 0 1 . 1 0 1 – Num2
1 1 . 1 0 1
(vi)

–1 +10
1 0 0 1 10 . 10 0 10 – Num1
– 1 0 0 1 . 1 0 1 – Num2
0 1 1 . 1 0 1
(vii)
0 10 0 1 10 . 10 0 10 – Num1
– 1 0 0 1 . 1 0 1 – Num2
1 0 1 1 . 1 0 1

Final answer is negative i.e., – 1011.101


Signed Bit Representation of a Binary Number
In this type of representation, for a n-bit Binary number, the leftmost bit is reserved
for its sign, where 0 indicates positive and 1 indicates negative.
For example :
(a) 0110 is a 4-bit positive number.
(b) 1010 is a 4-bit negative number.
(c) 10001101 is a 8-bit negative number.
(d) 00001000 is a 8-bit positive number.

42
ARITHMETIC OPERATIONS
(ii) Subtraction Using Method of One’s Complement
One’s Complement of a binary number is found by inverting the 0s and 1s, without
changing the number of digits.
For example :

S.No. Given Number One’s Complement


(i) 0110 1001
(ii) 1010 0101
(iii) 10001101 01110010

(iv) 00001000 11110111


(v) 111000 000111
Steps of subtracting (Num1 – Num2) using One’s Complement Method :
Step I  : Put leading 0s to make both Num1 and Num2 to have same number of
digits, say n.
Step II : Find One’s Complement of Num2 and name it CNum2.
Step III   : Add Num1 and CNum2 and store in R. Divide R into parts, sum and carry,
where sum part contains n bits from the right side and carry part is the
(n + 1)th bit from the right.
Step IV   : Observe the value of carry.
If carry is 1, then the answer is positive and equal to (sum + 1).
If carry is 0, then the answer is negative and equal to One’s complement
of the sum part.
Example 1 : 11100101 – 11011
Step I : Put leading 0s to make both Num1 and Num2 to have same number of
digits, say n.
Num1 = 11100101
Num2 = 00011011, n=8
Step II : Find One’s Complement of Num2 and name it CNum2.
Num2 = 00011011
CNum2 = 11100100
Step III : Add Num1 and CNum2 and store in R. Divide R into parts, sum and
carry, where sum part contains n(8) bits from the right side and carry part
is the (n + 1)th (9th)bit from the right.
R = Num 1 + CNum2
1 1 1 1
1 1 1 0 0 1 0 1 Num1
+ 1 1 1 0 0 1 0 0 CNum2
1 1 1 0 0 1 0 0 1 R
Carry Sum
Part

43
ISC COMPUTER SCIENCE – XI

Step IV : The carry is 1. So, the answer is positive and equal to (sum + 1).
Ans = 11001001 + 1
1
1 1 0 0 1 0 0 1 Sum
+ 1
1 1 0 0 1 0 1 0 Ans
Final Ans : (11001010)2
Verify – (Ans + Num2) should be Num1
Example 2 : 110101 – 100101 … using 1’s complement method
Step I : Minuend (Num1) and Subtrahend(Num2) both have the same number of
digits (n = 6).
Num1 = 110101
Num2 = 100101
Step II : Num2 = 100101
CNum2 = 011010 (1’s complement of 100101)
Step III : Minuend Num1 - 1 1 0 1 0 1
CNum2 - 0 1 1 0 1 0
Sum - 1 0 0 1 1 1 1
Step IV : The Carry is 1, hence the result is positive and is equal to (1 + sumpart)
0 0 1 1 1 1
+                    1
0 1 0 0 0 0
Final Ans : (10000)2
Example 3 : 101011 – 111001
Step I : Minuend (Num1) and Subtrahend (Num2) both have the same number of
digits (n = 6).
Num1 = 101011
Num2 = 111001
Step II : Num2 = 111001
CNum2 = 000110 (1’s complement of 111001)
Step III : Minuend Num1 -  1 0 1 0 1 1
CNum2 - 0 0 0 1 1 0
Sum - 0 1 1 0 0 0 1
Step IV : The Carry is 0, hence the result is negative and is equal to the one’s
complement of the sum part.

44
ARITHMETIC OPERATIONS

Sum part = 110001


One’s comp = 001110
Final Ans : (–1110)2
Example 4 : 1011.001 – 110.10
Step I : Minuend (Num1) and Subtrahend (Num2) both do not have the same
number of digits.
Putting leading and following 0s to make the number of digits same.
Num1 = 1011.001
Num2 = 0110.100
Step II : Num2 = 0110.100
CNum2 = 1001.011 (1’s complement of 0110.100)
Step III : Minued 1 0 1 1 . 0 0 1
CNum2   1 0 0 1 . 0 1 1
Sum 1 0 1 0 0 . 1 0 0
Step IV : The Carry is 1, so the result is positive and is equal to (1 + sumpart as a
whole)
Sum part = 0100.100
+         1
0100.101
Final Ans : (100.101)2
Example 5 : 10110.01 – 11010.1
Step I : Minuend (Num1) and Subtrahend(Num2) both do not have the same
number of digits.
Putting following 0s to make the number of digits same.
Num1 = 10110.01
Num2 = 11010.10
Step II : Num2 = 11010.10
CNum2 = 00101.01 (1’s complement of 11010.10)
Step III : Num1(Minued) 1 0 1 1 0 . 0 1
CNum2               0 0 1 0 1 . 0 1
Sum           0 1 1 0 1 1 . 1 0
Step IV : The Carry is 0, hence the result is negative and is equal to 1’s comp of the
sumpart as a whole Sum part = 11011.10
1’s complement = 00100.01
Final Ans : (–00100.01)2 or (–100.01)2
(iii) Subtraction Using Method of Two’s Complement
Two’s Complement of a binary number is found by adding 1 to its one’s complement.

45
ISC COMPUTER SCIENCE – XI

For example :
S. No. Given Number One’s Complement Two’s Complement
(i) 0110 1001 1001 + 1 = 1010
(ii) 1010 0101 0101 + 1 = 0110
(iii) 10001101 01110010 01110010 + 1 = 01110011
(iv) 00001000 11110111 11110111 + 1 = 11111000
Steps of subtracting (Num1 – Num2) using Two’s Complement Method :
Step I : Put leading 0s to make both Num1 and Num2 to have the same number
of digits, say n.
Step II : Find Two’s Complement of Num2 and name it TNum2.
Step III : Add Num1 and TNum2 and store in P. Divide P into parts, sum and
carry, where sum part contains n bits from the right side and carry part
is the (n+1)th bit from the right.
Step IV : Observe the value of carry.
If carry is 1, then the answer is positive and equal to the sum part itself.
If carry is 0, then the answer is negative and equal to Two’s complement
of the sum part.
Example 1 : 11100101 – 11011
Step I : Put leading 0s to make both Num1 and Num2 to have same number of
digits, say n.
Num1 = 11100101
Num2 = 00011011 n=8
Step II : Find Two’s Complement of Num2 and name it TNum2.
Num2 = 00011011
CNum2 = 11100100
TNum2 = CNum2 + 1
= 11100100 + 1
= 11100101
Step III : Add Num1 and TNum2 and store in P. Divide P into parts, sum and
carry, where sum part contains n bits from the right side and carry part
is the (n + 1)th bit from the right.
R = Num 1 + TNum2
1 1 1 1 1 carry
1 1 1 0 0 1 0 1 Num1
+ 1 1 1 0 0 1 0 1 TNum2
1 1 1 0 0 1 0 1 0 Result P
Carry Sum Part

46
ARITHMETIC OPERATIONS

Step IV : The carry is 1. So the answer is positive and equal to the sum part itself.
Final Ans : (11001010)2
Verify : (Ans + Num2) should be equal to Num1
Example 2 : 110110 – 10110
Step I : Put leading 0s to make both Num1 and Num2 to have the same number
of digits, say n.
Num1 = 1 1 0 1 1 0
Num2 = 0 1 0 1 1 0 n=6
Step II : Two’s Complement of Num2 as TNum2 (1’s comp + 1)
Num2 = 0 1 0 1 1 0
CNum2 = 101001
+ 1
TNum2 = 1 0 1 0 1 0
Step III : Num1 = 110110
TNum2 = 1 0 1 0 1 0
Sum = 1 1 0 0 0 0 0
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part
itself.
Final Ans : (100000)2
Example 3. 10110 – 11010
Step I : Both Num1 and Num2 have the same number of digits, say n.
Num1 = 1 0 1 1 0
Num2 = 1 1 0 1 0 n=5
Step II : Two’s Complement of Num2 as TNum2 (1’s comp + 1)
Num2 = 11010
CNum2 = 00101
+ 1
TNum2 = 00110
Step III : Num1 = 10110
TNum2 = 0 0 1 1 0 
Sum 0 1 1 1 0 0
Step IV : T
he Carry is 0, hence the result is negative and is equal to the 2’s
Complement of the sum part.
Sum part = 11100
1’s comp = 00011
+ 1
00100
Final Ans : (–100)2

47
ISC COMPUTER SCIENCE – XI

Example 4 : 1010.11 – 1001.01


Step I : Both Num1 and Num2 have the same number of digits, say n.
Num1 = 1 0 1 0 . 1 1
Num2 = 1 0 0 1 . 0 1 n=6
Step II : Two’s Complement of Num2 as TNum2 (1’s comp + 1)

Num2 = 1 0 0 1 . 0 1
CNum2 = 0 1 1 0 . 1 0
+ 1
TNum2 = 0 1 1 0 . 1 1
Step III : Num1 1 0 1 0 . 1 1
TNum2 0 1 1 0 . 1 1
Sum
  10001.10
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part
itself.
Final Ans : (1.10)2
Example 5 : 10100.01 – 11011.1
Step I : Adding a 0 behind Num2 so that both Num1 and Num2 get the same
number of digits, say n. Num1 = 1 0 1 0 0 . 0 1
Num2 = 1 1 0 1 1 . 1 0 n=7
Step II : Num2 = 1 1 0 1 1 . 1 0
CNum2 0 0 1 0 0 . 0 1
+ 1
TNum2 0 0 1 0 0 . 1 0
Step III : Num1 1 0 1 0 0 . 0 1
TNum2 0 0 1 0 0 . 1 0
Sum0 1 1 0 0 0 . 1 1
Step IV : The Carry is 0, hence the result is negative and is equal to the 2’s
Complement of the sum part. Sum part — 11000.11
1’s comp 00111.00
+ 1
00111.01
Final Ans : (00111.01)2

BINARY DIVISION
Binary division is similar to decimal division.

48
ARITHMETIC OPERATIONS

Ex. 1. 11011 / 11
Ans :
11 11011 1001
11
00
00
01
00
11
00
0
Quotient → 1001 Remainder → 0
Verify : 1001 × 11 + 0 = 11011
Ex. 2. 1011101 / 101
Ans :

101 1011101 10010


101
01
00
11
00
110
101
11
00
11

Verify : 1 0010 × 101 + 11 = 1011101

II. OCTAL ARITHMETIC


Octal Addition
Octal digits range from 0 to 7. Number after 7 is 10.
So, in octal number system—
7 + 1 = 10, 17 + 1 = 20, 77 + 1 = 100 and so on.
Refer to the Number Chart.
Ex 1. (6 + 2)8
Ans. Elementary one digit number addition can be done from the number line.
(6 + 2) means to move 2 places ahead from 6. From number line we get 10 as the result.

49
ISC COMPUTER SCIENCE – XI

Ex. 2. 25 + 4
Ans.
1
2 5
+ 4
3 1
Ans : (31)8
Note : The above sum generates no carry.
Ex. 3. 26477 + 60325
Ans.
1 1 1
2 6 4 7 7
+ 6 0 3 2 5
1 0 7 0 2 4
Ans : (107024)8
Note : The above sum generates a carry.
Octal Subtraction
We refer to the octal number line for reference.
Ex.1. (10 – 2)8 = (6)8 [In the Octal Number Line, 2 places before 10 is 6]
Ex.2. (11 – 4)8 = (5)8 [In the Octal Number Line, 4 places before 11 is 5]
Method of Borrow
As in case of Binary, in Octal system also,
(i) Each value in 10’s place is equal to 10 values in 1’s place.
(ii)       Each value in 100’s place is equal to 10 values in 10’s place.
(iii)  1 borrowed from the 10’s place increases 10 in the unit’s place. And so on.
Ex.3. 712 – 54
Ans. The subtraction process is explained in detail below :
(i)
7 1 2 Num1
– 0 5 4 Num2
(ii)
–1 +10

7 1 2 Num1
– 0 5 4 Num2

50
ARITHMETIC OPERATIONS

(iii)
–1 +10

7 0 12 Num1
– 5 4 Num2
6
(iv)
6 10 12 Num1
– 5 4 Num2
6 3 6 Result
Ans : (636)8
Verify – (Result + Num2) should be equal to Num1.
Verify : 636 + 54 = 712
III. HEXADECIMAL ARITHMETIC
Hexadecimal Addition
Hexadecimal digits range from 0 to F. Number after 9 is A and number after F is
10. So, in hexadecimal number system F + 1 = 10, 1F + 1 = 20, 29 + 1 = 2A and so on. We
look at the hexadecimal number line for reference to addition :
0 1 2 3 4 5 6 7 8 9 A B C D E F
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F …
Ex. 1. (6 + 4)16 = (A)16 Ex. 2. (9 + 9)16 = (12)16
Ex. 3. 984 + 27
Ans.
9 8 4
+ 2 7
9 A B
Final Ans : (9AB)16

Note :
l The above sum generates no carry.
Ex. 4. FADE + CAFE
Ans.
1 1 1 1
F A D E
+ C A F E
1 C 5 D C
Final Ans : (IC5DC)16

51
ISC COMPUTER SCIENCE – XI

Note :
l The above sum generates a carry.

Hexadecimal Subtraction
We refer to the hexadecimal number line for reference.
Ex. 1. (10 – 2)1 = (E)16 Ex. 2. (15 – A)16 = (B)16 Ex. 3. (20 – F)16 = (11)16
Ex. 4. (18 – D)16 = (B)16
Method of Borrow
As in the previous case, 1 borrowed from the 10’s place increases 10 in the unit’s
place.
Similarly 1 borrowed from 100’s place increases 10 in the 10’s place and so on.
Ex. 5. (78F – D9)16
Ans. The subtraction steps :
(i)
7 8 F – Num1
– D 9 –Num2
(ii)

–1 +10

7 8 F –Num1
– D 9 –Num2
6
(iii)
6 18 F – Num1
– D 9 – Num2
6 B 6 Result
Final Ans : (6B6)16
Verify : (Result + Num2) should be equal to Num1.
Verify : 6B6 + D9 = 78F

Note :
l (B + D) can be done in two ways :
(i) By counting hexadecimal digits.
(ii) By converting B and D to decimal, add them and then convert the result back to
hexadecimal.

52
ARITHMETIC OPERATIONS

(i) By counting hexadecimal digits - (B + D) is D places from B = 18.


….. B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B…..
+ 1 2 3 4 5 6 7 8 9 A B C D …
= (B + D)16 = (18)16
(ii) By converting B and D to decimal, add them and then convert the result back to
hexadecimal.
For Example :
(B)16 = (11)10 (D)16 = (13)10
(B + D)16 = (11 + 13)10 = (24)10
(24)10 = (18)16
Ex.5. (1000 – ACE)16
(i)
1 0 0 0 – Num1
– A C E – Num2
(ii)
–1 +10

1 0 0 0 –Num1
– A C E –Num2
2
(iii)
–1 –1+10 +10

1 0 0 0 – Num1
– A C E – Num2
3 2
(iv)
–1 –1+10 F +10

1 0 0 0 – Num1
– A C E – Num2
0 5 3 2

Final Ans : (0532)16

Complement of A Number
The complement of a number in any base is that number which when added to it ,
gives the next nearest power of 10.

53
ISC COMPUTER SCIENCE – XI

For example, in case of decimal numbers, complement of 60 is 40, as 60 + 40 = 100


Complement of 992 is 8 as 992 + 8 = 1000 and so on. The concept is same for all bases.
Complement (CN) of a number (N) in any base (b)
It can be found by subtracting the number from the next nearest power of 10 (M). In
order to avoid subtraction of bigger digit from smaller digit, M is split into two parts H,
L where ( H + L = M ) and all digits of H is greater than all digits of N.
CN = (H – N) + L
Integer Handling
Examples : Complement of the given numbers in given bases :
(i) N = (64)10 Base = 10, Decimal (ii) N = (22)8 Base = 8, Octal
M = 100 H = 99, L = 1 M = 100 H = 77, L = 1
CN = 99 – 64 + 1 CN = 77 – 22 + 1
= 36 = 56
(iii) N = (A65)16 Base = 16, Hexadecimal (iv) N = (11010110)2 Base = 2, Binary
M = 1000 H = FFF, L = 1 M = 100000000 H = 11111111, L = 1
CN = FFF – A65 + 1 CN = 11111111 – 11010110 + 1
= 59B = 00101010
(v) N = (100)10 Base = 10 , Decimal (vi) N = (1)8 Base = 8, Octal
M = 1000 H = 999 , L = 1 M = 10 H = 7, L = 1
CN = 999 – 100 + 1 CN = 7 – 1 + 1
= 900 = 7

(vii) N = (EE)16 Base = 16, Hexadecimal (viii) N = (1001)2 Base = 2, Binary


M = 100 H = FF, L = 1 M = 10000 H = 1111, L = 1
CN = FF – EE + 1 CN = 1111 – 1001 + 1
= 12 = 0111
(ix) N = (21)4 Base = 4 , Quadral (x) N = (5241)6 Base = 6 , Hexal
M = 100 H = 33 , L = 1 M = 10000 H = 5555, L = 1
CN = 33 – 21 + 1 CN = 5555 – 5421 + 1
= 13 = 0135
Note : Note :
In Quadral system, there are 4 digits, 0, 1,
l  In
l  Hexal system, there are 6 digits, 0,
2, 3 and 3 + 1 = 10 ] 1, 2, 3, 4, 5 and 5 + 1 = 10 ]

Fraction Handling
Examples : Complement of the given numbers in given bases :

(i) N = (25.74)10 Base = 10 , Decimal (ii) N = (3.5)8 Base = 8, Octal


M = 100 H = 99.99 , L = 0.01 M = 10 H = 7.7, L = 0.1
CN = 99.99 – 25.74 + 0.01 CN = 7.7 – 3.5 + 0.1
= 74.26 = 4.3

54
ARITHMETIC OPERATIONS

(iii) N = (CE.B)16 Base = 16, Hexadecimal (iv) N = (11.011)2 Base = 2 , Binary


M = 100 H = FF.F, L = 0.1 M = 100 H = 11.111, L = 0.001
CN = FF.F – CE.B + 0.1 CN = 11.111 – 11.011 + 0.001
= 31.5 = 00.101
(v) N = (10.05)10 Base = 10 , Decimal (vi) N = (42.24)8 Base = 8 , Octal
M = 100 H = 99.99 , L = 0.01 M = 100 H = 77.77 , L = 0.01
CN = 99.99 – 10.05 + 0.01 CN = 77.77 – 42.24 + 0.01
= 89.95 = 35.54
(vii) N = (ED.1B)16 Base = 16 , Hexadecimal (viii) N = (100.01)2 Base = 2, Binary
M = 100 H = FF.FF , L = 0.01 M = 1000 H = 111.11, L = 0.01
CN = FF.FF – ED.1B + 0.01 CN = 1111 – 1001 + 0.01
= 12.E5 = 011.11
(ix) N = (3.232)4 Base = 4 , Quadral (x) N = (3412.3)6 Base = 6, Hexal
M = 10 H = 3.333, L = 0.001 M = 10000 H = 5555.5, L = 0.1
CN = 3.333 – 3.232 + 0.001 CN = 5555.5 – 3412.3 + 0.1
= 0.102 = 2143.3

Note : Note :
In Quadral system, there are 4 digits, 0, 1,
l  In
l  Hexal system, there are 6 digits,
2, 3 and 3 + 1 = 10 ] 0, 1, 2, 3, 4, 5 and 5 + 1 = 10 ]
Subtraction Using Complement of a Number
Steps of subtracting (Num1 – Num2)b using Complement Method in Base b :
Step I : Put leading 0s to make both Num1 and Num2 to have same number of
digits, say n.
Step II : Find b’s Complement of Num2 and name it bNum2.
Step III : Add Num1 and bNum2 and store in R. Divide R into parts, sum and
carry, where sum part contains n bits from the right side and carry part
is the (n + 1)th bit from the right.
Step IV : Observe the value of carry.
If carry is 1, then the answer is positive and equal to the sum part itself.
If carry is 0, then the answer is negative and equal to b’s complement of
the sum part.
Worked Examples :
Example 1 : (6052 – 584)10
Step I : Num1 = 6 0 5 2
Num2 = 0 5 8 4 n=4

55
ISC COMPUTER SCIENCE – XI

Step II : b’s Complement of Num2 as bNum2 [here b = 10]


9999
–  0 5 8 4
9 4 1 5 + 1 = 9 4 1 6
bNum2 = 9 4 1 6
Step III : Num1 = 6052
bNum2 = 9 4 1 6 
Sum 1 5 4 6 8
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 5 4 6 8
Final Ans : (6052 – 584)10 = (+5468)10
Example 2 : (249 – 7654)10
Step I : Num1 = 0 2 4 9
Num2 = 7 6 5 4 n=4
b’s Complement of Num2 as bNum2
Step II : [here b = 10]
9999
– 7654
2345+1
bNum2 = 2346
Step III : Num1 = 0249
bNum2 = 2 3 4 6
Sum 0 2 5 9 5
Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
10’s Complement of 2 5 9 5
9 9 9 9
– 2595
7404 +1=7405
Final Ans (249 – 7654 )10 = (–7405)10
Example 3 : (352.41 – 67.6)10
Step I : Num1 = 3 5 2 . 4 1
Num2 = 0 6 7 . 6 0 n=5
Step II : b’s Complement of Num2 as bNum2 [here b = 10]
999.99
– 067.60
9 3 2 . 3 9 + 0.01 = 9 3 2 . 4 0

56
ARITHMETIC OPERATIONS

bNum2 = 9 3 2 . 4 0
Step III : Num1 = 3 5 2 . 4 1
bNum2 = 9 3 2 . 4 0
Sum 1 2 8 4 .8 1
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 2 8 4 . 8 1
Final Ans : (352.41 – 67.6 )10 = + 284.81)10
Example 4 : (7.5 – 104.24)10
Step I : Num1 = 0 0 7 . 5 0
Num2 = 1 0 4 . 2 4
Step II : b’s Complement of Num2 as bNum2 [ here b = 10]
9 9 9 . 9 9
– 104.24
895.75+0.01
bNum2 = 8 9 5 . 7 6
Step III : Num1 = 007.50
bNum2 = 8 9 5 . 7 6
Sum 0 9 0 3 . 2 6
Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
10’s Complement of 9 0 3 . 2 6
999.99
– 903.26
96.73 +0.01=96.74
Final Ans : (7.5 – 104.24 )10 = (–96.74 )10
Example 5 : (73 – 57)8
Step I : Num1 = 7 3
Num2 = 5 7
Step II : b’s Complement of Num2 as bNum2 [here b = 8]
7 7
–57
20+1
bNum2 = 21
Step III : Num1 = 73
bNum2 = 2 1
Sum 114

57
ISC COMPUTER SCIENCE – XI

Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 1 4
Final Ans : (73 – 57)10 = (+14)10
Example 6 : (24 – 451)8
Step I : Num1 = 0 2 4
Num2 = 4 5 1 n=3
Step II : b’s Complement of Num2 as bNum2 [here b = 8]
7 7 7
– 4 5 1
376+1
bNum2 = 377
Step III : Num1 = 024
bNum2 = 3 7 7
Sum 0 4 2 3
Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
8’s Complement of—4 2 3
777
–423
354+1=355
Final Ans : (24 – 451)8 = (–355)8
Example 7 : (121.42 – 35.74)8
Step I : Num1 = 1 2 1 . 4 2
Num2 = 0 3 5 . 7 4
Step II : b’s Complement of Num2 as bNum2 [here b = 8]
777.77
–035.74
742.03+0.01
bNum2 = 742.04
Step III : Num1 = 121.42
bNum2 = 7 4 2 . 0 4
Sum 1 0 6 3 . 4 6
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 0 6 3 . 4 6
Final Ans : (121.42 – 35.74)8 = (+63.46)8

58
ARITHMETIC OPERATIONS

Example 8 : (502.043 – 713.4651)8


Step I : Num1 = 5 0 2 . 0 4 3 0
Num2 = 7 1 3 . 4 6 5 1 n=7
b’s Complement of Num2 as bNum2
Step II : [here b = 8]
7 7 7 . 7 7 7 7
–713.4651
0 6 4 . 3 1 2 6 + 0 . 0 0 0 1
bNum2 = 064.3127
Step III : Num1 = 502.0430
bNum2 = 0 6 4 . 3 1 2 7
Sum 0 5 6 6 . 3 5 5 7
Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
8’s Complement of 5 6 6 . 3 5 5 7
777.7777
– 5 6 6 . 3 5 5 7
211.4220+0.0001=211.4221
Final Ans : (502.043 – 713.4651)8 = (–211.4221)8
Example 9 : (20C – 9D)16
Step I : Num1 = 2 0 C
Num2 = 0 9 D
Step II : b’s Complement of Num2 as bNum2 [here b = 16]
FFF
– 0 9 D
F62 +1
bNum2 = F 6 3
Step III : Num1 = 2 0 C
bNum2 = F 6 3
Sum 1 1 6 F
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 1 6 F
Final Ans : (20C – 9D)16 = (+16F)16
Example 10 : (D – ABC)8
Step I : Num1 = 0 0 D
Num2 = AB C n=3

59
ISC COMPUTER SCIENCE – XI
Step II : b’s Complement of Num2 as bNum2 [here b = 16]
FFF
– A B C
5 4 3+1
bNum2 = 5 4 4
Step III : Num1 = 0 0 D
bNum2 = 5 4 4  
Sum 0 5 5 1
Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
16’s Complement of 5 5 1
F F F
– 5 5 1
AAE+1=AAF
Final Ans : (D – ABC)16 = (AAF)16
Example 11 : (8A9E.F1 – CAB.0E )16
Step I : Num1 = 8 A 9 E . F 1
Num2 = 0 C A B . 0 E
Step II : b’s Complement of Num2 as bNum2 [here b = 16]
F F F F . F F
– 0 CA B . 0 E
F 3 5 4 . F 1 + 0 . 0 1
bNum2 = F 3 5 4 . F 2
Step III : Num1 = 8 A 9 E . F 1
bNum2 = F 3 5 4 . F 2
Sum 1 7 D F 3 . E 3
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 7 D F 3 . E 3
Final Ans : (8A9E.F1 – CAB.0E)16 = (+7DF3.E3)16
Example 12 : (CE0.0B – DBDA.8FB )16
Step I : Num1 = 0 C E 0 . 0 B 0
Num2 = D B D A . 8 F B n=7
Step II : b’s Complement of Num2 as bNum2 [here b = 16]
F F F F . F F F
–DBDA.8FB
2 4 2 5.704+0.001

60
ARITHMETIC OPERATIONS

bNum2 = 2 4 2 5 . 7 0 5
Step III : Num1 = 0 C E 0 . 0 B 0
bNum2 = 2 4 2 5 . 7 0 5
Sum 0 3 1 0 5 . 7 B 5
Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
16’s Complement of 3 1 0 5. 7 B 5
FFFF.FFF
– 3 1 0 5 . 7 B 5
CEFA.84A+0.001=CEFA.84B
Final Ans : (CE0.0B – DBDA.8FB)16 = (–CEFA.84B)16
Example 13 : (110010 – 1101)2
Step I : Num1 = 1 1 0 0 1 0
Num2 = 0 0 1 1 0 1 n=6
Step II : b’s Complement of Num2 as bNum2 [here b = 2]
1 1 1 1 1 1
– 0 0 1 1 0 1
110010+1
bNum2 = 1 1 0 0 1 1
Step III : Num1 = 1 1 0 0 1 0
bNum2 = 1 1 0 0 1 1
Sum 1 1 0 0 1 0 1
Step IV : The Carry is 1, hence the result is positive and is equal to the sum part.
Sum part = 1 0 0 1 0 1
Final Ans : (110010 – 1101)2 = (+100101)2
Example 14 : (10.001 – 100.01)2
Step I : Num1 = 0 1 0 . 0 0 1
Num2 = 1 0 0 . 0 1 0 n=6
Step II : b’s Complement of Num2 as bNum2 [here b = 2]
111.111
–100.010
011.101+0.001
bNum2 = 0 1 1 . 1 1 0
Step III : Num1 = 010.001
bNum2 = 011.110
Sum 0 1 0 1 . 1 1 1

61
ISC COMPUTER SCIENCE – XI

Step IV : T
he Carry is 0, hence the result is negative and is equal to the b’s
complement of the sum part.
2’s Complement of 101.111
111.111
– 1 0 1 . 1 1 1
010.000+0.001=010.001
Final Ans : (10.001 – 100.01)2 = (–10.001)2

EXERCISE

Perform the following arithmetic :


(a) (652.05)8 – (74.2)8
(b) (10001.101)2 + (110011.11001)2
(c) (1000)16 + (75)16
(d) (1011101)2 – (110111)2 ...using 2’s complement
(e) (1001010)2 / (101)2
(f) (753)8 + (62)8
(g) (101)2 * (111)2
(h) (10001)10 + (6965.5)10
(i) (1101.11)2 – (1011.101)2
(j) (241.75)10 + (14.86)10
(k) (2050.0101)8 + (106.101)8
(l) (110111)2 – (1011101)2 ...using 1’s complement
(m) (DACA)16 + (FECA)16
(n) (33)8 + (2046)8
(o) (1010000)2 – (111)2 ...using 1’s complement
(p) (111)2 – (1010000)2 ...using 2’s complement
(q) (40033)8 – (2046)16 ...mixed base operation
(r) (5134B)16 – (270673)10
(s) (100)10 – (100)8
(t) (1000)2 – (11)16
(u) (1029)10 – (9201)16 ...complement method for the next set
(v) (26.AE)16 – (7.D)16
(w) (100100)2 – (11.001)2
(x) (123.45)8 – (76.5)8
qq

62
ENCODINGS
2
l Representation of Numbers
l Signed and Unsigned Representation of Binary Numbers
l Shortcomings of Sign—Magnitude Representation of Numbers
l Floating Point Representation of a Number
l Normalizing Floating Point Data
l Operations on Binary Numbers (Arithmetic, Logical, Shift)

 Floating Point Arithmetic

l Bitwise Operators
l Shift Operations on a Number
l Signed Bit Representation of a Binary Number
l Signed and Unsigned Numbers
l Two’s Complement form of Representing a Signed Bit Negative
Binary Number
l Mantissa-Exponent form of Signed-Bit Number Representation
l n – Bit Binary Floating Point Notation
l Normalizing a Number according to IEEE 32-bit standard :
l Trade — off between size of Mantissa and Exponent
l Single and Double Precision
l Characters and their Encodings

REPRESENTATION OF NUMBERS

Numbers can be represented in many forms. They may vary in their base such as
binary, octal, decimal, hexadecimal etc., or in the position of the decimal point such as
1234.56 × 10 or 12.3456 × 10^3 and so on.
ISC COMPUTER SCIENCE – XI

As we learn number representations, we start with the position of the digits of a


number. In a number, the position of lowest significance is on the rightmost hand which
is called the Least Significant Bit (LSB). The position of highest significance is on the
leftmost hand and is called the Most Significant Bit (MSB).

SIGNED AND UNSIGNED


REPRESENTATION OF BINARY NUMBERS
Binary numbers are represented by using n-bit notation where n indicates the bit
length.
In case of unsigned numbers, there is no provision of negative numbers. Hence,
there is no sign. In a n-bit representation, there can be values ranging between 0 and
2n –1.
In a 3-bit representation of a binary number, the smallest possible value is 000 and
the largest possible value is 111 (binary equivalent of 7 i.e., 23 – 1).
In a 4-bit representation of a binary number, the smallest possible value is 0000 and
the largest possible value is 1111 (binary equivalent of 15 i.e., 24 – 1).
Signed representation of binary numbers, can represent positive numbers, negative
numbers and zero. There are three ways of signed binary representation : (i) Sign-
magnitude representation, (ii) One’s complement representation, (iii) Two’s complement
representation.
(i) Sign–magnitude representation of a binary number
In this form, the most-significant bit (MSB) represents the sign of the number, 0 for
positive and 1 for negative. For a n-bit representation, 1-bit is reserved for the sign of the
number and the remaining (n – 1) bits are used for storing the number.
Example :
In a 4-bit representation, 1100 will be –4 , since binary equivalent of 100 is 4 and the
sign indicates a negative number.

1 1 0 0
Sign Value of the number

Example :
In a 4-bit representation, 0011 will be +3, since binary equivalent of 011 is 3 and
the sign indicates a positive number.

0 0 1 1
Sign Value of the number

Example :
In a 8-bit representation, 10100011 will be –35, since binary equivalent of 0100011 is
35 and the sign indicates negative number.

64
ENCODINGS

1 0 1 0 0 0 1 1
Sign Value of the number
Example :
In a 8-bit representation, 01001001 will be +73 , since binary equivalent of 1001001 is
73 and the sign indicates negative number.
0 1 0 0 1 0 0 1
Sign Value of the number

SHORTCOMINGS OF SIGN-MAGNITUDE
REPRESENTATION OF NUMBERS

(i) There are two representations of 0 :


As we know, 0 has no magnitude. But in sign-magnitude representation with n-bits,
there are two representations of 0, one with sign-bit 0 (as negative) and the other with
sign–bit 1(as positive).
Example :
In a 8-bit representation, +0 will be 00000000
0 0 0 0 0 0 0 0
Sign Value of the number

In a 8-bit representation, –0 will be 10000000

1 0 0 0 0 0 0 0
Sign Value of the number
(ii) The sign of the numbers need to be examined and processed separately before
operating on them for addition or subtraction.
One’s complement representation of a binary number
In this form, positive numbers are their normal binary equivalent while negative
numbers are the 1’s complement of the normal binary representation of the magnitude.
For a number requiring n-bits, the signed representation requires at least one extra bit.
Example : Represent +9 using one’s complement representation using 6-bits.
Binary equivalent of 9 is 1001.
In 6-bits, +9 will be represented as 001001.
Example : Represent –9 using one’s complement representation using 6-bits.
Binary equivalent of +9 is 001001.
In 6-bits, –9 will be the one’s complement of binary representation of +9 resulting
in 110110.

65
ISC COMPUTER SCIENCE – XI

Note : Negative numbers will have a 1 in the MSB and positive numbers will have a 0.
Note : Double representation of 0, as in previous case.
+0 in 6-bits will be 000000
–0 in 6-bits will be 111111
Two’s complement representation of a binary number
In this form, positive numbers are their normal binary equivalent while negative
numbers are the 2’s complement of the normal binary representation of the magnitude.
For a number requiring n-bits, the signed representation requires at least one extra bit.
Example : Represent +14 using two’s complement representation using 6-bits.
Binary equivalent of +14 is 1001.
In 6-bits, +14 will be represented as 001110.
Example : Represent –14 using two’s complement representation using 6-bits.
Binary equivalent of +14 is 001110.
In 6-bits, –14 will be the two’s complement of binary representation +14 resulting
in 110010.

Note : Negative numbers will have a 1 in the MSB and positive numbers will have a 0.
Note : Two’s complement gives the same representation of +0 and –0, since two’s
complement of 0 is 0 itself.

FLOATING POINT REPRESENTATION


OF A NUMBER

A number having a decimal point that divides the number into integer and fractional
part is called a floating point number.
For example : 32.76, 25.84
A floating point number can be written in many forms.
Example 1 : Decimal floating point number 42.576 can also be written as :
(i) 0.42576 × 102 (ii) 4257.6 × 10–2 (iii) 42576 × 10–3
In general, a floating point number can be written as M × BE,
where, M is the Mantissa, B is the base of the number system and E is the exponent.
When a number’s Mantissa is multiplied with BE,
(i) if E > 0, then in the result, the point moves towards right.
(ii) if E < 0, then in the result, the point moves towards left.
(iii) if E = 0, then in the result, the position of the point remains unchanged.

66
ENCODINGS

Example 2 : Octal floating point number 234.67 can also be written as :


(i) 0.23467 × 83 (ii) 23467 × 8-2
Example 3 : Hexadecimal floating point number 9AD2.EF can also be written as :
(i) 9AD2EF × 16–2 (ii) 9.AD2EF × 163 (iii) 0.009AD2EF × 166
Example 4 : Binary floating point number 101101110.011 can also be written as :
(i) 10110111001.1 × 2–2 (ii) 0.101101110011 × 29 (iii) 101101.110011 × 23

NORMALIZING FLOATING POINT DATA

A floating point data is normalized by moving the floating point in such a manner
that there is always a single non-zero digit in the integer part and rest are in decimal part
with the product of base^exp.
For example, for the given numbers the corresponding normalized equivalent values
are :

(1001.101)2 = 1.001101 × 23

(98732.0065)10 = 9.87320065 × 104

(0.0050684001)10 = 5.0684001 × 10 –3

(60052401)8 = 6.0052401 × 87

(0.0009AD2EF)16 = 9.AD2EF × 16–4

In a normalized floating point number, two cases occur depending on the size of the
exponent namely, overflow and underflow.

• Overflow : The exponent is too large to be represented in the Exponent field.

• Underflow : The exponent is too small to be represented in the Exponent field.

OPERATIONS ON BINARY NUMBERS


[ARITHMETIC, LOGICAL, SHIFT]

FLOATING POINT ARITHMETIC

Floating Point Addition


• To add two floating point values, they have to be aligned so that they have the
same exponent.
• After addition, the sum may need to be normalized.
• Potential errors include overflow, underflow and inexact results.

67
ISC COMPUTER SCIENCE – XI

For example :

2.34  × 103 622  × 108


+0.88  × 103 +3.93  × 108
3.22  × 103 10.15  × 108 = 1.015 × 109

Floating Point Subtraction

• Subtracting floating point values also require re-alignment so that they have the
same exponent.
• After subtraction, the difference may need to be normalized.
• Potential errors include overflow, underflow and inexact results as the difference
may have one significant bit less than the operands.

For example :

2.34 × 103 622 × 104


– 0.88 × 103 – 3.93 × 104
1.46 × 103 0.21 × 104 = 2.1 × 103

Floating Point Multiplication

• Multiplying floating point values do not require re-alignment. Re-alignment may


lead to loss of significance.
• After multiplication, the product may need to be normalized.
• Potential errors include overflow, underflow and inexact results.

For example :

2.4 × 10–3
× 6.3 × 102
15.12 × 10–3+2 = 15.12 × 10–1
= 1.512 × 100
= 1.512

Floating Point Division

• Dividing floating point values do not require re-alignment.


• After division, the (floating point) quotient may need to be normalized, there is
no remainder.

68
ENCODINGS

• Potential errors include overflow, underflow, inexact errors and attempts to


divide by 0.
For example :
1.86 × 1017 ÷ 7.44 × 105 = 0.25 × 108
= 2.5 × 107

BITWISE OPERATORS
Logical operators AND and OR can be applied on a binary number. It works in a
bit-wise fashion. The final result can be found by working on the pair of bits of the two
numbers.
AND OPERATOR
Example : 1101 AND 1011
Sol. 1101
AND 1011
1 0 0 1 … answer

Example : 101010 AND 11


Sol. 101010
AND 0 0 0 0 1 1
0 0 0 0 1 0 … answer

OR OPERATOR
Example : 100011 OR 110010
Sol. 100011
AND 110010
1 1 0 0 1 1 … answer

Example : 11010010 AND 1001


Sol. 11010010
AND 0 0 0 0 1 0 0 1
1 1 0 1 1 0 1 1 … answer

SHIFT OPERATIONS ON A
NUMBER
Shift operation performs shifting of binary digits by one bit at a time, in the given
direction, by the number mentioned on the right of the operator. It causes the specified
number of bits in the direction of shift to get eliminated and a 0 is pushed on the other end.
<< indicates a left shift and >> indicates a right shift

69
ISC COMPUTER SCIENCE – XI

Example : 0010 << 1 (perform one bit left shift)


→ 0100

Example : 1011 >> 1 (perform one bit right shift)


→ 0101

Example : 11001011 >> 2(perform two bit right shift)


→ 00110010

Example : 10101100 << 2(perform two bit left shift)


→10110000

Some Basic Binary System Terminologies :


(i) In binary number representation, only 0’s and 1’s are used.
(ii) A binary number is made up of binary digits called bits. Each bit can assume
either 0 or 1.
(iii) A group of 8 bits is called a byte. Half a byte, a group of 4 bits is called a
nibble.
(iv) A group of 2 bytes (16 bits) is commonly called a word.
(v) A word size may vary depending on the application, such as 32 or 64 bit word
is also possible.
In general, binary numbers are represented by using either 4-bits or 8-bits or
16 bits.

SIGNED BIT REPRESENTATION OF


A BINARY NUMBER
Sign of a number can be either positive or negative. Sign is represented by using the
symbol +/– for positive/negative values.
In signed bit representation of Binary numbers, instead of symbols +/– for positive/
negative values, signed bit value of 0/1 is used.
To represent an n-bit signed binary number, the leftmost bit is used for representing
the sign. The following table shows the bitwise values of an unsigned and signed-bit
4-bit binary number.

Bit 3 Bit 2 Bit 1 Bit 0


Unsigned 23 22 21 20
Signed –(23) 22 21 20

SIGNED AND UNSIGNED NUMBERS


The following table shows some examples of signed and unsigned representations
of binary numbers.

70
ENCODINGS

Decimal Equivalent
Binary
Unsigned Signed
3 2 1 0
0×2 +0×2 +1×2 +1×2 0 × 2 + 0 × 22 + 1 × 21 + 1 × 20
3

0011 = 0 + 0 + 2 + 1 = 0 + 0 + 2 + 1


= 3 = 3
1 × 23 + 0 × 22 + 1 × 21 + 1 × 20 –1 × 23 + 0 × 22 + 1 × 21 + 1 × 20
1011 = 8 + 0 + 2 + 1 = –8 + 0 + 2 + 1
= 11 = –5
0 × 23 + 1 × 22 + 1 × 21 + 1 × 20 0 × 23 + 1 × 2 2 + 1 × 2 1 + 1 × 2 0
0111 = 0 + 4 + 2 + 1 = 0 + 4 + 2 + 1
= 7 = 7
1 × 23 + 1 × 22 + 1 × 21 + 1 × 20 –1 × 23 + 1 × 22 + 1 × 21 + 1 × 20
1111 = 8 + 4 + 2 + 1 = –8 + 4 + 2 + 1
= 15 = –1

TWO’S COMPLEMENT FORM OF REPRESENTING A


SIGNED BIT NEGATIVE BINARY NUMBER
In any number system, when a number is added to its negative, the result is zero.
For example 5 + (–5) = 0.
In case of signed bit representation of a binary number, symbols + and – are not
used.
Instead a sign-bit is used, where 0 is for positive and 1 is for negative.
In signed-bit representation, the negative value of a binary number, say n, is the
two’s complement of n.
Signed-bit representation of +3 in 4-bits is 0011.
But the signed-bit representation of –3 in 4-bits is not 1011 (shown in the above
table).
The reason can be sited as +3 + (–3) = 0. But (0011) + (1011) = 1110 ≠ 0
So, we find the Two’s complement of 3 in 4-bits. [2’s Complement = 1’s Complement + 1]
N = 0011
TN = 1100 + 1 = 1101 [two’s complement of N]
If TN is the negative of N then N + TN should be 0. Let us verify–
N + TN = 0011 + 1101
= 10000 [where the 4-bit representation is 0000]
= 0
Therefore, we can say that TN is the negative value of N.
Example : Represent –23 in binary signed-bit representation (8-bits).

71
ISC COMPUTER SCIENCE – XI

Ans : Binary representation of 23 in 8-bits is 0001 0111


Let N = 00010111
CN = 11101000 [CN is one’s complement of N]
TN = CN + 1 = 11101001
Therefore, binary signed-bit representation (8-bits) of –23 is 1110 1001.
[To verify, 23+ (–23) = 0 → (0001 0111) + (1110 1001) = (0000 0000) … in 8-bits]

MANTISSA-EXPONENT FORM OF SIGNED-


BIT NUMBER REPRESENTATION
In mantissa-exponent form of data, a number has two parts : mantissa and exponent.
To write a given floating point number in mantissa-exponent form, the floating
point is relocated in such a way that :
(i) The mantissa part begins with a decimal-point.
(ii) The exponent contains the value of power to generate the actual number.
For example :

S. No. Given Number Mantissa-Exponent Form

(i) (42.576)10 0.42576 × 102

(ii) (36374.092)10 0.36374092 × 105

(iii) (0.0082)10 0.82 × 10-2

(iv) (–0.000010063)10 –0.10063 × 10-4

(v) (0.00000024)10 0.24 × 10-6

(vi) (–0.0014)10 –0.14 × 10-2

A number can be stored in memory bits, only when it is in binary form.

Steps To Represent A Number In Mantissa-Exponent Form In Binary


Signed-Bit Representation :
(i) The number is divided into mantissa (M) and exponent (E) form.
(ii) If both are positive, then find their binary equivalent and plot them in the bit
positions.
(iii) If E is negative, find its two’s complement and plot that.

Note :
l In sign-bit representation of a binary number, a negative number has its sign bit
value set to 1. It is represented by the two’s complement of the value of the number.

72
ENCODINGS

n-BIT BINARY FLOATING POINT NOTATION


As we know, all data and instructions that are sent to the computer have to be
encoded in series of 0 and 1. In this segment we will learn how to encode data.
For example :
(37.5)10 in 16-bit binary floating point notation will be (0011010010110000)2
Converting A Decimal Number To N Bit Binary Floating Point Notation :
To convert a decimal number to n-bit binary floating point notation, the steps are :
(i) Convert the given decimal number to binary.
(ii) Relocate the point and write the Mantissa and the Exponent in the form
0.M × 2E, where E can be either positive or negative.
(iii) If E is negative, find its two’s complement, which is to be plotted.
Shown below is an example of 16-bit memory with the given bit-significance.
1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa (M)
1 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11
S E M
Where
S—The sign bit of the number or mantissa.
E—The exponent, the first bit here is for sign of the exponent (0 for positive and
1 for negative). Negative exponent is represented in two’s complement form.
M—The mantissa, to utilize the bits available, the Mantissa is written in the
form 0. M and the values are kept unchanged by adjusting the exponent
accordingly.
Note :
l The base is 2, since the number represented is a binary number.
l If the exponent E begins with 0, then it is positive and its value is E itself.
l If E begins with 1, then the exponent is negative and its value is taken as the two’s
complement of E.
l The E part is filled from right to left (leading 0’s are not significant).
l The M part is filled from left to right (following 0’s are not significant because the
M part has a leading decimal point, that has been assumed).
Ex. 1. : E
 xpress 37.5 in a binary floating point notation on a 16-bit memory with
the given bit-significance 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Convert (37.5)10 to binary → (100101.1)2
Step 2 : Relocate the point and write the mantissa in the form 0.M × 2E
(100101.1)2 = 0.1001011 × 26

73
ISC COMPUTER SCIENCE – XI

Step 3 : E is positive. Represent E in binary form → 610 = 1102


Step 4 : S = 0 (since M is positive)
E = 0110 (4 bit Exponent)
M = 0.10010110000 (11 bit Mantissa)
0 0 1 1 0 1 0 0 1 0 1 1 0 0 0 0
1 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11
S E M
Answer : (37.5)10 in 16-bit binary floating point notation will be (0011010010110000)2
Ex. 2. E
 xpress (–0.125) in a binary floating point notation on a 16-bit memory with
the given bit-significance 1-bit Sign (S), 4-bit Exponent (E), 11–bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Convert (–0.125)10 to binary → (–0.001)2
Step 2 : Relocate the point and write the mantissa in the form 0.M × 2E
(–0.001)2 = –0.1 × 2-2
Step 3 : E is negative. Represent E in binary form and find its two’s complement in
4-bits
→ (2)10 = (10)2
Let N = 10 = 0010
CN = 1101 (One’s Complement)
TN = CN + 1 = 1101 + 1 = 1110(Two’s Complement)
Step 4 : S = 1 (since M is negative)
E = 1110 (4 bit Exponent, a negative number here)
M = 0.10000000000 (11 bit Mantissa)
1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0
S E M
Answer : (–0.125)10 in 16-bit binary floating point notation will be (1111010000000000)2.
Ex. 3. E
 xpress (–25.25) in a binary floating point notation on a 16-bit memory with
the given bit-significance 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Convert (–25.25)10 to binary → (–11001.01)2
Step 2 : Relocate the point and write the mantissa in the form 0.M × 2E
(–11001.01)2 = –0.1100101 × 25

74
ENCODINGS

Step 3 : E is positive. Represent E in binary form → 510 = 01012


Step 4 : S = 1 (since M is negative)
E = 0101 (4 bit Exponent, a positive number here)
M = 0. 11001010000 (11 bit Mantissa)
1 0 1 0 1 1 1 0 0 1 0 1 0 0 0 0
S E M
Answer : (–25.25)10 in 16-bit binary floating point notation will be (1010111001010000)2
Ex. 4. E
 xpress (0.0065) in a binary floating point notation on a 16-bit memory with
the given bit-significance 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Convert (0.0065)10 to binary → (0.0000000101010)2 [Approximately]
Step 2 : Relocate the point and write the mantissa in the form 0.M × 2E
(0.0000000101010)2 = 0.101010 × 2–7
Step 3 : E is negative. Represent E in binary form and find its two’s complement in
4-bits
→ (7)10 = (0111)2
Let N = 0111
CN = 1000 (One’s Complement)
TN = CN + 1 = 1000 + 1 = 1001 (Two’s Complement)
Step 4 : S = 0 (since M is positive)
E = 1001 (4 bit Exponent, a negative number here)
M = 0.10101000000 (11 bit Mantissa)

0 1 0 0 1 1 0 1 0 1 0 0 0 0 0 0
S E M
Answer : (0.0065)10 in 16-bit binary floating point notation will be (0100110101000000)2
Ex. 5. E
 xpress (–0.125) in a binary floating point notation on a 32-bit memory with
the given bit-significance 1-bit Sign (S), 8-bit Exponent (E), 23-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Convert (–0.125)10 to binary → (–0.001)2
Step 2 : Relocate the point and write the mantissa in the form 0.M × 2E
(–0.001)2 = –0.1 × 2–2

75
ISC COMPUTER SCIENCE – XI

Step 3 : E is negative. Represent E in binary form and find its two’s complement in
8-bits → (2)10 = (10)2
Let N = 10 = 00000010
CN = 11111101 (One’s Complement)
TN = CN + 1 = 11111101 + 1 = 11111110
 (Two’s Complement)
Step 4 : S = 1 (since M is negative)
E = 11111110 (8 bit Exponent, a negative number here)
M = 0.10000000000000000000000 (23 bit Mantissa)

1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
S E (8 bit) M (23 bit)
Answer : (–0.125)10 in 32-bit binary floating point notation will be (11111111010000
000000000000000000)2.
Ex. 6. E
 xpress (0.03125) in a binary floating point notation on a 32-bit memory
with the given bit-significance 1-bit Sign (S), 8-bit Exponent (E), 23-bit
Mantissa (M).
Ans. : Steps of conversion :
Step 1 : Convert (0.03125)10 to binary → (0.00001)2
Step 2 : Relocate the point and write the mantissa in the form 0.M × 2E
(0.00001)2 = 0.1 × 2–4
Step 3 : E is negative. Represent E in binary form and find its two’s complement in
8-bits
→ (4)10 = (100)2
Let N = 100 = 00000100
CN = 11111011 (One’s Complement)
TN = CN + 1 = 11111011 + 1 = 11111100
 (Two’s Complement)
Step 4 : S = 0 (since M is positive)
E = 11111100 (8 bit Exponent, a negative number here)
M = 0.10000000000000000000000 (23 bit Mantissa)
0 1 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
S E ( 8 bit ) M ( 23 bit )
Answer : (0.03125)10 in 32-bit binary floating point notation will be (1111111001000
0000000000000000000)2.

76
ENCODINGS

NORMALIZING A NUMBER ACCORDING TO


IEEE 32-BIT STANDARD

(i) The mantissa part assumes 1 on left of the point, to increase one more bit of
accuracy. This assumes the number to be non-zero.
However, to avoid possible confusion in the following, the default normalization
does not assume this implicit 1 unless otherwise specified.
Zero is represented by all 0’s and is not (and cannot be) normalized.
(ii) To avoid negative exponent values to an extent, the exponent is made biased.
Instead of 0, the value of the bias is 127.
Thus, in IEEE 32-bit standard, the notation becomes : (S) × (1.M) × (2)E+Bias
where, S—The sign of the number.
M—The Mantissa with 1 as its integer value.
E—The exponent.
Bias—The biased value 127.
Ex. 7. E
 xpress (–0.3125) in a binary floating point notation with IEEE 32-bit
standard.
Ans. : Steps of conversion :
Step 1 : Convert (–0.3125)10 to binary → (–0.0101)2
Step 2 : Relocate the point and write the mantissa in the form 1.M × 2E
(–0.0101)2 = –1.01 × 2–2
Step 3 : E is (–2). The biased exponent will be (–2 + 127) = 125
(125)10 = (1111101)2 (in 7 bits)
= (01111101)2 (in 8 bits)
Step 4 : S = 1 (since M is negative)
E = (01111101)2 (8 bit Biased Exponent)
M = 1.010000000000000000000000
(23 bit Mantissa, value 1 on the left of the point is taken for granted)

1 0 1 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
S E ( 8 bit ) M ( 23 bit )
Answer : (–0.03125)10 is binary floating point notation with IEEE 32-bit standard will
be (10111110101000000000000000000000)2.
Note :
l The bit significance for 32 bits : 1 (S), 8 (E), 23 (M) and for 64 bits : 1 (S), 11 (E),
52 (M).

77
ISC COMPUTER SCIENCE – XI

Converting A n-Bit Binary Floating Point Notation To Decimal Number


To convert a binary floating point notation to decimal number, the steps are :
(i) Extract the bit-significant values of S, E, M (using the given bit significance).
(ii) Identify and calculate E. It is in sign bit representation of a binary number.
(iii) Multiply the value of M with Base^E.
(iv) Convert the binary number to the equivalent decimal.
Shown below is an example of 16-bit memory with the given bit-significance.
1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa (M)
1 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11
S E M
Where S— The sign bit of the number or mantissa.
E—The exponent, present in sign bit representation of binary number.
M—The mantissa of the normalized form.
Ex. 8. (1111010000000000)2
Express the given binary floating point notation on a 16-bit memory in decimal
form. The bit significance is given as 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Extract the bit-significant values of S, E, M :

1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0
S E M
S = 1 (the number is negative)
E = 1 1 1 0
M = 1 0 0 0 0 0 0 0 0 0 0
Step 2 : Identification and calculation of E :
E = 1110, sign bit representation in 4 bits
1 × (–2 ) + 1 × 22 + 1 × 21 + 0 × 20 3

⇒ 1 × (–8) + 1 × 4 + 1 × 2 + 0 × 1
⇒ –8 + 4 + 2 + 0 ⇒ –2
Step 3 : The number is in form 0.M × Base ^ E
Num = (0.10000000000)2 × 2 ^ (–2)
= (0.001)2
Step 4 : Upon converting to decimal
= 0 × 2–1 + 0 × 2–2 + 1 × 2–3 = (0.125)10
Answer : (1100110000000000)2 represents (–0.125)10 in 16-bit binary floating point
notation.

78
ENCODINGS

Ex. 9. (0001010110000000)2
Express the given binary floating point notation on a 16-bit memory in decimal
form. The bit significance is given as 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Extract the bit-significant values of S, E, M :

0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0
S E M
S = 0 (the number is positive)
E = 0 0 1 0
M = 1 0 1 1 0 0 0 0 0 0 0
Step 2 : Identification and calculation of E :
E = 0010, sign bit representation in 4 bits
0 × (–23) + 0 × 22 + 1 × 21 + 0 × 20
⇒ 0 × (–8) + 0 × 4 + 1 × 2 + 0 × 1
⇒ 2
Step 3 : The number is in form 0.M × Base ^ E
Num = (0.10110000000)2 × 2 ^ (2)
= (10.11)2
Step 4 : Upon converting to decimal = 1 × 21 + 0 × 20 + 1 × 2–1 + 1 × 2–2 = (2.75)10
Answer : (0001010110000000)2 represents (2.75)10 in 16-bit binary floating point
notation.
Ex. 10. (1001110110000000)2
Express the given binary floating point notation on a 16-bit memory in decimal
form. The bit significance is given as 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Extract the bit-significant values of S, E, M :

1 0 0 1 1 1 0 1 1 0 0 0 0 0 0 0
S E M
S = 1 (the number is negative)
E = 0 0 1 1
M = 1 0 1 1 0 0 0 0 0 0 0
Step 2 : Identification and calculation of E :
E = 0011 , sign bit representation in 4 bits
0 × (–2 ) + 0 × 22 + 1 × 21 + 1 × 20
3

⇒ 0 × (–8) + 0 × 4 + 1 × 2 + 1 × 1 ⇒ 3

79
ISC COMPUTER SCIENCE – XI

Step 3 : The number is in form 0.M × Base ^ E


Num = (0.10110000000)2 × 2 ^ (3)
= (101.1)2
Step 4 : Upon converting to decimal = 1 × 22 + 0 × 21 + 1 × 20 + 1 × 2–1 = (5.5)10
Answer : (1001110110000000)2 represents (–5.5)10 in 16-bit binary floating point
notation.
Ex 11. (00000101010011100011000000000000)2
Express the given binary floating point notation on a 32-bit memory in decimal
form. The bit significance is given as 1-bit Sign (S), 8-bit Exponent (E), 23-bit Mantissa
(M).
Ans. : Steps of conversion :
Step 1 : Extract the bit-significant values of S, E, M :

0 0 0 0 0 1 0 1 0 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0
S E M
S = 0 (the number is positive)
E = 0 0 0 0 1 0 1 0
M = 10011100011000000000000
Step 2 : Identification and calculation of E :
E = 00001010, sign bit representation in 8 bits
0 × (–2 ) + 0 × 2 + 0 × 25 + 0 × 24 + 1 × 23 + 0 × 22 + 1 × 21 + 0 × 20
7 6

⇒ 10
Step 3 : The number is in form 0.M × Base ^ E :
Num = (0.10011100011000000000000)2 × 2 ^ (10)
= (1001110001.1)2
Step 4 : Upon converting to decimal
= 1 × 29 + 0 × 28 + 0 × 27 + 1 × 26 + 1 × 25 + 1 ×
24 + 0 × 23 + 0 × 22 + 0 × 21 + 1 × 20 + 1 × 2–1
= (625.5)10
Answer : (00000101010011100011000000000000)2 is (625.5)10 in 32-bit binary floating
point notation.
Ex. 12. (1111111100000000)2
Express the given binary floating point notation on a 16-bit memory in decimal form.
The bit significance is given as 1-bit Sign (S), 6-bit Exponent (E), 9-bit Mantissa (M).
Ans. : Steps of conversion :
Step 1 : Extract the bit-significant values of S, E, M :
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
S E M

80
ENCODINGS

S = 1 (the number is negative)


E = 1 1 1 1 1 1
M = 1 0 0 0 0 0 0 0 0
Step 2 : Identification and calculation of E :
E = 1 1 1 1 1 1, sign bit representation in 4 bits
  1 × (–2 ) + 1 × 2 + 1 × 23 + 1 × 22 + 1 × 21 + 1 × 20
5 4

⇒ –32 + 16 + 8 + 4 + 2 + 1
⇒   –1
Step 3 : The number is in form 0.M × Base ^ E :
Num = (0.100000000)2 × 2 ^ (–1)
= (0.01)2
Step 4 : Upon converting to decimal = 0 × 2–1 + 1 × 2–2 = (0.25)10
Answer : (1111111100000000)2 represents (–0.25)10 in 16-bit binary floating point
notation.

Limitations of Finite Representation


Floating-point numbers are represented in computer hardware as base 2 (binary)
fractions.
For example, the decimal fraction 0.125 is 0.001 in binary.
Unfortunately, many decimal fractions cannot be represented exactly as binary
fractions. As a result, the decimal floating-point numbers are only approximated by the
binary floating-point numbers actually stored in the machine.
For example, decimal value 0.1 cannot be represented exactly as a binary based
value.
(0.1)10 = (0.0001100110011001100110011001100110011001100110011...)2.

CHARACTERS AND THEIR ENCODING

The American Standard Code for Information Interchange (ASCII) is a character-


encoding scheme. Originally based on the English alphabet, it encodes 128 specified
characters into 7-bit binary integers as shown by the ASCII chart below. It includes
English alphabets (lower and upper case), digits, symbols and special characters. ASCII
code had a limitation that it was confined to a few characters and could not include
further characters. To overcome this problem, extended ASCII codes were introduced.
Later UNICODE was introduced which has 16-bits and could represent characters of
various languages other than English.
The Unicode is an international encoding standard for use with different languages
and scripts, by which each letter, digit or symbol is assigned a unique numeric value

81
ISC COMPUTER SCIENCE – XI

that applies across different platforms and programs. Unicode allows for 17 planes, each
of 65,536 possible characters (or ‘code points’). This gives a total of 1,114,112 possible
characters.
ASCII Chart

Extended ASCII code takes the list upto 255 characters. It includes some more special
characters.


Extended ASCII codes EBCDIC codes
Extended Binary Coded Decimal Interchange Code (EBCDIC) is an 8-bit character
encoding used mainly on IBM mainframe and IBM midrange computer operating
systems.
82
ENCODINGS

In an EBCDIC file, each alphabetic or numeric character is represented with an 8-bit


binary number (a string of eight 0’s or 1’s). 256 possible characters (letters of the alphabet,
numerals and special characters) are defined.
ASCII and EBCDIC codes are not same. They differ in their presentation and codes
of characters.
EXERCISE

1. State True or False. Correct the false statements :


(a) (125.25)10 = 0.12525 × 10 3 (b) (101101)2 = 10.1101 × 10–2
(c) (142360.0241)8 = 1423600241 × 85 (d) (ABCD.EF)16 = ABCDE.F × 16
2. Normalize the given data by relocating the floating point :
(a) (0.00001024)10 (b) (200.00CD)16
(c) (0.001001001)2 (d) (800.203004)8
3. Write the decimal equivalent value of the following Signed Bit Representation of
a Binary Number in 6-bits :
(a) (110101)2 (b) (011011)2
(c) (101110)2 (d) (001101)2
4. Represent the following Decimal Numbers Signed Bit Binary Number in 8-bits
(using 2’s Complement) :
(a) –19 (b) –27
(c) –11 (d) –6
5. Represent the following Decimal Numbers in Binary Floating Point Notation :
(A) 16-bit memory bit-significance 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa (M).
(a) (24.75)10 (b) (–35.25)10
(c) (10.125)10 (d) (64.5)10
(e) (–16.25)10
(B) 32-bit memory bit-significance 1-bit Sign (S), 8-bit Exponent (E), 23-bit Mantissa (M).
(a) (100.001)10 (b) (–0.015625)10
6. Given the Binary Floating Point Notation , find the corresponding Decimal
Number it is representing :
(A) 16-bit memory bit-significance 1-bit Sign (S), 4-bit Exponent (E), 11-bit Mantissa (M).
(a) (0111011000000000)2 (b) (1001111100000000)2
(B) 32-bit memory bit-significance 1-bit Sign (S), 8-bit Exponent (E), 23-bit Mantissa (M).
(a) (11111111001000000000000000000000)2 (b) (00000010110010010000000000000000)2

qq

83
PROPOSITIONAL
3 LOGIC

l Proposition and Propositional Logic


l Properties of a proposition
l A Truth Table
l Connectives
l Propositional Definitions
l Simple Laws on Propositions
l Propositional Statement and Expression

PROPOSITION AND PROPOSITIONAL LOGIC

A proposition is a statement that has a value, which can be either true or false but
can’t be anything else. The value of a proposition is called its Truth Value.
Propositional logic uses statements which are atomic in nature. These statements are
called propositions.

Propositions Non-Propositions
• Lina read the book “The Shadow • Which book did Lina read ?
Lines”. • Who took Anil’s copy ?
• Anil lost his copy. • In which month annual exams will
• M > V when M = 10 and V = 7. take place ?

PROPERTIES OF A PROPOSITION
Propositions have the following properties :
(i) A proposition has a truth value which cannot be anything other than True or
False.
(ii) Propositions can be connected using connectives to result in another proposition.
(iii) They are represented by using upper case alphabets.
(iv) States of a proposition can be represented by a Truth Table.
PROPOSITIONAL LOGIC

A TRUTH TABLE
A truth table is a complete list of possible values of a proposition. For example, let P
be a proposition, given that P – My class work copy is full. Now, P can assume any one
of its truth values (true or false).
The Truth Table of —
(i) One variable P is as follows : (ii) Two variables P, Q is as follows :
Term Term
Proposition P P Q
Numbers Numbers
Value (False) 0 0 0 0 0
Value (True) 1 1 0 1 1
1 0 2
1 1 3

(iii) Three variables P, Q, R is as follows : (iv) Four variables P, Q, R, S is as follows :


Term Term
P Q R P Q R S
Numbers Numbers
0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 1 1
0 1 0 2 0 0 1 0 2
0 1 1 3 0 0 1 1 3
1 0 0 4 0 1 0 0 4
1 0 1 5 0 1 0 1 5
1 1 0 6 0 1 1 0 6
1 1 1 7 0 1 1 1 7
Note : Term numbers ranging from : 1 0 0 0 8
(i) 0 to 1 indicates 1 Boolean variable. 1 0 0 1 9
(ii) 0 to 3 indicates 2 Boolean variable. 1 0 1 0 10
(iii) 0 to 7 indicates 3 Boolean variable. 1 0 1 1 11
(iv) 0 to 15 indicates 4 Boolean variable. 1 1 0 0 12
1 1 0 1 13
1 1 1 0 14
1 1 1 1 15

CONNECTIVES
A. Atomic propositions can be connected to create a larger proposition. They are
connected by using connectives. Connectives used in Propositional Logic are :

85
ISC COMPUTER SCIENCE – XI

u NEGATION — NOT
u CONJUNCTION — AND
u DISJUNCTION — OR
u CONDITIONAL — IF...THEN
u BI-CONDITIONAL — IF AND ONLY IF…THEN
hown below are Truth Tables of various connectives. Assume P, Q are two
S
propositions.
[Let P — The bird can talk. Q — The bird can sing.]
(i) Negation ( ~ or ’ ) — also known as NOT or COMPLEMENT. Also denoted as P’
or ~P. It is applicable on a single proposition.
P P’ Example :
0 1 P — The bird can talk.
1 0 P’ — The bird can NOT talk.
 onjunction ( ^ ) — also known as AND, denoted with symbol (.) Dot. The
(ii) C
result of conjunction is true only when both the atomic propositions are true. We
can say that C = P.Q, where C is a proposition denoting the result of conjunction.
P Q C Example :
0 0 0 P — The bird can talk.
0 1 0 Q — The bird can sing.
1 0 0 C — The bird can talk
1 1 1 AND the bird can sing.

Note :
l As mentioned above, P’s value 0 indicates P is False and P’s value 1 indicates P is
True. Similar is for Q and C.
The statement C is True only when both P and Q are True. It can also be said that
the validity of statement C is False when P or Q (any one or both) is False.
(iii) Disjunction ( ) — also known as OR, denoted with symbol (+) Plus. The result
of disjunction is true if any of the atomic propositions is true. It is false only
when both the atomic propositions are false. We can say that D = P + Q, where
D is a proposition denoting the result of disjunction.
P Q D Example :
0 0 0 P — The bird can talk.
0 1 1 Q — bird can sing.
1 0 1 D — The bird can talk OR the bird
1 1 1 can sing.
(iv) Conditional ( ) — also known as IMPLIES or IF..THEN. Let M be P ⇒ Q. The
result of condition is such that if P is true then Q will have to be true. Along
with these criteria, when P is false, Q can be allowed to be both false and true.
86
PROPOSITIONAL LOGIC

P Q D
0 0 1 Example :
0 1 1 P — The bird can talk.
1 0 0 Q — The bird can sing.

1 1 1 D — If the bird can talk.


then the bird can sing.
Let D be P ⇒ Q. It can be interpreted as : D—If the bird can talk then the bird can
sing.
If ‘The bird can talk’ is true, then P is 1. And since P ⇒ Q, so whenever P is true, Q
will have to be true to make D possible.
So when P is 1 then Q’s value 1 is making D possible and so D is 1.
When P is 1 then Q’s value 0 is making D impossible and so D is 0.
Now, if ‘The bird can talk’ is false, then P is 0. When P is not true, Q may assume
any value. [as the bird may or may not sing when the bird can talk.] So, D is possible (1)
for both values of Q.
P Q simplifies to P’ + Q
(v) Biconditional ( ) – Also known as EQUIVALENCE or IF AND ONLY IF or
IFF. Let B be P  Q. The result of bicondition B is true when both P and Q are
true or when both are false. It can be simplified as (P ⇒ Q AND Q ⇒ P).
P Q B
0 0 1 Example :
0 1 0 P — The bird can sing.
1 0 0 Q — The bird can talk.
1 1 1
Let B be P  Q. It can be interpreted as : B—If the bird can sing then the bird can
talk and if the bird can talk then the bird can sing.
If ‘The bird can sing’ is true then P is 1. If ‘The bird can talk’ is true then Q is 1. B is
valid, when both are true or when both are false. If anyone is true and the other is false,
B is not valid.
P Q simplifies to P’.Q’ + P.Q

PROPOSITIONAL DEFINITIONS
(i) Well Formed Formula. (ii) Tautology.
(iii) Contradiction. (iv) Contingency.
(v) Satisfiable. (vi) Unsatisfiable.

87
ISC COMPUTER SCIENCE – XI

(vii) Premise. (viii) Syllogism.


(ix) Chain Rule. (x) Modus Ponens.
(xi) Converse. (xii) Inverse.
(xiii) Consistent Statement. (xiv) Contrapositive.
Well Formed Formula (wff) : It is an expression of Boolean statements made up of
elementary statements and symbols. It can be constructed according to the following rules :
u All smaller statements are wff.
u If P is a wff then P’ is a wff.
u If P and Q are wff then – P.Q, P + Q, P ⇒ Q, P ⇔ Q are also wff.
u Nothing else is a wff.
Tautology : A proposition that is always true. A tautology has only true values
(1) in its truth table.
For example :
(i) Let T1 be A + A’ (ii) Let T2 be A + B + B’
A A’ T1 Term
A B B’ T2
0 1 1 Number
1 0 1 0 0 1 1 0
0 1 0 1 1
1 0 1 1 2
1 1 0 1 3
[Expression of T2 can be plotted directly. Term A sets term number 2 and 3 to 1.
Term B sets term number 1 and 3 to 1, of which term number 3 is already 1. Term B’ sets
term number 0 and 2 to 1.]
Contradiction : A proposition that is always false.
A contradiction has only false values (0) in its truth table column.
For example :
(i) Let C1 be A . A’ :
A A’ C1
0 1 0
1 0 0
(ii) Let C2 be B.A.B’ :
Term
A B B’ B.A C2
Number
0 0 1 0 0 0
0 1 0 0 0 1
1 0 1 0 0 2
1 1 0 1 0 3
[Expression of C2 can be plotted directly as well. C2 will be 1 only in those terms

88
PROPOSITIONAL LOGIC

where the truth values of all the three columns (B A B’) is 1 at the same time. In case of
C2, no such combination is present.]
Contingency : A proposition that contains values which are combinations of false
and true (0 and 1). These propositions are sometimes true and sometimes false.
For example :
(i) Let N1 = A.B + A’.B’
Term
A B A’ B’ A.B A’.B’ N1
Number
0 0 1 1 0 1 1 0
0 1 1 0 0 0 0 1
1 0 0 1 0 0 0 2
1 1 0 0 1 0 1 3
(ii) Let N2 = A.B.C’ + A.B’.C + A’.B.C + A.B.C
Term
A.B.
A B C A’ B’ C’ A.B.C.’ A.B’.C A’.B.C N2 Num-
C
ber
0 0 0 1 1 1 0 0 0 0 0 0
0 0 1 1 1 0 0 0 0 0 0 1
0 1 0 1 0 1 0 0 0 0 0 2
0 1 1 1 0 0 0 0 1 0 1 3
1 0 0 0 1 1 0 0 0 0 0 4
1 0 1 0 1 0 0 1 0 0 1 5
1 1 0 0 0 1 1 0 0 0 1 3
1 1 1 0 0 0 0 0 0 1 1 7

Satisfiable : A Boolean expression is called Satisfiable if among its truth values there
exists at least one 1.
Unsatisfiable : A Boolean expression is called Unsatisfiable if all its truth values are
0. A contradiction is an unsatisfiable expression.
Premise : It is a proposition from which a conclusion is drawn.
For example : 6 is the number that appears after 5. So 5 + 1 = 6.
In general it can be said that…this is so (concluded) because….that is so (premise).
Syllogism : It is a form of logical reasoning in which a logical conclusion is drawn
from two premises. The premises share a common element called middle term.
P—All fruits are green.
Q —Orange is a fruit.
R— Orange is green.

89
ISC COMPUTER SCIENCE – XI

Chain Rule : It states that two conditions of form P ⇒ Q and Q ⇒ R can be combined
to create a new condition P ⇒ R.
For example : Let [P—You study.] , [Q – You pass the exam.] and [R—You get a job.]
P ⇒ Q — If you study then you pass the exam.
Q ⇒ R — If you pass the exam, you get a job.
P ⇒ R — If you study, you get a job.
Modus Ponens : It states that whenever in a condition, the antecedent is true, the
consequent will be true.
For example : Let [P—The car tyre got punctured.] and [Q—The car could not move.]
If the condition P ⇒ Q is true and P is true then Q will be true. Here, P is Antecedent
and Q is Consequent.
P ⇒ Q — If the car tyre got punctured then the car could not move.
P — P is true. The car tyre got punctured.
Q — Q will be true. The car could not move.
Converse : For a condition P ⇒ Q, its Converse is Q ⇒ P.
For example : Let [P—The cat was hungry.] and [Q – The cat drank the milk.]
P ⇒ Q — If the cat was hungry then the cat drank the milk.
Q⇒P — If the cat drank the milk then the cat was hungry.
Inverse : For a condition P ⇒ Q, its Inverse is P’ ⇒ Q’.
For example : Let [P — The box was locked.] and [Q — The box had gold biscuits in it. ]
P ⇒ Q — If the box was locked then the box had gold biscuits in it.
P’ ⇒ Q’ — If the box was not locked then the box did not have gold biscuits in it.
Consistent statements : A group of statements is called consistent if it is possible for
all of them to be true together. Otherwise they are called Inconsistent.
For example : Let [P— Rob is a rabbit.], [Q — Rob is not a rabbit.] and [R — Rob is white.]
(P.R) — is not a contradiction. P, R are consistent.
(P.Q) — is a contradiction. P, Q are not consistent or are inconsistent.
Contrapositive : It states that whenever in a condition, the consequent is false, the
antecedent is also false.
For example : Let [P—The car tyre got punctured.] and [Q —The car could not move.]
P ⇒ Q — If the car tyre got punctured then the car could not move.
Q’ ⇒ P’ — If the car could move then the car tyre did not get punctured.
Exercise : Prove that the chain rule (p ⇒ q ∧ q ⇒ r) ⇒ (p ⇒ r) is a tautology.
Proof : Let M = (p ⇒ q ∧ q ⇒ r) N = (p ⇒ r) [Hint : 1 ⇒ 0 is 0]

90
PROPOSITIONAL LOGIC

p⇒q q⇒r M p⇒r


p q r M⇒N
X Y X.Y N
0 0 0 1 1 1 1 1
0 0 1 1 1 1 1 1
0 1 0 1 0 0 1 1
0 1 1 1 1 1 1 1
1 0 0 0 1 0 0 1
1 0 1 0 1 0 1 1
1 1 0 1 0 0 0 1
1 1 1 1 1 1 1 1

SIMPLE LAWS ON PROPOSITIONS


Law I : P + P’ = 1 P.P’ = 0
Law II : P + 1 = 1 P + 0 = P
Law III : P.1 = P P.0 = 0
Proof of the above laws using Truth Tables :
Law I : Law II : Law III :

P P’ P + P’ P.P’ P P+1 P+0 P P.1 P.0


0 1 1 0 0 1 0
0 0 0
1 1 1
1 0 1 0 1 1 0

Note :
l The operations on propositions result in True or False which are denoted by 1 or 0
only.

PROPOSITIONAL STATEMENT AND EXPRESSION


Example 1 : Consider the two given propositions :
C : The car belongs to a doctor.
M : The car is red in colour.
Write the Expression of the Combinational Statement :
u Combinational Statement :
W : Either the car belongs to a doctor and the car is red in colour or the car does not
belong to a doctor and the car is not red in colour.
 ewriting W : (The car belongs to a doctor AND the car is red in colour) OR (the car
R
does not belong to a doctor AND the car is not red in colour).

91
ISC COMPUTER SCIENCE – XI

Expression of W : (C . M ) + (C’ . M’)


u C
ombinational Statement :
V – The car does not belong to a doctor but the car is red in colour.
Rewriting V : (The car does not belong to a doctor) AND (the car is red in colour).
Expression of V : C’ . M
Example 2 : Consider the two given propositions :
J : The road was jam-packed.
K : Kyrz did not reach on time.
Write the expression of the Combinational Statement :
u C
ombinational Statement :
D : The road was not jam-packed, but Kyrz reached on time.
Rewriting D : (The road was not jam-packed) AND ( Kyrz reached on time).
Expression of D : J’.K’
u Combinational Statement :
N : Neither the road was jam-packed nor did Kyrz reach on time.
Rewriting N : (The road was not jam-packed) AND (Kyrz did not reach on time).
Expression of N : J’ . K
u Combinational Statement :
T : Kyrz reached on time because the road was jam-packed.
Rewriting T : (Kyrz reached on time AND the road was jam-packed).
Expression of T : (K’ . J)
Example 3 : Consider the two given propositions :
R — They will go to Rome.
N — They are not Roman.
Write the Combinational Statement of the given Expressions :
u Expression (i) M : (R.N’) + (R’.N)
Combinational Statement of M : (They will go to Rome AND they are Roman) OR
(they will not go to Rome AND they are not Roman).
u Expression (ii) S : (R + N’)
Combinational Statement of S : (They will go to Rome OR they are Roman)
u Expression (iii) P : R + N + (R’.N’)
Combinational Statement of P : (They will go to Rome) OR (they are not Roman)
OR (they will not go to Rome AND they are Roman).
Example 4 : Consider the two given propositions :
H — Home-works are necessary.

92
PROPOSITIONAL LOGIC

L — Students do not like home-work.


Write the Combinational Proposition of the given Expressions :
u Expression (i) T1 : H . L’ + H’. L
Combinational Statement of T1 : (Home-works are necessary AND students like
home-work) OR (home-works are not necessary AND students do not like home-
work).
u Expression (ii) T2 : H . L + H’ + L’
Combinational Statement of T2 : (Home-works are necessary AND students do not
like home-work) OR (home-works are not necessary) OR (students like home-work).

REAL LIFE BASED APPLICATIONS


In Real Life based Applications of Propositional Logic, a truth table is plotted
according to the criteria given. The truth table generates the corresponding Boolean
expression.
The following examples show how to implement the above.
Question 1 : A family decides to create a Voting Machine that will help them to
take decisions. There were four members in the family : Father(F), Mother(M), Son(S)
and Daughter(D). Any proposal gets passed only if any one of the following conditions
is true :
• Both parents say yes.
• Both children and Father say yes.
• Both children and Mother say yes.
Inputs are :
F — Father voting Yes.
M — Mother voting Yes.
S — Son voting Yes.
D — Daughter voting Yes. [1 indicates yes, 0 indicates no]
Output is : P
— The proposal is passed. [1 indicates yes, 0 indicates no]
(a) Draw the truth table for the inputs and outputs given above.
(b) Write the expression for P (F, M, S, D).
Solution :
I. Planning the truth table
For four inputs, there will be four input columns in the truth table. For the output
there will be one output column. All possible combinations of the input set has to plotted
and for each criteria of positive output, the output column term has to be made 1. Finally
for the non-happening criteria, the output column term has to be made 0.
Make the truth table.

93
ISC COMPUTER SCIENCE – XI

Method of Truth Table Plotting


Condition 1 : Both parents say yes.
Father votes yes → F=1
Mother votes yes → M=1
All the values of S and D are to be considered.
So, the terms that will become 1 from this condition are (12 , 13 , 14 , 15).
Condition 2 : Both children and Father say yes.
Father votes yes → F=1
Son votes yes → S = 1
Daughter votes yes → D = 1
All the values of M are to be considered.
So, the terms that will become 1 from this condition are (11, 15).
Condition 3 : Both children and Mother say yes.
Mother votes yes → M = 1
Son votes yes → S = 1
Daughter votes yes → D = 1
All the values of F are to be considered.
So, the terms that will become 1 from this condition are (7, 15).
II. The Truth Table
F M S D P Term Num
0 0 0 0 0 0
0 0 0 1 0 1
0 0 1 0 0 2
0 0 1 1 0 3
0 1 0 0 0 4
0 1 0 1 0 5
0 1 1 0 0 6
0 1 1 1 1 7
1 0 0 0 0 8
1 0 0 1 0 9
1 0 1 0 0 10
1 0 1 1 1 11
1 1 0 0 1 12
1 1 0 1 1 13
1 1 1 0 1 14
1 1 1 1 1 15

94
PROPOSITIONAL LOGIC

III. The Sum of Product Expression


P (F, M, S, D) = ∑ (7, 11, 12, 13, 14, 15)
= F ’. M . S . D + F . M ’. S . D + F. M . S ’. D ’
+ F . M . S’. D + F . M . S . D’ + F . M . S . D
Question 2 : In a Home Delivery Store, it was observed that the sales were more if
any one of the following conditions were true :
• There were rains and the time was after 8 pm.
• The season was summer and the year-end sale was on.
• The year-end sale was not on but there were rains.
• The time was not after 8 pm and the year-end sale was not on.
Inputs are :
R — There were rains.
S — The season was summer.
T — The time was after 8 pm.
Y — The year-end sale was not on. [1 indicates yes, 0 indicates no]
Output is : M — More Sales [1 indicates yes, 0 indicates no]
(a) Draw the truth table for the inputs and outputs given above.
(b) Write the expression for M (R, S, T , Y).
Solution :
I. Planning the truth table
Condition 1 : There were rains and the time was after 8 pm.
R = 1 T=1
So, the terms that will become 1 from this condition are (10, 11, 14, 15).
Condition 2 : The season was summer and the year-end sale was on.
S = 1 Y=0
So, the terms that will become 1 from this condition are (4, 6, 12, 14).
Condition 3 : The year-end sale was not on but there were rains.
Y = 1 R=1
So, the terms that will become 1 from this condition are (9, 11, 13, 15).
Condition 4 : The time was not after 8 pm and the year-end sale was not on.
T = 0 Y=1
So, the terms that will become 1 from this condition are (1, 5, 9, 13).

95
ISC COMPUTER SCIENCE – XI

II. The Truth Table


R S T Y M TN
0 0 0 0 0 0
0 0 0 1 1 1
0 0 1 0 0 2
0 0 1 1 0 3
0 1 0 0 1 4
0 1 0 1 1 5
0 1 1 0 1 6
0 1 1 1 0 7
1 0 0 0 0 8
1 0 0 1 1 9
1 0 1 0 1 10
1 0 1 1 1 11
1 1 0 0 1 12
1 1 0 1 1 13
1 1 1 0 1 14
1 1 1 1 1 15

III. The Sum of Product Expression


M (R, S, T, Y) = S (1, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15)
= R’.S’.T’. Y + R’.S. T’.Y’ + R’.S.T’.Y + R’.S.T.Y’ + R.S.’.T’.Y +
R.S’. T. Y’ + R. S’. T. Y + R. S. T’. Y’ + R. S. T’. Y + R. S. T. Y’
+ R. S. T. Y
Question 3 : A
 Silver Pen was the award of a male student if he satisfied any one of
the following :
• He was never late and his haircut was always ok.
• His work was always up-to-date and he never got a red mark.
• His work was always up-to-date although his haircut was sometimes not ok.
Inputs are :
L — He was never late.
R — He always got red mark.
H — His haircut was always ok.
W — His work was always up-to-date. [1 indicates yes, 0 indicates no]
Output is : S – Silver Pen awarded.  [1 indicates yes, 0 indicates no]
(a) Draw the truth table for the inputs and outputs given above.
(b) Write the expression for S (L, R, H, W).

96
PROPOSITIONAL LOGIC

Solution :
I. Planning the truth table
Condition 1 : He was never late and his haircut was always ok.
L = 1 H=1
Condition 2 : His work was always up-to-date and he never got a red mark.
W = 1 R=0
Condition 3 : His work was always up-to-date although his haircut was sometimes
not ok.
W = 1 H = 0[although = and]
[For the variables not mentioned in a condition, consider both cases.]
L R H W S Term Number
0 0 0 0 0 0
0 0 0 1 1 1
0 0 1 0 0 2
0 0 1 1 1 3
0 1 0 0 0 4
0 1 0 1 1 5
0 1 1 0 0 6
0 1 1 1 0 7
1 0 0 0 0 8
1 0 0 1 1 9
1 0 1 0 1 10
1 0 1 1 1 11
1 1 0 0 0 12
1 1 0 1 1 13
1 1 1 0 1 14
1 1 1 1 1 15

II. The sum of product Expression :


S (L, R, H, W) = ∑(1, 3, 5, 9, 10, 11, 13, 14, 15)
Example 4 : An Electronic Digit can represent any of the
decimal digits ranging from 0 to 9 using glowing rods. It is made
up of 7 binary lines. Each of these lines get a value of 1 (to glow) or
0 (not to glow) depending on the digit selected.
For example, to represent 0, it will have all its rods glowing
except N5.
The following truth table shows the truth values of the rods
depending on the digits selected.
Draw the block diagram for the following output lines.

97
ISC COMPUTER SCIENCE – XI

The Truth Table


Term
Decimal Input Output
Num
Digit
Input D3 D2 D1 D0 N1 N2 N3 N4 N5 N6 N7

0 0 0 0 0 1 1 1 1 0 1 1 0

1 0 0 0 1 0 0 1 0 0 1 0 1

2 0 0 1 0 1 0 1 1 1 0 1 2

3 0 0 1 1 1 0 1 0 1 1 1 3

4 0 1 0 0 0 1 1 0 1 1 0 4

5 0 1 0 1 1 1 0 0 1 1 1 5

6 0 1 1 0 1 1 0 1 1 1 1 6

7 0 1 1 1 1 0 1 0 0 1 0 7

8 1 0 0 0 1 1 1 1 1 1 1 8

9 1 0 0 1 1 1 1 0 1 1 1 9

The Block Diagram of the circuit will be as follows :

EXERCISE

1. Answer the following :


(a) What is a proposition ? Write its properties.
(b) What is a Truth Table ?
(c) What are Connectives ? How are Conditional and Biconditional different ?
(d) What is a Well Formed Formula ?
(e) Define Converse, Inverse and Contra Positive with example.

98
PROPOSITIONAL LOGIC

2. State True or False (Correct the false statements) :


(a) A Tautology is Satisfiable.
(b) A Premise is a proposition from which a conclusion is drawn.
(c) A Contingency can be sometimes false.
(d) (True and False) = False.
(e) Contrapositive Rule states that If P ⇒ Q then Q ⇒ P.
3. Given the two propositions :
(a) D : You did not do. W : You won.
Write the expressions of the combinational propositions T1 , T2, T3 :
T1 : You won it in spite of not doing it.
T2 : All that you did, you could not win.
T3 : It never happened that you won without doing it.
Write the combinational propositions of the given expressions E1 and E2 :
E1 : D’ + W’
Expression I.
E2 : D.W’ + D’.W
Expression II.
(b) W : The water is safe for drinking. B : The water is blue in colour.
Write the expressions of the combinational propositions V1 and V2 :
V1 : The water is safe for drinking if and only if the water is blue in colour.
V2 : The water is not blue in colour but it is safe for drinking.
Write the combinational propositions of the given expressions Y1 and Y2 :
Expression I : Y1 : W + B’ + W’.B
Expression II : Y2 : (W . B’) + (W . B)
4. Verify using Truth Table ( Equal, Tautology, Contradiction, Contingency) :
(a) (p ⇔ q) = (p ⇒ q) . (q ⇒ p) (f) (a + b) ⇒ (a.b) is a Contingency.
(b) (m’ + m.n) = (m ⇒ n) (g) (a.b) ⇒ a is a Tautology.
(c) (x’.y’ + x + y ) ’ is a Contradiction. (h) (a.b) ⇒ (a ⇒ b) is a Tautology.
(d) (a + b) . (a’ + b’) = (a.b’ + a’.b) (i) (m + n’) = (m’ + n)
(e) (a . b) ⇒ (a + b) is a Tautology. (j) (a’ + a.b’ + b.c’ + c)’ = a’ + c

5. Answer the following :

(a) Given below are situations of propositional statements :


An airlines company had certain reservations on allotting a window seat for a
long journey. A window seat was allotted to a passenger if :
• The passenger is of age  between 3 to 7 years and accompanied by an adult.
• Is a lady and not accompanied by an adult.

99
ISC COMPUTER SCIENCE – XI

• Is not of age between 3 to 7 years and is travelling for the first time.
• Is a lady and is travelling for the first time.
Inputs are :
G : The passenger is of age  between 3 to 7 years.
C : Is accompanied by an adult.
L : Is a lady.
F : Is travelling for the first time.
Output is : W : The passenger gets a window seat. [1 indicates yes, 0 indicates no]
(i) Draw the truth table for the inputs and outputs given above.
(ii) Write the Sum of Product expression for W (G, C, L, F).
(b) Given below are situations of propositional statements :
In a company meeting, it was told to everyone that a person cannot accept a
mobile phone call when :
• He is in office and is in a meeting.
• He is not in office but is driving.
• He is driving and is having a cake.
• He is not in office but having a cake and is in a meeting.
Inputs are : F : The person is in office.
D : The person is driving.
M : The person is in a meeting.
C : The person is having a cake.
Output is : N : The person cannot accept the mobile phone call.
 [1 indicates yes, 0 indicates no]
(i) Draw the truth table for the inputs and outputs given above.
(ii) Write the Sum of Product expression for N (F, D, M, C).
(c) Given below are situations of propositional statements :
Mt Vesuvius Express would stop on a city station if :
• The city had no trap and the platform was not perfect.
• The platform was not long ranged and had no artifact.
• The city had no trap and the platform had artifact.
• The platform was not long ranged and the platform had artifact.
Inputs are :
T : The city had a trap.
R : The platform was long ranged.
A : The platform had no artifact.
P : The platform was perfect. [1 indicates yes, 0 indicates no]

100
PROPOSITIONAL LOGIC

Output is :
V : Mt Vesuvius Express would stop on a city station.
(i) Draw the truth table for the inputs and outputs given above.
(ii) Write the Sum of Product expression for V (T, R, A, P).
(d) Given below are situations of propositional statements :
 Ustad Zakir Hussain gave permission to his singers to have ice-cream only if
any one of the following happened :
• The month was April and the city was dry.
• The city was not dry but the singer had toothache and the next function was
after two months.
• The month was not April but the city was dry and the singer had toothache.
• The next function was after two months and the city was dry.
Inputs are : A : The month was April.
D : The city was dry.
T : The singer had no toothache.
N : The next function was two months away.
Output is : C : The singer can have ice-cream.[1 indicates yes, 0 indicates no]
(i) Draw the truth table for the inputs and outputs given above.
(ii) Write the Sum of Product expression for C (A, D, T, N).

qq

101
4 LOGIC GATES

l Logic Gate

 Elementary Logic Gates (AND, NOT, OR)


 Universal Gates (NAND, NOR)


 Other Gates (XOR, XNOR)

l Logic Gate Diagrams using Elementary Gates


l Universal Gates

 Universal NAND Gate


 Relation between SOP Expressions and Universal
NAND Gates

 Universal NOR Gate


 Relation between POS Expressions and Universal
NOR Gates
l Application of Logic Gates–Half Adder, Full Adder

LOGIC GATE

A logic gate is an elementary digital circuit that gives the result of a propositional
operation. Signals that are used as input and output in a Logic Gate can be either 0 or 1.
Digital circuits are made by using Logic Gates.
Elementary Logic Gates

(i) NOT Gate : This gate inverts the input signal to its complement. It implements
the operation ‘Negation’.
P P’
0 1
1 0
LOGIC GATES

(ii) AND Gate : This gate connects two signals using the connective AND. It
implements the operation ‘Conjunction’. It gives a True result only if both inputs are True.
P Q C
0 0 0
0 1 0
1 0 0
1 1 1
(iii) OR Gate : This gate connects two signals using the connective OR. It implements
the operation ‘Disjunction’.
P Q D
0 0 0
0 1 1
1 0 1
1 1 1

Universal Logic Gates


[In detail in later section of the chapter.]
(iv) NAND Gate : This gate inverts the signal of an AND gate.
P Q N1
0 0 1
0 1 1
1 0 1
1 1 0
(v) NOR Gate : This gate inverts the signal of an OR gate.
P Q N2
0 0 1
0 1 0
1 0 0
1 1 0

Other Logic Gates


(vi) XOR Gate : This gate gives the result of (P.Q’ + P’.Q). Symbol of XOR is ⊕.
P Q X1
0 0 0
0 1 1
1 0 1
1 1 0

103
ISC COMPUTER SCIENCE – XI

(vii) XNOR Gate : This gate gives the result of (P.Q + P’.Q’). Symbol of XNOR is

P Q X2
0 0 1
0 1 0
1 0 0
1 1 1

Sum of Product Form of An Expression (SOP Form) :

A Boolean expression can be written in the form of Sum of Product-terms.

Product terms are those in which elementary propositions are multiplied. For
e.g., A.B’.C

Sum of product-terms result as : A


.B’.C + A.B.C’ + A’.B.C’ + A.B.C
Product of Sum Form of An Expression (POS Form) :

A Boolean expression can also be written in the form of Product of Sum-terms.

Sum terms are those in which elementary propositions are added. For e.g., (A+B’+C)

Product of Sum-terms result as : ( A + B’+C) . (A+B+C’) . (A’+B+C’) . (A+B+C)

LOGIC GATE DIAGRAMS

Draw the Logic Gate Diagram of the following Boolean Expressions using Elementary
Gates. [Assume that the AND, OR gates can accept more than two inputs.]
(i) F1 = A.B’ + A’.B [A XOR B]

104
LOGIC GATES

(ii) G4 = A.B + A’.B’ [A XNOR B]

(iii) F3 = A + B’ + A’.B’

(iv) G6 = A.B.C + A’.B’.C’ + A.B’.C

105
ISC COMPUTER SCIENCE – XI

(v) F2 = A.B.C’ + A.B’.C + A’.B.C + A’.B’.C’

UNIVERSAL GATES
Universal gates are those which can replace all the other elementary gates.
There are two universal gates—NAND and NOR.
Using NAND and NOR gates, all the three elementary gates can be generated.

Universal Nand Gate


Generating the elementary gates by using Universal NAND gate.
NOT using NAND :
NOT Gate : Not using NAND Gate


AND using NAND :
AND Gate : AND Gate using NAND Gate :

106
LOGIC GATES

OR using NAND :
OR Gate : OR Gate using NAND Gate :


Q. How to draw a Logic Gate Diagram (LGD) using Universal NAND Gates ?
Ans. There are two methods of drawing LGD using Universal NAND Gates. In
Method I, the LGD is drawn by using elementary gates and then the gates are reduced.
In Method II, the expression is converted to another form and the reduced LGD is drawn.
The steps of Method I are given below :
Step I : Draw the LGD using elementary gates.
Step II : Draw a second diagram by replacing each elementary gate with equivalent
NAND Gates.
Step III : Reduce the gates if possible. [Double inversion of the same line nullifies
two gates.]

Logic Gate Diagram using Universal NAND Gates

(i) F1 = A.B’ + A’.B

Step I : Diagram using elementary gates :

107
ISC COMPUTER SCIENCE – XI

Step II : Diagram by replacing each elementary gate with equivalent NAND Gates :

From the above diagram, we can see that Gate 2 and 5 invert the output of Gate 1
twice. Hence they can be removed. Similarly, Gate 4 and 6 invert the output of Gate 3
twice. They can also be removed.
Step III : Diagram after reducing the NAND Gates. :

Output of the above diagram :


Gate 1 : (A.B’)’ Gate 2 : (A’.B)’ Gate 7 : ((A.B’)’ . (A’.B)’)’= ((A.B’) + (A’.B))
Relation between SOP Expressions and Universal NAND Gates
SOP expressions can be drawn using Universal NAND Gates, by replacing the
elementary gates directly. Note that, if a term has a single variable, then it should be inverted.
Ex. 1. F3 = A.B + A’.B’
Step I : Diagram using elementary gates :

F3

108
LOGIC GATES

Step II : Diagram using universal NAND Gates : 


 [Simply replace the elementary gates with NAND gates.]

Output of the above diagram :


Gate 1 : (A.B)’
Gate 2 : (A’.B’)’
Gate 3 : ((A.B)’ . (A’.B’)’)’= (A.B) + (A’.B’)
Ex 2. F4 = A + B.C
Step I : Diagram using elementary gates :

Step II : Diagram using Universal NAND Gates. [Replace the elementary gates
with NAND gates. The term containing single variable is made to pass
through inverter (NOT Equivalent gate).]

109
ISC COMPUTER SCIENCE – XI

Output of the above diagram :


Gate 1 : A’ Gate 2 : (B.C)’ Gate 3 : ((A)’ . (B.C)’ )’= (A) + (B.C)
Q. What happens if the single term of SOP expression is not complemented (as
shown in the above example) ?

Ans. When the NAND gate works as an OR gate, it needs the individual entries
to be complemented. If a term is not alone and it passes through a NAND gate, it gets
complemented and then further when it is passed through another NAND gate, it gets
inverted again to it’s original state, providing the required expression. Whereas it is not
the case when a single term is not negated before going through the final NAND gate.
The following diagram shows the error caused if the single term is not complemented.

Output of the above diagram :


Gate 2 : (B.C)’
Gate 3 : (A . (B.C)’)’= A’ + B.C
Thus, the final expression is not giving F4 as output.

UNIVERSAL NOR GATE

Q. Why is the NOR gate a Universal Gate ?


Ans. Universal gates are those which can be used instead of any of the elementary
gates. The NOR gate is such a gate. It can be used to generate all the three elementary
gates as shown below :
Generating the elementary gates by using Universal NOR gates
NOT using NOR :

NOT Gate : NOT Gate using NOR Gate :

A (A + A)' = A'

110
LOGIC GATES

OR using NOR :
OR Gate : OR Gate using NOR Gate :

AND Using NOR :


AND Gate : AND Using NOR :

A A'

(A'+B')=A.B

B B'


Q. How to draw a Logic Gate Diagram using Universal NOR Gate ?
Ans. The steps are given below :
Step I : Draw the LGD using elementary gates.
Step II : Draw a second diagram by replacing each elementary gate with equivalent
NOR Gate circuit.
Step III : Reduce the gates if possible.
[Double inversion of the same line nullifies two gates.]

Logic Gate Diagram Using Universal NOR Gates

(i) H1 = (A + B’).(A’+ B)
Step I : Diagram using elementary gates :

111
ISC COMPUTER SCIENCE – XI

Step II : Diagram by replacing every elementary gate with equivalent NOR Gates :

From the above diagram, we can see that Gate 2 and 5 invert the output of Gate 1
twice. Hence, they can be removed. Similarly, Gate 4 and 6 invert the output of Gate 3
twice. They can also be removed.
Step III : Diagram after reducing the NOR Gates :

Output of the above diagram :


Gate 1 : (A+B’)’ Gate 2 : (A’+B)’
Gate 7 : ((A+B’)’ + (A’+B)’)’= ((A+B’) . (A’+B))
Relation between POS Expressions and Universal NOR Gates
POS expressions can be drawn using Universal NOR Gates, by replacing the
elementary gates directly. Note that, if a term has a single variable, then it should be
inverted.
Ex. 1 : H3 = (A+B) . (A’+B’)
Step I : Diagram using elementary gates :

112
LOGIC GATES

Step II : Diagram using universal NOR Gates :


[Simply replace the elementary gates with NOR gates.]

A B

1
H3
3

Output of the above diagram :


Gate 1 : (A+B)’ Gate 2 : (A’+B’)’
Gate 3 : ((A+B)’ + (A’+B’)’)’ = (A+B) . (A’+B’)
Ex. 2 : H4 = A.(B+C)
Step I : Diagram using elementary gates :

Step II : Diagram using Universal NOR Gates. [Replace the elementary gates with
NOR gates. The term containing single variable is made to pass through
inverter (NOT Equivalent gate).]

Output of the above diagram :


Gate 1 : A’ Gate 2 : (B+C)’ Gate 3 : (A)’ + (B+C)’)’ = A.(B+C)
Q. What happens if the single term of POS expression is not complemented (as
shown in the above example) ?
Ans. When the NOR gate works as an OR gate, it needs the individual entries
to be complemented. If a term is not alone and it passes through a NOR gate, it gets

113
ISC COMPUTER SCIENCE – XI

complemented and then further when it is passed through another NOR gate, it gets
inverted again to it’s original state, providing the required expression. Whereas it is not
the case when a single term is not negated before going throught the final NOR gate.
The following diagram shows the error caused if the single term is not
complemented.

Output of the above diagram :


Gate 2 : (B + C)’ Gate 3 : (A + (B+C)’)’= A’.(B + C)
Thus, the final expression is not giving H4 as output.

APPLICATION OF LOGIC GATES

Half Adder
A circuit that performs the addition of two bits is called a Half Adder.
A Half Adder circuit is a combinational arithmetic circuit that adds two bits and
produces two bits, a sumbit (S) and a carry bit (C) as the output. If P and Q are the input
bits, then the sum bit (S) is the XOR of P and Q and the carry bit (C) is the AND of P and Q.
Shown below is the truth table of a Half Adder.

Input Output
P Q C S
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 0

The simplified expressions of the two output lines of a Half Adder are :
S = P’.Q + P.Q’ or P ⊕ Q C = P.Q
The block diagram of a Half Adder is shown below :

114
LOGIC GATES

The Logic Gate diagram of a Half Adder is shown below :

P Q

Full Adder
A combinational circuit that performs the addition of three bits is called a Full Adder.
A Full Adder is an arithmetic circuit that adds three bits and produces two bits, a
sum bit (S) and a carry bit (C) as the output. If P, Q, R are the input bits then the sum bit
(S) is P ⊕ Q ⊕ R and the carry bit (C) is P.Q + Q.R + R.P.
Shown below is the truth table of a Full Adder.

Input Output
P Q R Term Num C S
0 0 0 0 0 0
0 0 1 1 0 1
0 1 0 2 0 1
0 1 1 3 1 0
1 0 0 4 0 1
1 0 1 5 1 0
1 1 0 6 1 0
1 1 1 7 1 1

115
ISC COMPUTER SCIENCE – XI

The expressions of the two output lines of a Full Adder are :


S = ∑ (1, 2, 4, 7) = P’.Q’.R + P’.Q.R’ + P.Q’.R’ + P.Q.R [not reducible]
C = ∑ (3, 5, 6, 7) = P’.Q.R + P.Q’.R + P.Q.R’ + P.Q.R [reducible]
The reduced expression of C = P.Q + Q.R + P.R
The block diagram of a Full Adder is shown :

The Logic Gate Diagram of a Full Adder is shown below, where


C = P.Q + Q.R + P.R
S = P’.Q’.R + P’.Q.R’ + P.Q’.R’ + P.Q.R or P ⊕ Q ⊕ R

P Q R

116
LOGIC GATES

P Q R
S

EXERCISE

1. Answer the following :


(a) What are Logic Gates ?
(b) What are Universal Gates ?
(c) What is the relation between SOP expressions and Universal NAND Gates ?
(d) What is an Half Adder ? Explain.
(e) What is a Full Adder ? Explain.

2. Draw the Logic Gate Diagram of the following using :

(A) Elementary Gates :


(a) p’.q’.r + p.q.r + p.q’.r’ + p’.q.r’
(b) m + m’.n’ + n + m.n
(c) a.b’.c’.d + a’.b’.c.d + a’.b.c.d’ + a.b.c’.d’ + a’.b.c’.d
(d) p . (p + q’) . (p’ + q) . q’
(e) (m + n) . (s’ + m’) . (s + n’)
(B) Universal NAND Gates :
(a) p.q + p’.q
(b) m’. n’ + n
(C) Universal NOR Gates :
(a) p.q’ + p’.q’
(b) m . (n + m’)

117
ISC COMPUTER SCIENCE – XI

3. Write the output of the following Logic Gate Diagrams :


(a)

(b)

qq

118
INTRODUCTION
5 TO JAVA

l Object Oriented Programming and its features


l Class and Object
l Data and Behaviour of Objects of a Class
l Java–An Object Oriented Programming Language
l Introduction to Java Programming
l Java Tokens
l Wrapper Class
l Type Casting
l Mixed types of data;
l Priority of operators

OBJECT ORIENTED PROGRAMMING


In real world, we are surrounded by objects which belong to some class or the other.
Object Oriented Programming (also called OOP) applies this concept in programming.
OOP also implements other concepts which are related to the real world. Let us look into
some of such OOP concepts.
Features of Object Oriented Programming
An Object Oriented Program has the following features :
(a) Encapsulation : All related data and methods are enclosed within one boundary
(a class).
(b) Inheritance : A derived (child) class is able to access data/methods of its base
(parent) class. This feature helps in code reusability.
(c) Dynamic Binding : Programs are written in such a way that during runtime, the
linking of data and methods takes place. This feature provides flexibility to a
program.
(d) Polymorphism : Ability of the methods to have the same name but to behave
differently under different situations.
ISC COMPUTER SCIENCE – XI

(e) Abstraction : The result of a task is presented without giving the details of how
the task is performed.
(f) Modularity : A big program is divided into small working modules which are
connectable.

CLASS AND OBJECT


Class

A class implements the concept of encapsulation. It bounds data and methods that
are relevant to one task. A class serves as a definition to describe an entity. It is like a
blueprint or a template which can be used for creating objects of same type.
Example : A House can be seen as a class which encapsulates its necessary member
data and methods.
Example : Similarly a School or a Bank can also be seen as classes which encapsulate
their necessary member data and methods.

Object

An object is an instance of a class. A class is a definition of data and methods. An


object implements that class in reality. So, we can say that in real life, all that we see
around us are objects of various classes.
Example :
Class—Wall-Clock : The data of a Wall-Clock can be many, few of which are—
colour, size, etc.
The methods of a Wall-Clock can be many, few of which are—show_time, ring_
alarm, etc.
Object : The wall-clocks that exist in real world are all objects of class Wall-Clock
which have the above mentioned data and methods.


Objects of Wall-Clock Objects of School

120
INTRODUCTION TO JAVA

Class—School : The data of a School can be many, few of which are—name, student-
strength, etc.
The methods of a School can be many, few of which are—teaching, playing,
examination, etc.
Object : The schools that exist in the real world are all objects of class School which
have the above mentioned data and methods.

DATA AND BEHAVIOUR OF OBJECTS OF A CLASS


Data or Attributes are those members of a class that store relevant information.
Behaviour or Methods of a class contain the execution steps to perform a certain
task. A method is also called a process or a function.
Data and Method belonging to a class are called member data and methods of that
class. It is mentionable that behaviour of a class changes upon addition, deletion or
modification of existing methods.
Difference between Class and Object
Class Object
It bounds the data and methods that are It is an instance of a class.
relevant to a task.
A class is like a blueprint or a template An object implements a class in the real
which can be used for creating objects of world. All that we have seen in real life
the same type. around us, are objects of various classes.

JAVA—AN OBJECT ORIENTED


PROGRAMMING LANGUAGE
It is a programming language that has many features. It was developed by James
Gosling, Mike Sheridan and Patrick Naughton. Sun Microsystems first launched it in
1995. The latest version of Java is Version 8 that was released on 18th of March, 2014. The
code name culture is dropped with Java 8, so no official code name going forward from
Java 8.
Features of Java
I. Simple : Java Programming Language provides many assisting tools that make
it easy to learn. Its compilation process shows the errors to the programmer.
II. Platform Independent : Programs written in Java can be executed on any other
platform (such as Windows, Unix, Linux, MacOS, etc.) that has the Java Virtual
Machine (JVM).
III. Portable : The feature of Platform Independence makes a Java program portable,
following the concept of “Write Once Run Anywhere (WORA)”.
IV. Dynamic and Distributed : Java programs can use other required files either
from the local drive or from other computers by getting connected to the Internet.
121
ISC COMPUTER SCIENCE – XI

V. Object Oriented : Java fulfills all important features of Object Oriented


Programming, which are—abstraction, encapsulation, polymorphism,
inheritance, dynamic binding, modularity.
VI. Robust : Java provides powerful error (exception) handling mechanisms. Thus,
Java programs crash very rarely.
VII. Secure : Java has a very efficient security model that makes it one of the most
dependable programming languages. Given below are some of the security
features :
 The Sand Box : All the Java programs are run under as area called the Sand
Box, which allows only secure programs to run and prevents activities from
unreliable sources.
 No Pointers : Access to memory blocks can be a potential risk in memory
management. Programming languages C/C++ have a feature called Pointer,
which allows memory access in a program. Java does not have pointers,
instead it has its own internal memory management system, that keeps the
memory guarded.
 Exception Handing : An exception is said to occur when the normal
execution of a program is disrupted. There exceptions of various types, such
as IOException, ArithmeticException, ArrayIndexOutOfBoundsException to
name a few. Java can handle exceptions by using try..catch block or by the
use of keyword throws. It even gives the programmer a way to define user
specific exception handling code by the use of keyword “throw”.
 Java Byte Code : Every program is converted to Java Byte Code during
compilation, which is tested in the Java Virtual Machine that prevents any
malicious code to reach the actual processor of the computer system. This
feature brings security security and other advantages to Java programs.
VIII. Wide Application Area : Java programming language can be used in
developing programs of various kinds. It is also used in a variety of devices for
implementing solutions such as networking of PCs, the internet, mobile and
entertainment software etc.
IX. Interactive Internet Programming : Java can be used to write interactive
Internet programs which are helpful in giving users choice while going through
a webpage. Applications for playing games over the Internet and similar.
X. Multithreads : Threads are executable parts of a program. Multithreading
means a single program having multiple threads working at the same time.
Multithreading in a program is similar to multiprocessing in a processor.
Java Byte Code
Java code is complied to create Java Byte Code which is then processed by Java
Virtual Machine. This code is independent of the processor of the computer system. The
portability or machine independence of Java program is because of this Java Byte Code.

122
INTRODUCTION TO JAVA

JVM is a machine but built as a program and brought through hardware. So, it is
called a virtual machine. To run, JVM machine language programs require an interpreter.
The advantage is that, such JVM machine language programs (.class files) are portable
and can run on any machine that has the java program.
Java Virtual Machine (JVM)
This is a Software that converts Java Byte Code to Machine Level Language. It works
as a platform for a Java program, and can be executed on any platform (Windows, Unix,
Linux etc). JVM or Java Virtual Machine comes in between a compiled Java Code and the
Computer System. JVM is the main component of the Java architecture and is a part of the
Java Runtime Environment (JRE). JVM combined with Java API (Application Program
Interface) makes the Java Platform. Most compilers provide code for a computer system
but Java compiler produces code for JVM.
The functioning of Java Virtual Machine (JVM)
When a Java program is compiled, the compiler creates a code called Java Byte Code
for the Java Virtual Machine. Now, for different operating systems, this Java Virtual
Machine (JVM) converts the Java Byte Code to a machine executable code. Hence, if the
operating system is Windows, JVM creates a machine code that is executable in it. A
different machine code is created by the JVM if the operating system of the computer is
Unix or is LINUX and so on.
Advantage of JVM–Java is Platform Independent
Java compiler creates Java Byte Code which is interpreted by the Java Virtual
Machine for any computer system (platform). This feature makes a Java program
platform independent. For different platforms, the Java code need not be changed, only
the interpreter has to be changed.

123
ISC COMPUTER SCIENCE – XI

Exception Handling in Java


In Java, Exception means exceptional situations (of errors). Java has a very efficient
compiler for handling errors. It has a name and details for every exception. It even
gives scope to write built-in error messages or user error messages in case of exceptions
through try {...} catch {...} block. Other error handling syntax is throws.

INTRODUCTION TO JAVA PROGRAMMING


Steps to work on a Java BlueJ program :

I. Click on the BlueJ icon on the start menu. It will show the BlueJ
opening screen.

II. Click on Project → New Project to begin a new Project.

The Project Window


III. Give a name to the New Project and click on Create. It gets created in the
specified folder [shown in Look in].
IV. Programs are written in a class. To make a new class, click on New Class. A
dialog box opens up. Name the class and click on OK. The class icon appears in
the project window.
V. Right click on the icon. A list appears. Choose Open Editor. [You may also
double click the icon to open the editor.]
124
INTRODUCTION TO JAVA

The Program Window [Sample program and modified program].


VI. A sample program appears with comment lines. Change this code to make
your own program by adding and deleting the required statements.
VII. Close/minimize the program window to go to the project window. Any change
in the program causes stripes to reappear on the class icon. The stripes on the
class icon means that the program is not compiled. A Java BlueJ program can
be executed only after compilation.
VIII. To compile the program, click on the Compile button. The compilation is
successful in case of correct syntax.
IX. After successful compilation, the program has to be executed. Right click on
the class icon and choose option ‘new test1()’.

X. An object is created (red rectangular box) at the left bottom of the screen. Right
click on the object to get a list of methods. Click on the method to execute it.

The Output Screen

125
ISC COMPUTER SCIENCE – XI

Before we begin with Java programming in detail, let us learn about a few basic
terminologies.

JAVA TOKENS
Token : A token is the smallest identifiable part of a program. Following are the
tokens in Java—Keywords, Identifiers, Literals, Separators and Operators.
Let us now see the details of the various tokens.
Keywords : These are the words that convey a specific meaning to the compiler.
There are reserved words and are used for special purposes and thus, cannot be used as
normal identifiers. List of keywords used in Java is given below :
abstract char else if native short throw
boolean const extends implements new static throws
break continue final import package strictfp transient
byte double finally instanceof private super try
case default float int protected switch void
catch do for interface public synchronized volatile
class enum goto long return this while
Identifiers : Identifiers are names given to variables, constants, classes, methods.
Keywords cannot be used as identifiers.
To use indentifiers in Java programs certain rules are to be followed such as :
l The first character of an identifier must be a letter, an underscore (_), or a dollar
sign ($).
l The rest of the characters in the identifier can be a letter, underscore, dollar sign
or digit.
Note that spaces are NOT allowed in identifiers.
l Identifiers are case-sensitive. This means that age and Age are different.
l Java’s keywords/reserved words cannot be used as identifiers.
E.g., of Valid identifiers : SubValue, $name, totMarks, PI, _address
E.g., of Invalid Identifiers :
1. Sub Value....spaces are not allowed.
2. p + q .....arithmetic operators cannot be used.
3. int....int is a keyword.
4. 7day ....identifiers cannot start with a digit.
5. (week) ...braces or any other special character other than _and $ are not allowed.
Literals : Literals are constants that have a fixed value of any of the data-types.
For example : 9, 3.7 are numeric literals. ‘a’ is a character literal. false is a boolean
literal.
Named Constants : These are special kind of variables which have a fixed value
throughout. Its value is set at compile time which cannot be changed at runtime.
126
INTRODUCTION TO JAVA

To create a named constant, keyword final is used. They are called final constants.
For example : final double PI = 3.142;
Now in the program, the value of PI cannot be changed. Any attempt to change the
value of PI in the program will cause error.
In addition, to make a variable constant to all the objects of a class, keyword static
is used with final.
For example : static final double PI = 3.142;
Separators : The following nine ASCII characters are the Java separators (punctuators) :
( ) { } [ ] ; , .
; is also called a statement terminator.
Operators : Operators are special symbols that perform specific operations on one,
two, or three operands and then return a result.
Unary Operators : These operators are used with one variable to indicate its sign.
Java has two Unary Operators + and –.
Arithmetic Operators Relational Operators
+ Additive operator =  = Equal to
– Subtraction operator != Not equal to
* Multiplication operator > Greater than
/ Division operator >= Greater than or equal to
% Remainder operator < Less than
(Modulo or Mod or Modulus) <= Less than or equal to
Logical Operators
! NOT
&& AND
|| OR
Assignment Operator : This operator is used to assign a value to a variable. There
are certain rules to be followed while using the assignment operator :
 It assigns the value on its right side to a variable on its left side.
 It cannot have a constant on its left side.
 Cannot have any expression on its left side.
 It can reuse a variable.
 On its left side is the memory location and on its right side is the content.
Difference between left-hand side and right-hand side of assignment operator :
 Only a variable can be present on the left side whereas on the right side there can
be a constant, variable or expression.
 Left side denotes the memory location of a variable whereas the right side denotes
the content of the memory location.
 Left side receives a value whereas right side supplies a value.

127
ISC COMPUTER SCIENCE – XI

Precedence or priority of operators


Precedence or Priority means the order in which operators get executed. For example
(a+b*c)....* has higher priority than + thus, * gets executed before + in the expression.
The following chart shows priority in order.
Operator Associativity Precedence
( ) Function Left-to-Right Highest 14
[] Array subscript
. Dot (Member of structure)
–> Arrow (Member of structure)
! Logical NOT Right-to-Left 13
- One’s complement
– Unary minus (Negation)
++ Increment
–– Decrement
& Address-of
* Indirection
(type) Cast
sizeof Sizeof
* Multiplication Left-to-Right 12
/ Division
% Modulus (Remainder)
+ Addition Left-to-Right 11
– Subtraction
<< Left-shift Left-to-Right 10
>> Right-shift
< Less than Left-to-Right 9
<= Less than or equal to
> Greater than
>= Greater than or equal to
= = Equal to Left-to-Right 8
!= Not equal to
& Bitwise AND Left-to-Right 7
^ Bitwise XOR Left-to-Right 6
| Bitwise OR Left-to-Right 5
&& Logical AND Left-to-Right 4
|| Logical OR Left-to-Right 3
?: Conditional Right-to-Left 2
=, + = Assignment operators Right-to-Left 1
* =, etc.
, Comma Left-to-Right Lowest 0
Table : Precedence and Associativity Table

128
INTRODUCTION TO JAVA

Rules of Evaluating Expressions

1. Arithmetic Operators follow the given priority or precedence :


* / % Higher Priority (left to right)
+ – Lower Priority (left to right)
Worked Example :
(i) R = 25 + 5 * 2 Ans. : R = 35
(ii) R = 5 * 20 /10 Ans. : R = 10
(iii) R = (int) 5 / 10 * 20 Ans. : R = 0 … because of integer division
(iv) R = 5.0 / 10 * 20 Ans. : R = 10.0 … datatype of R is double
(v) R = 5 * 25 – 10 + 25 / 5 Ans. : R = 120
2. Assignment Operator allows a variable to get a value using a constant or another
variable.
3. Only a variable can be written on the left-hand side of the assignment operator.
Statement : It is the smallest unit of a program that gets executed. Statements in Java
are terminated by a semicolon (;).
Block : A group of statemements that have a specific aim is called a block. They are
used to divide big tasks into smaller ones. It helps in understanding bigger problems.
Blocks are generlly enclosed within a pair of parenthesis (second bracket { } ).
Comments : Comments are those parts of a program that do not get executed. They
are used to write notes for better understanding of a program. In Java, comments are of
three types :
Single line comment : The compiler ignores the part of the line that comes after it.
It begins with //.
Example :
// a single line comment
Multiple line comment : The compiler ignores the part that is enclosed within it. It
begins with /* and ends with */.
Example :
/* a multiple
line comment*/
Documentation comment : It encloses documentation on the program or any
method. The compiler ignores the part that is enclosed within it. It begins with /** and
ends with */.

129
ISC COMPUTER SCIENCE – XI

Example :
/** documentation
...
...
... */
Primitives used in Java : Primitives are the elementary data types stored in Java.
These data types are recognized by the Java compiler for memory allocation that is
needed during compilation. There are 8 primitives in Java out of which 4 are integer
based, 2 are floating point based, 1 for storing true/false and 1 for storing characters.
Integer based primitives : byte, short, int, long
Floating point based primitives : float, double
True/False based primitive : boolean
Character based primitive : char
Few of the primitives are tabulated as follows :

Primitive Description Size Example


byte byte length integer 1 byte byte b = 2;

short Short integer whole numbers 2 bytes short s = 7;

int Integer whole numbers 4 bytes int x = 5;


long Bigger integer whole numbers 8 bytes long n = 980807465
float Fractional numbers 4 bytes float f = 45.7

double Bigger fractional numbers 8 bytes double d = 72.8893444265534

char Keyboard characters 2 bytes char h = ‘d’

boolean Values of type True or False 1 byte boolean st = false

Note :
l The default value of a numeric data type is 0. Character and String have null values
as false is the default value of boolean data type.

WRAPPER CLASS

A Wrapper Class is a special kind of class which wraps the value of a primitive data
type in an object. These classes contain certain methods which are useful for handling
data and objects.

130
INTRODUCTION TO JAVA

For example :
int n = 5; // n declared as an integer primitive whose value is 5
Integer wn = new Integer(7); // wn is not a primitive but an object of wrapper class
Integer
int cn = wn.IntValue(); // methods of wrapper class called by its object.
S. No. Primitive Wrapper Class S. No. Primitive Wrapper Class
(i) boolean Boolean (v) float Float
(ii) byte Byte (vi) int Integer
(iii) char Character (vii) long Long
(iv) double Double (viii) short Short

The methods of a wrapper class are static. Static functions can be invoked by using
the class itself, without creating an object.
A wrapper class contains a parameterized constructor through which, its member
data can be assigned a value.
Class as a Mechanism for User Defined Types : A class is created in a program to fulfill
user requirements. It can have its own member data and member methods. Once a class
is created, multiple objects can be created from it. A class can also be called a user defined
data type.
For example :
class Book
{
String name, author, genre;
double price;
Book()
{
name = “”;
author = “”;
price = 0;
genre = “”;
}
void IssueBook()
{ //code to assign values to member data of a Book
}
void ModifyBook()
{

131
ISC COMPUTER SCIENCE – XI

//code to modify data of a Book


}
void main()
{
Book mybook1 = new Book ();
Book mybook2 = new Book(); //creating 2 books, user defined types
}
}
Shown above is a partial program demonstrating class as a mechaninsm for user
defined types.

TYPE CASTING

When data of multiple types are operated upon, the result varies if the data types
are not correctly set. The compiler has its own rules in cases when an expression uses
data of multiple types. The following table shows how data types are converted by the
compiler.
Explicit Type Conversion : In this kind of type conversion, the resulting data types
are explicitly specified by the programmer.
Implicit Type Conversion : In this kind of type conversion, the resulting data types
are not specified and are chosen by the compiler. The compiler prefers not to lose any
part of the data value.
The following table shows the numeric data types and their allowed type-
conversions :
I – Implicit
Data type from Data type to
E – Explicit
short int/long/float/double I
int long/float/double I
short E
long int/float E
double I
float short/int E
long/double I
double short/int/long/float E

132
INTRODUCTION TO JAVA

MIXED TYPES IN AN EXPRESSION


If an expression is made up of different kinds of data types, then the compiler allots
the highest data type to the result and if the programmer has specified a particular data
type for the result then, that data type is alloted to the expression, irrespective of the fact
that which data type is higher or lower.
For example :
double g = 9.14, h = 0.0;
int n = 10, p = 0;
x = (g + n); // result will be of type double.
y = (int)g + n; // result will be of type int. g undergoes data loss in this case.
w = (int)(g + n); // result will be of type int. The sum at first gets converted to
// double and then the result gets converted to int.

SPECIAL CASE OF INTEGER DIVISION


When an integer is divided by another integer, the operation results in an integer
value. This causes an error. The way to solve this error is to convert any one of the
numerator or denominator to a decimal containing data type (float or double).
double res = 10/4;
* Error * the value that goes to variable res is 2 and not 2.5. It is because, even if
the data type of res is double, the division is carried out only on integers causing the
calculation to become an integer calculation.
double res = 10.0/4; OR double res = 10/4.0; OR double res = 10.0/4.0;
In all of these statements, variable res gets a value of 2.5 from the calculation. This
calculation does not convert the result to integer.

EXERCISE

1. Explain the following terms in brief :


(a) Object (b) Inheritance (c) Primitives (d) Type Casting
(e) Precedence (or Priority) (f) double
2. State True or False [correct the false statements] :
(a) Explicit Type Conversion is done by the compiler.
(b) A wrapper class contains a parameterized constructor through which its member
data can be assigned a value.
(c) Size of int is 8 bytes.

133
ISC COMPUTER SCIENCE – XI

(d) A Java BlueJ program can be executed only after compilation.


(e) Java is platform dependent.
3. Answer the following in brief :
(a) What are threads ? What are multithreads ?
(b) What is meant by “platform independence” ? How is it related to “portability” ?
(c) Why is Java considered to be secure ?
(d) What are the features of Object Oriented Programming ?
(e) What are the various operators used in Java ? Explain with example.
qq

134
6 JAVA STATEMENTS

l Input Statements

 Input using Buffered Reader Class

 Input using Scanner Class
l Conditions
 Relational operators
 Logical operators

 Conditional Statements

 Use of default in switch case
l Fall Through in switch case
l Comparison of if else and switch case
l Loops & their types
l Block of Code

 Nesting of blocks
l Scope of a variable in a block
l Types of Loops

 Infinite Loop

 Empty Loop

 Flag

 Accumulator

 Counter
l Condition in a Loop
l Loop in a Condition
l Nested Loops
l Jump Statements in a Loop

Statements in Java are syntactically complete instructions that perform a specific
task. A program is hence, made up of multiple statements that are arranged in a way
to fulfill a given aim. A statement can have multiple inner components where each
component can have sub-components or expressions.
ISC COMPUTER SCIENCE – XI

There are many statements in Java for various programming actions. Let us look
into various Java statements.

INPUT STATEMENTS
In this section, let us see one of the ways to take input for variables of various types
such as integer, double, char, string, boolean, etc.

Input Using Buffered Reader Class

Program Example :
import java.io.*;
public class SampleInput1
{
public void main() throws IOException
{
int n = 0;
double d = 0.0;
String s = “”;
char c = ‘’;
boolean b = false;
BufferedReader buf = new BufferedReader (new InputStreamReader (System.in));

//Statement 1
System.out.print(“ Enter an integer number : ”);
r = Integer.parseInt(buf.readLine());

System.out.print(“ Enter a double number : ”);


d = Double.parseDouble(buf.readLine());

System.out.print(“ Enter a string (in one line) : ”);


s = buf.readLine();

System.out.print(“ Enter a boolean value : ”);


b = Boolean.parseBoolean(buf.readLine());

System.out.print(“ Enter a character : ”);


c = (char) buf.read();

136
JAVA STATEMENTS

System.out.println(“ The integer is : ” + r + “ \n The double is : ” + d);


System.out.println(“ The string is : ” + s + “ \n The boolean is : ” + b);
System.out.println(“ The character is : ” + c );
}
}
Input : Output :
Enter the integer number : 26 The integer is : 26
Enter the double number : 24.8 The double is : 24.8
Enter the string (in one line) : All The Best The string is : All The Best
Enter the boolean value : true The boolean is : true
Enter the character : g The character is : g
Input Using Scanner Class

Program Example :
import java.util.*;
public class SampleInput2
{
private int x;
double f;
char vh;
String sh;

public void main()


{
Scanner sca = new Scanner(System.in);

System.out.print(“ Enter an integer number... ”);


x = sca.nextInt();
System.out.print(“ x = ” + x);

System.out.print(“ Enter a double number... ”);


f = sca.nextFloat();

137
ISC COMPUTER SCIENCE – XI

System.out.print(“ f = ” + f);
sh = sca.nextLine();
System.out.print(“\n sh = ” + sh); // to clear the buffer
System.out.print(“ Enter a character... ”);
vh = sca.nextLine().charAt(0);
System.out.print(“ vh = ” + vh);

System.out.print(“\n Enter a String... ”);


sh = sca.nextLine();
System.out.print(“ sh = ” + sh);

}
}
CONDITIONS

A condition is a statement that helps in decision making. It gives a result of either a


true or a false value. Conditions help to create programs that perform different course of
actions, when executed with changing set of values each time.

Relational Operators

Conditions are made by using Relational operators. There are six relational operators,
given below :

Relational
Use Example
Operator

> Greater than Q = 25 ; T = 55 ; ( Q > T ) is False

< Less than Q = 36 ; T = 82 ; ( Q < T ) is True

>= Greater than equal to Q = 16 ; T = 34 ; ( Q >= T ) is False

<= Less than equal to Q = 24 ; T = 24 ; ( Q <= T ) is True

== Comparison of equality Q = 25 ; T = 55 ; ( Q == T ) is False

!= Comparison of inequality Q = 25 ; T = 55 ; ( Q != T ) is True

138
JAVA STATEMENTS

Logical Operators

These operators are used to connect more than one condition to make a composite
condition. A composite condition is made up of multiple connected conditions.

Logical
Use Example
Operator
NOT P = 45;
!
True when the condition is False ( ! P == 45) is False
AND
P = 45; R = 70
&& True when all the conditions are
( P > 10 && R < 10 ) is False
True
OR
P = 45; R = 70
|| True when any one of the conditions
( P > 10 || R < 10 ) is True
is True

Conditional Statements

In Java, there are three conditional statements


(i) If..else
This statement can be applied in three ways :
1. if
2. if....else
3. if...elseif....elseif....else
(ii) switch....case
(iii) ternary operator
CONDITIONAL STATEMENT if....else
1. if
Syntax :
if(condition)
{
Block of statements (if condition satisfies)
}
If condition is true, then the Block of statements gets executed.
Program Example :
A program to find the smallest among three numbers.
Assign values to three integer variables. Print the smallest among the three.

139
ISC COMPUTER SCIENCE – XI

Program Idea
• Assign values to three integer variables.
• Using only if statement find the smallest number.
• Print the smallest number.
PROGRAM
import java.util,*;
public class SmallestNumber
{
void main()
{
int a = 21, b = 67, c = 92;
int sm = a;
if(b < sm)
{
sm = b;
}
System.out.print(“The smallest number is” + sm);
}
}
OUTPUT :
The smallest number is 21
2. if...else
Syntax
if(condition)
{
Block of statements 1 (if condition satisfies)
}
else
{
Block of statements 2 (if condition does not satisfy)
}
If condition is true, then Block of statements 1 gets executed otherwise Block of
statements 2 gets executed.
Program Example :
A program to check whether a number is even or odd.
Accept a number. Print the result.
Program Idea
• Accept a number.
• Verify the condition.
• Print whether it is even or odd.
140
JAVA STATEMENTS

PROGRAM
//if...else
import java.util.*;
public class OddEven
{
void main()
{
Scanner sc = new Scanner(System.in);
int n = 0;
System.out.print(“\n\nEnter a number :”);
n = sc.nextInt();
if(n % 2 == 0)
{
System.out.print(“\nThe number is even.”)
}
else
{
System.out.print(“\nThe number is odd.”);
}
}
}
OUTPUT :

Enter a number : 34
The number is even.
3. If … elseif…elseif…else
Syntax :
if(condition1)
{
Block of statements 1
}
else if(condition2)
{
Block of statements 2
}

141
ISC COMPUTER SCIENCE – XI

else if(condition3)
{
Block of statements 3
}
else
{
Final Block of statements
}
If condition1 is true, then Block of statements 1 gets executed otherwise if condition2
is true then Block of statements 2 gets executed and so on. If none of the conditions are
true then the last else part having Final Block of statements gets executed. The number
of conditions is optional.
Program Example :
In a fabric color box, colours were coded as :
2 – Blue 4 – Green 10 – Yellow 12 – Red
Enter the colour code in integer variable cd. Print the colour it represents. In case the
code did not match with the given choice, print “No such colour in the box”.
Program Idea
• Input the colour code, cd (int).
• Verify the condition.
• Print color name on the condition being true.
PROGRAM
//if .. else if .. else if .. else ladder
import java.util.*;

public class ProgColour


{
void main()
{
int cd = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n\n Enter the colour code : ”);
cd = sc.nextInt();

if(cd == 2)
{
System.out.print(“\n Code ” + cd + “ is for colour BLUE”);
}
else if(cd == 4)
{
System.out.print(“\n Code ” + cd + “ is for colour GREEN”);
}

142
JAVA STATEMENTS

else if(cd == 10)


{
System.out.print(“\n Code ” + cd + “ is for colour YELLOW”);
}
else if(cd == 12)
{
System.out.print(“\n Code ” + cd + “ is for colour RED”);
}
else
{
System.out.print(“\n No such colour in the box ”);
}
}
}
OUTPUT :
Enter the colour code: 8
No such colour in the box
Enter the colour code : 10
Code 10 is for colour YELLOW
CONDITIONAL STATEMENT switch ... case
This conditional statement is used in cases where the comparison is of equality only.
Syntax :
switch(expression)
{
case value1 : block of code 1
break;
case value2 : block of code 2
break;
case value3 : block of code 3
break;
default : final block of code
}
Use of default in Switch Case
In Switch Case statement, if none of the cases match, then default becomes active.
Default and the block present under it should appear at last. It is optional.
Program Example :
Input a day number and print the corresponding day of the week. Assume that a
week begins with Sunday with day number being 1. Valid day numbers are from 1 to 7.

143
ISC COMPUTER SCIENCE – XI

PROGRAM

//Weekday from day number, using Switch..Case construct


import java.util.*;

public class ProgDay


{
void main()
{
int dn = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n\n Enter the day number : ”);
dn = sc.nextInt();

switch(dn)
{
case 1 : System.out.print(“\n dn = ” + dn + “ is SUNDAY.”);
break;

case 2 : System.out.print(“\n dn = ” + dn + “ is MONDAY.”);


break;

case 3 : System.out.print(“\n dn = ” + dn + “ is TUESDAY.”);


break;

case 4 : System.out.print(“\n dn = ” + dn + “ is WEDNESDAY.”);


break;

case 5 : System.out.print(“\n dn = ” + dn + “ is THURSDAY.”);


break;

case 6 : System.out.print(“\n dn = ” + dn + “ is FRIDAY.”);


break;

case 7 : System.out.print(“\n dn = ” + dn + “ is SATURDAY.”);


break;

System.out.print(“\n dn = ” + dn + “ is an INVALID day number. ”);


default :
}
}
}
OUTPUT :
Enter the day number : 7
dn = 7 is SATURDAY.

Enter the day number : 0


dn = 0 is an INVALID day number.

144
JAVA STATEMENTS

FALL THROUGH IN SWITCH CASE


Break Statement is very important in Switch Case construct. It helps to terminate a
block and to bring the control out.
If break is not given then, all the statements that appear below the matching case,
get executed, till a break is reached. This leads to a logical error situation, which is called
Fall Through.
The below program shows the error of Fall Through. Thus, the break statements
are missing in it.
PROGRAM :

 /Weekday from day number...program showing LOGICAL ERROR SITUATION


/
of Fall Through
import java.util.*;
public class ProgDay
{
void main()
{
int dn = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n\n Enter the day number : ”);
dn = sc.nextInt();
switch(dn)
{
case 1 : System.out.print(“\n dn = ” + dn + “ is SUNDAY.”);

case 2 : System.out.print(“\n dn = ” + dn + “ is MONDAY.”);

case 3 : System.out.print(“\n dn = ” + dn + “ is TUESDAY.”);

case 4 : System.out.print(“\n dn = ” + dn + “ is WEDNESDAY.”);

case 5 : System.out.print(“\n dn = ” + dn + “ is THURSDAY.”);

case 6 : System.out.print(“\n dn = ” + dn + “ is FRIDAY.”);

case 7 : System.out.print(“\n dn = ” + dn + “ is SATURDAY.”);

default : System.out.print(“\n dn = ” + dn + “ is an INVALID day number. ”);


}
}
}
OUTPUT :
Enter the day number : 5
dn = 5 is THURSDAY.

145
ISC COMPUTER SCIENCE – XI

dn = 5 is FRIDAY.
dn = 5 is SATURDAY.
dn = 5 is an INVALID day number.

COMPARISON OF IF…ELSE AND SWITCH...CASE


Both if else and switch case are conditional statements, but they have some
differences.
S. No. if else switch case
1 All relational operators (greater Only comparison of equality takes
than, less than, etc.) can be used place.
and interpreted.
2 Two variables can be compared. Only a variable and a constant can be
compared.
3 Multiple conditions can be Multiple conditions are not possible to
connected by using logical connect together.
operators.
4 All data types are allowed. Variables of only type integer (byte,
short, int, long) and char can be used.
5 Preferred in cases where there Preferred in cases where there are
are conditions other than equality simple conditions of equality.
comparison.
6 Gives more variety and is better for Gives less variety and is better for
bigger and complicated situations. smaller and simpler situations.
7 No use of break. Fall through not Break is a must. Fall through happens
possible but proper brackets must in absence of break statement.
be there.

CONDITIONAL STATEMENT ternary operator


Syntax :
(condition) ? true zone : false zone ;

Ternary operator is used in cases where the condition is small.


Program Example :
Input the length of two ropes in n1 and n2. Store the length of the longer rope in
variable ln and print it. Use ternary operator.
PROGRAM
import java.util.*;
public class ProgLength
{

146
JAVA STATEMENTS

void main()
{
int n1 = 0, n2 = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n Enter length of rope 1 : ”);
n1 = sc.nextInt();
System.out.print(“\n Enter length of rope 2 : ”);
n2 = sc.nextInt();
ln = (n1 > n2 ) ? n1 : n2;
System.out.print(“\n Length of longer rope is : ” + ln);
}
}

OUTPUT :
Enter length of rope 1 : 47
Enter length of rope 2 : 82
Length of longer rope is : 82

LOOPS AND THEIR TYPES


A loop is a programming concept in which a group of statements are executed
repeatedly as long as the specified condition is valid.
There are 3 types of loops in Java program :
(i) for loop - used when the number of iterations are known, entry controlled.
(ii) while loop – used when the number of iterations are not known, entry controlled.
(iii) do-while – used when the number of iterations are not known, exit controlled.
Syntax of FOR loop Syntax of WHILE loop Syntax of DO-WHILE loop
for(init; test; inc) while(test) do
{ { {
Block of statements Block of statements Block of statements
} } }while(test);

Program code example of For Loop :


for(p = 1; p <= 15; p = p + 1)
{
System.out.print(+ p +“ ”);
}

147
ISC COMPUTER SCIENCE – XI

OUTPUT :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Program code example of While Loop (to generate the same output as shown above) :
int p = 1;
while(p <= 15)
{
System.out.print(p +“ ”);
p++;
}
Program code example of Do While Loop (to generate the same output as shown
above) :
int p = 1;
do
{
System.out.print(p +“ ”);
p++;
} while(p <= 15);

BLOCK OF CODE
A group of program statements that are enclosed within a pair of { } is called a block
of code.
In the above examples, block of While Loop contains 2 statements.
Nesting of Blocks
When one block is present inside another block, nesting of blocks is said to occur.
Program code example :
for(p = 1; p <= 15; p = p + 1)
{
if(p % 2 == 0)
{
System.out.print(“\n Even Number” + p);
}
}

Here, the outer block is of the loop, and the inner block is of the condition.

148
JAVA STATEMENTS

SCOPE OF A VARIABLE IN A BLOCK


• If a variable is declared inside a block then its existence is limited to the block.
• T
 wo variables of the same name can exist if they are declared in different blocks,
the variable declared in the inner block gets priority.

Program code example on scope of a variable in a block :


int p = 1;
while(p <= 10)
{
int c = 0;
if(p % 2 == 0)
{
c = 1;
}
System.out.print(“\n Inside while block c = ” + c);
}
System.out.print(“\n Outside while block c = ” + c); //error, c not found

Program code example on scope of a variable in a block :

void sample2()
{
for(int k = 1; k <= 5; k++)
{
System.out.println(“Inside 1st block k =” +k);

}
for(int k = 11; k <= 15; k++)

System.out.println(“Inside 2nd block k = ” +k);

System.out.print(“\nOutside k = ” + k); //error, k not found

Program code example on scope of a variable in a block

class Example

149
ISC COMPUTER SCIENCE – XI

int m;
Example()
{
m = 15;
}
void method1()
{
System.out.println(“Inside method1, m = ” + m);
}
void method2()
{
int m = 109;
System.out.println(“Inside method2 m = ” + m);
}
}
In the above program, a call to method1() will produce the following :
OUTPUT :
Inside method1, m = 15
and a call to method2() will produce the following :
OUTPUT :
Inside method2, m = 109

TYPES OF LOOPS

INFINITE LOOP

It is in general an error situation where a loop goes on and on for infinite number
of times.
Program code example :
k = 1;
while(k <= 20)
{
System.out.print(“\n Value of k = ” +k);
}
Note :
l Shown above is a common error found in use of while loop, where the value of the
counter has not been updated. Such kind of error results in an infinite loop.

150
JAVA STATEMENTS

OUTPUT :
Error situation, as k does not change making the loop infinite.
EMPTY LOOP
It is a loop that does not have any task in it. But an empty loop is not an infinite
loop. One application area of empty loop is – “to wait or to delay”.
Program code example :
for(j = 1; j <= 1000; j++);
Note : The terminator at the end shows that the loop has no task. Thus, resulting in
an empty loop.
OUTPUT :
j = 1000 (here), if j is initialized in the statement then j will not exist outside.

FLAG

A flag is a kind of variable that is used as an indicator, assuming the value true/
false. For example, set a flag to true if in a group of students, a single student has scored
full marks.
Program Code Example :
Program to verify whether a number, say n, has any factor between 2 and its half.
[ application of a flag ]
Program Idea
• Input a number (say n).
• Run a loop from 2 to its half (n/2).
• Test values of f to be a factor of n. If a factor is found then set the flag to true and stop
the loop.
PROGRAM
//Verifying if the number has any factor between 2 to n/2
//input n
boolean isf = false;
for(f = 2; f <= n/2; f++)
{
if(n % f == 0)
{
isf = true;
break; //refer to jump statements at the end
}
}

151
ISC COMPUTER SCIENCE – XI

if(isf == true)
{
System.out.print(n + “ has factor/s between 2 and ” + n/2);
}
else
{
System.out.print(n + “ has NO factor between 2 and ” + n/2);
}

OUTPUT :
(let, n = 12)
12 has factor/s between 2 and 6

ACCUMULATOR
An accumulator is a kind of variable that is used to store the sum or product of a
series by continuously overwriting its own value.
Program Code Example :
Program to find the sum of all the numbers from 1 to 20.
Program idea
• Assign accumulator s = 0.
• Run a loop from 1 to 20 (assume f as loop counter).
• Modify s by (s + f) each time (s = s + f).
• Print s outside the loop.
PROGRAM
// Find the sum of all the numbers from 1 to 20
int s = 0;
for(f = 1; f <= 5; f++)
{
s = s + f;
}
System.out.print(“ Sum = ” + s);
OUTPUT :
Sum = 15

152
JAVA STATEMENTS

COUNTER
A counter is a kind of variable that counts. In general, counting takes place in a
condition. For example, count the number of children present in the group. A counter is
a special type of accumulator whose value gets modified by 1.

Program Code Example :


Program to count the factors of a variable, say n.
[application of a counter]
Program Idea

• Input a number (say n).


• Run a loop from 1 to itself (using say, f).
• Test each value of f to be a factor of n ( condition inside the loop ), if so then
increase the counter.
PROGRAM
//Count the factors of a number – Counting as per the condition inside the loop,
using a counter
//input n
int c = 0;
for(f = 1; f <= n; f++)
{
if(n % f == 0)
{
c = c + 1; // increasing counter on condition
}
}
System.out.print(“\n Number of factors of ” + n + “ = ” + c);
OUTPUT :
(let, n = 6)
Number of factors of 6 = 4

CONDITION IN A LOOP
When a condition has to be applied again and again on changing set of variables,
we use a condition inside a loop. This situation is called repetitive decision and is mainly
used for counting.

153
ISC COMPUTER SCIENCE – XI

Program Code Example :


Program to print the factors of a variable, say n.
Program Idea
• Input a number (say n).
• Run a loop from 1 to itself (using say, f).
• Test each value of f to be a factor of n (condition inside the loop), if so then print
it.
PROGRAM
//Print the factors of a number - Condition in a loop
//input n
for(f = 1; f <= n; f++)
{
if(n % f == 0)
{
System.out.print(“\n ” + f + “ is a factor of ” + n);
}
}
OUTPUT :
(let, n = 6)
1 is a factor of 6
2 is a factor of 6
3 is a factor of 6
6 is a factor of 6

LOOP IN A CONDITION
When a repetitive task takes place upon a condition being true/false.
For example, print the numbers from a to b, only if a < b.
//input a, b
if(a < b)
{
System.out.println(“\n The numbers from ” + a + “ to ” + b + “ are :: \n”);
for(int j = a; j <= b; j++)
{
System.out.print(“ ” + j);
}
}

154
JAVA STATEMENTS

else
{
System.out.println(“\n Sorry, the limits are not valid.”);

}
OUTPUT :
(let, a = 6, b = 10)
The numbers from 6 to 10 are ::
6 7 8 9 10

NESTED LOOPS
When a loop gets executed inside another loop. In such cases the inner loop
completes its iterations and then the outer loop is incremented. Shown below are
some program codes with outputs.
Program Code Example :
Program to print the numbers from (1 to 5) 5 times and some other patterns
Program Idea
• Run a loop from 1 to 5 (using say, r).
• Inside the loop run another loop from 1 to 5 (using say, c).
• Print the value of c.
PROGRAM CODE 1 : PROGRAM CODE 2 :

for(r = 1; r <= n; r++) for(r = n; r >= 1; r– –)
{ {
for(c = 1; c <= n; c++) for(c = 1; c <= r; c++)
{ {
System.out.print(“ ” + c); System.out.print(“ ” + c);
} }
System.out.println(); System.out.print(“\n”);
} }
OUTPUT – CODE 1 : OUTPUT – CODE 2 :
1 2 3 4 5 1 2 3 4 5
1 2 3 4 5 1 2 3 4
1 2 3 4 5 1 2 3
1 2 3 4 5 1 2
1 2 3 4 5 1

155
ISC COMPUTER SCIENCE – XI

PROGRAM CODE 3 : PROGRAM CODE 4 :


for(r = 1; r <= n; r++)
for(r = 1; r <= n; r++) {
{ for(c = 1; c <= r – 1; c++)
for(c = 1; c <= r – 1; c++) {
{ System.out.print(“ ”);
System.out.print(“ ”); }
} for(c = r; c <= n; c++)
for(c = r; c <= n; c++) {
{ System.out.print(“ * ”);
System.out.print(“ ” + c); }
} System.out.print(“\n”);
System.out.print(“\n”); }
}
OUTPUT CODE 3 : OUTPUT CODE 4 :
1 2 3 4 5 * * * * *
2 3 4 5 * * * *
3 4 5 * * *
4 5 * *
5 *

JUMP STATEMENTS IN A LOOP

break : I t causes a loop to terminate its iterations. Whenever a break is encountered,


the control comes out of the loop and resumes at the next statement following the loop.
Program code example on application of break in a for loop :

int j = 0;

for( j = 10; j <= 25; j++)

if(j == 15)

break;

System.out.print(“\n Value of j = ”+ j);

156
JAVA STATEMENTS

System.out.print(“\n OUT OF THE LOOP Value of j = ” + j);


OUTPUT :

Value of j = 10

Value of j = 11

Value of j = 12

Value of j = 13

Value of j = 14

OUT OF THE LOOP Value of J = 15


Note :
l If break is used without any condition, the loop loses its effect. Observe the output
of the given code.

int j = 0;

for( j = 10; j <= 25; j++)

break;

System.out.print(“\n Value of j = ” + j);

System.out.print(“\n OUT OF THE LOOP Value of j = ”+ j);

OUTPUT :

Value of J remains 0. Hence, the loop does not make any sense in this code.

Continue : It makes the loop-counter go to its next value by skipping the rest of the
statements for that particular iteration.

Program code example :

// application of continue in a for loop

int j = 0;

for(j = 10; j <= 25; j++)

if(j == 15)

157
ISC COMPUTER SCIENCE – XI

continue;
}
System.out.print(“\n Value of j = ” + j);
}
System.out.print(“\n OUT OF THE LOOP Value of j = ” + j);

OUTPUT :
Value of j from 10 to 14 and from 16 to 25 will get printed.

EXERCISE

1. State True or False [correct the false statements :


(a) If present value of a = 6 then a == 9 will change the value of a to 9.
(b) Symbol ! stands for NOT.
(c) Ternary operator is used to define a loop.
(d) If a variable is declared inside a block then its existence is limited to that block.
(e) Fall through can occur in a do–while loop.

2. Answer the following :


(a) Write three differences between if else and switch case statements.
(b) What is Fall through situation ?
(c) How does ternary operator work ?
(d) What are the different types of loops ? Explain each type briefly.
(e) What is the scope of a variable ?

3. Write the output of the following codes :


(a) int j = 0, g = 0, result = 1;
for(j = 3; j <= 5; j++)
{
result = j;
for(g = 5; g >= 3; g – –)
{
result = result * g;
}
System.out.print(“\n Result is ” + result);
}
System.out.print(“\n Out Of The Loop Value of (j, g) are ” + j + “ , ” + g);

158
JAVA STATEMENTS

(b) int cnt = 10; (f) double dbl = 10.5;


while(cnt >= 1) for(double d = 1; d <= dbl; d += 0.5 )
{ {
System.out.print(cnt– – + “ ”); if(d % 2.5 == 0)
cnt –= 2; {
} System.out.print(d + “\t”);
(c) int cnt = 10; }
for(int j = 1; j <= cnt; j++) }
{ (g) double db2 = 123.45;
System.out.print(j + “ ”); int p = 0;
if(j % 3 == 0) double d1 = db2;
j++; while(db2 – (int)db2 > 0)
} {
(d) int cnt = 10; db2 = db2 * 10;
for(int j = 1, k = 1; j <= cnt; j++, k++)
p – –;
{
System.out.print(k + “ ”); System.out.println(“ ## ” + db2);
if(j % 2 == 0)
}
{
k = j + 1; System.out.println(“\n Finally :” + db1

System.out.println(); + “ is\t ”+ db2 + “ × 10^”


} + p);
}
(h) int b = 56478;
(e) for(int j = 1; j <= cnt; j++)
{ int b2 = b;
System.out.print(j + “\t”); int r = 0;
if(k == j && j != cnt)
while(b2 != 0)
{
j = 0; {
k++;
System.out.println(b2 + “\t” + r);
System.out.println();
} r = r * 10 + (b2 % 10);
} b2 = b2/10;

}
qq

159
EXCEPTION
7 HANDLING

l Errors and Exceptions



v Types of Errors
l Compile time Errors (Syntax Error)
l Logical Error
l Runtime Error
l Comparison of Compile time, Logical and Runtime Errors
l Handling Exceptions in Java
l Try Catch Block

v Try Block

v Catch Block

v The Exception Object

v Multiple Catch Blocks
l Keyword finally
l Keywords throws and throw

v Throws

v Throw

ERRORS AND EXCEPTIONS


Error is a common term that indicates that something is wrong somewhere. In
Java, errors are of a serious concern and therefore are handled with much care. They are
classified into Errors and Exceptions.
An exception is an erroneous situation in a program which causes the program to
end abruptly. A program is called robust if it does not crash during execution.
Types of Errors
1. Compile Time Errors : These are listed by the compiler during compilation,
caused by improper way of program writing. These are also known as syntax errors. For
example : wrong spelling, missing brackets, missing file reference etc.
2. Logical Errors : These are caused by the implementation of wrong logic in the
program. These are not listed by the compiler. For example : use of + symbol in place of
*, etc.
EXCEPTION HANDLING

3. Runtime Errors [Exceptions] : These are unpredicted errors that show up during
program execution. For example : stack overflow, invalid input, etc.
In Java programming, importance is given to a robust error-free program. Exception
handling therefore, exists to handle those situations that may cause a program to crash.
In this chapter, we will look into errors of each type and their causes.

COMPILE TIME ERRORS (SYNTAX ERRORS)


These are caused by an improper way of writing a program and so, these are the
most common errors with the beginners. The good thing about syntax errors is that the
compiler can detect them. The compiler also generates a message about the error which
can be taken as a clue to rectify it.
Shown below are some of the most common syntax errors.
u W
 rong spelling of keywords : Note that Java is case sensitive. One has to be very
careful while writing long class names where both upper and lower case characters
are used.
For example : InputStreamReader
u Missing semicolon : Statement terminator indicated by a ; (semicolon) must be
present to mark the end of any command. Whereas, conditions and loops should
not be terminated as then they get disconnected from their block.
u Missing or mismatching brackets () or {} : () brackets are used in calculations.
Correct spacing saves this error.
{} brackets are used for making blocks. Indentation helps to make the blocks
distinct and identifiable. [Indentation is the process of changing the vertical
margin of each block.]
u Data type mismatch : Care must be taken towards verifying the data types of the
variables, when more than one are involved. The compiler helps out with implicit
data type conversions and the programmer should perform explicit data type
conversions as per the requirement.
u Unclosed character or string : Caused when the compiler encounters any
character ( ‘ ’ ) or string ( “ ” ) not closed. Characters comprise of single and strings
comprise of multiple characters.
u Forgetting to import a package : If one forgets to put the required import
statement at the beginning of a program, then the compiler will respond with a
message such as :
“Class ‘…’ not found in type declaration”
Note : that java.lang is imported automatically and, hence, does not need an
import statement.
u Method prototype and method call : A method prototype should be given a
proper return type, acceptable method name, parameter list along with their data
types.

161
ISC COMPUTER SCIENCE – XI

During method call, actual parameters should be sent without the data types, with
the number and type matching.
u Accessing a variable out of its scope : A variable is bounded within its block.
Variables declared inside one method are not accessible in another method.
u  rray index out of bounds : In case of arrays, the cell numbers begin with 0. In
A
case of string handling also, character positions are numbered from 0.

LOGICAL ERRORS
These are caused due to wrong interpretation of the logic. They are more difficult
to be identified as the compiler does not list them. The programmer has to apply careful
strategies to debug a program from logical errors.
Hints to identify logical errors :
u Counter initialization.
u Use of break/continue in a loop upon condition.
u Reinitializing variables inside a nested loop (depending on the program solution).
u Fall through in switch case construct.
u Loop ranges, condition validity.
u I n case of while and do..while loops, modification of the loop counter or
terminating criteria should be given more attention.
u I t has been observed that logical errors can be identified with intermediate
outputs of the variables that are used in the process.

RUNTIME ERRORS
These are not caused by the programmer’s fault, but due to external reasons. Java
provides different ways to catch these errors by a series of exception handling statements.
Some logical errors cause runtime errors. If runtime errors are not handled carefully they
can crash the program.
Some of the main causes of Exceptions are :
u Stack overflow during some huge mathematical calculations.
[in case the memory is less].
u Erroneous input [such as inputting char in place of int].
u Calculation causing division by 0.
u Resource unavailable [some external links/files missing].
u  oo many processes loaded into the system, causing shortage in memory
T
availability.

162
EXCEPTION HANDLING

COMPARISON OF COMPILE TIME, LOGICAL


AND RUNTIME ERRORS

Compile time Error Logical Error Runtime Error


It can be detected by the It cannot be detected by the It cannot be detected by the
compiler during compiler during compiler during
compilation. compilation. compilation.
It is easy to detect. It is difficult to detect. It is difficult to detect.
It does not allow the It allows the program to get It allows the program to get
program to execute. executed. executed
[it is a special type of
Logical error].
It does not cause the It can cause the program to It does cause the program to
propgram to crash. crash. crash.

HANDLING EXCEPTIONS IN JAVA


Java provides a class called the Exception class that comprises of the various
error handling subclasses and methods like, the try catch block, the keywords – throw,
throws, finally, etc.
In a method, an exception can be identified and treated with the help of a try catch
block. The probable error causing code is enclosed in a try catch block. In case any error
is generated, then it is caught by the catch block.

TRY CATCH BLOCK

Try block
The try block contains a block of program statements within which an exception
might occur. A try block is always followed by a catch block, which handles the exception
that occurs in the associated try block. A try block must be followed by a catch block or
finally block or both.
Syntax of try block :
try
{
//statements that may cause an exception
}
Catch Block
A catch block must be associated with a try block. The corresponding catch block
executes if an exception of a particular type occurs within the try block.

163
ISC COMPUTER SCIENCE – XI

Syntax of try catch in java :


try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}

The Exception Object


In the try catch block, an exception object is created for the exception that occurs.
This object can be accessed inside the catch block.
Program Example :
voidmain()
{
try
{
int DR[] = new int[5];
DR[8] = 9; // accessing cell number 8 in an array of size 5
}
catch(Exception e) // e is the Exception object
{
System.out.println(“Exception :: ” + e);
}
}
OUTPUT :
Exception :: java.lang.ArrayIndexOutOfBoundsException : 8

Multiple Catch Blocks


In case of multiple catch blocks, the control searches for the matching exception, and
that specific catch block gets executed, other catch blocks remain inactive.
In the following example, in spite of multiple catch blocks, only the specific catch
block gets executed and other catch blocks remain inactive.

164
EXCEPTION HANDLING

Program Example :
void main()
{
try
{
String S = “Rain”;
char p = S.charAt(6);
}
catch(NumberFormatException e)
{
System.out.println(“Exception 1. ” + e);
}
catch(Arithmetic Exception e)
{
System.out.println(“Exception 2. ” + e);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(“Exception 3. ”+ e);
}
catch(RuntimeException e)
{
System.out.println(“Exception 4. ” +e);
}
}
OUTPUT :
Exception 3. java.lang.StringIndexOutOfBoundsException : String index out of
range : 6
Flow of try catch block :
1. If an exception occurs in the try block then the control of execution is passed to the
catch block from the try block. The exception is caught up by the corresponding
catch block.
2. A single try block can have multiple catch statements associated with it, but each
catch block can be defined for only one exception class.

165
ISC COMPUTER SCIENCE – XI

3. The catch blocks should be written from specific to generic order of exceptions.
If generic exception is written above specific exceptions then the compiler will
mark the specific exceptions as “ exception … has already been caught”.
Observe the following example :
Program Example :
void main()
{
try
{
int p = 7, q = 0;
double r = p/q;
}
catch(NumberFormatException e) //specific exception
{
System.out.println(“Exception 1.” + e);
}
catch(Exception e) //generic exception
{
System.out.println(“Exception 2. ” + e);
}
}
OUTPUT :
Exception 2. java.lang.ArithmeticException: / by zero
Program Example:
void main()
{
try
{
int p = 7, q = 0;
double r = p/q;
}
catch(Exception e) //generic exception
{
System.out.println(“Exception 2.” + e);
}
catch(NumberFormatException e) //specific exception ( below generic exception )
{

166
EXCEPTION HANDLING

System.out.println(“Exception 1.” + e);


}
}

Note : The above code gives compile time error of


“exception java.lang.NumberFormatException has already been caught”

Program Example :
class TryExample1
{
void FnErrorTest(int n1, int n2)
{
try
{
System.out.println(“N1 = ” +n1);
double d = n1/n2;
System.out.println(“End of Try Block”);
}
catch(Exception e)
{
System.out.println(“ERROR :: ”);
System.out.println(e);
}
System.out.println(“Program continues out of Try Catch Block”);
System.out.println(“N2 = ” +n2);
}
}
OUTPUT :
N1 = 84
ERROR ::
java.lang.ArithmeticException:/by zero
Program continues out of Try Catch block
N2 = 0
Program Example :
class TryExample2
{

167
ISC COMPUTER SCIENCE – XI

void FnErrorTest(int k)
{
int A[] = new int[4];
try
{
System.out.println(“K= ” +k );
System.out.println(“ A[0] = ” +A[0]);
System.out.println(“A[K]= ” +A[k]);
}
catch(Exception e)
{
System.out.println(“ERROR :: ”);
System.out.println(e);
}
System.out.println(“Program continues, K again = ” +k);
}
}
OUTPUT :
K=6
A[0] = 0
ERROR ::
java.lang.ArrayIndexOutOfBoundException:6
Program Continues, K again = 6

Program Example :
import java.util.*;
class TryExample3
{
void FnErrorTest()
{
ink k = 0;
Scanner sc = new Scanner(System.in);
try
{
System.out.print(“ Enter value of K :”);
k = sc.nextInt();

168
EXCEPTION HANDLING

System.out.println(“ K = ” +k);
}
catch(Exception e)
{
System.out.println(“ERROR :: ”);
System.out.println(e);
}
System.out.println(“Program Continues, K again = ” +k);
}
}
OUTPUT :
Enter value of K : 9
ERROR ::
java.util.InputMismatchException
Program Continues, K again = 0

Program Example :
import java.util.*;
class TryExample4
{
void FnErrorTest(int a, int b)
{
int r = 0;
try
{
r = a % b;
System.out.printIn(“ R = ” +r);
}
catch(Exception e)
{
System.out.println(“ERROR :: ”);
System.out.println(e);
}
System.out.println(“Program Continues, A = ”+a + “ B = ” +b + “ R = ” +r);
}
}
OUTPUT :
ERROR ::
java.lang.ArithmeticException:/by zero
Program Continues, A = 7 B = 0 R = 0

169
ISC COMPUTER SCIENCE – XI

KEYWORD FINALLY
The keyword “finally” is used in a try catch block which becomes active after all the try
blocks have been executed. The finally block is optional. It gets executed irrespective of whether
any exception was thrown or not. The main use of finally block is to do cleanup tasks, since it
gets executed in all cases.
Program Example :
void main()
{
try
{
int DR[] = new int[5];
DR[8] = 63; // accessing cell number 8 in an array of size 5
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Exception 1. ” + e);
}
catch(RuntimeException e)
{
System.out.println(“Exception 2. ” + e);
}
catch(Exception e)
{
System.out.println(“Exception 3. ” + e);
}
finally
{
System.out.println(“Finally Block ” );
}
}
OUTPUT :
Exception 1. java.lang.ArrayIndexOutOfBoundsException: 8
Finally Block

KEYWORDS THROWS AND THROW


Throws
The keyword “throws” is used by the compiler to generate a predefined error. For
example, an IOException (Input Output Exception) is generated when an alphabet is inputted
in a variable of integer type.
170
EXCEPTION HANDLING

“throws” keyword is written in the method prototype. The keyword “throws” indicates
the compiler to just keep the error aside.
The syntax is :
void fnMethod(int a, int b) throws Exception
{
//program code
}
Program Example :
import java.io.*;
public class cllnput Data
{
public void fnlnput() throws Exception
{
int n = 0;
Buffered Reader but = new bufferedReader(new InputStreamReader(System.in));
System.out.print(“\n Enter the integer number :”);
n = Integer.parseInt(but.readLine());
}
}
OUTPUT :
Enter the integer number : n [Error terminates program but no
separate error message]
Throw
There is another keyword “throw” that allows the programmer to create a new error
situation that is specific to the program problem. For example, in a banking program, amount
less than a certain value in an account might be termed as MinimumBalance.
Program Example :
In a bank, the minimum balance should be 1000 for any transaction permission. Create an
exception to catch the error of minimum balance.
The classes MinimumBalance and BalanceProcessing are used to create the exception. The
class BalanceVerify uses MinimumBalance as an exception.

import java.io.*;
public class MinimumBalance extends Exception
{
private int balance;
public MinimumBalance(int balance)
{
this.balance = balance;
}

171
ISC COMPUTER SCIENCE – XI

public double getBalance()


{
return balance;
}
}

import java.io.*;
public class BalanceProcessing
{
private int actNum, balance;
BalanceProcessing(int balance)
{
this.balance = balance;
}
public void verify() throws MinimumBalance
{
if(balance >= 1000)
{
System.out.println(“\n You can go ahead with your transaction.”);
}
else
{
int needs = 1000 – balance;
throw new MinimumBalance(needs);
}
}
}
public class BalanceVerify
{
public static void main()
{
BalanceProcessing bp1 = new BalanceProcessing(5000); // first marks = 50
BalanceProcessing bp2 = new BalanceProcessing(600); // first marks = 50
BalanceProcessing bp3 = new BalanceProcessing(1000); // first marks = 50
try
{
System.out.println(“\n Customer 1 : Balance Amount ... ”);
bp1.verify();

172
EXCEPTION HANDLING

System.out.println(“\n Customer 2 : Balance Amount ... ”);


bp2.verify();
System.out.println(“\n Customer 3 : Balance Amount ... ”);
bp3.verify();
}
catch(MinimumBalance e)
{
System.out.println(“Sorry, balance short by : ” + e.getBalance());
}
}
}
OUTPUT : (main() of BalanceVerify class)
Customer 1 : Balance Amount ...
You can go ahead with your transaction.
Customer 2 : Balance Amount ...
Sorry, balance short by : 400.0

EXERCISE

1. Answer the following :


(a) What causes syntax errors ?
(b) Why do you think the compiler cannot identify logical errors ?
(c) Name three reasons for the occurrence of runtime errors.
(d) Name two keywords that help to identify runtime error.
(e) What is indentation ? How does it help ?
2. State the difference between :
(a) Runtime error and logical error.
(b) Keywords throw and throws.

3. In the following code snippets, identify if there is any error or not :


(a) double d1 = 19.2, d2 = 42.5;
int t1 = d1;
System.out.print(“ d1 = ” +d1+ “ \t and t1 = ” +t1);
(b) boolean pm = true;
int n = 77;
for(int j = 2; j <= n/2; j++)
{

173
ISC COMPUTER SCIENCE – XI

if(n % j == 0)
pm = false;
break;
}
(c) for(int j = 1; j <= n; j++)
{
int c = 0;
if(n % j == 0)
c++;
}
(d) System.out.print(“ Enter a char... ”);
vh = sca.next Line().charAt(0);
System.out.print(“ vh = ” +vh);
(e) //input a, b
d = a/b;
r = a%b;
System.out.print(“ Quotient = ” +d+ “Remainder = ” +r );

qq

174
METHODS (FUNCTIONS)

8 METHODS
(FUNCTIONS)

l Method or Function

 Function Prototype
 Super and Sub Function
 Function and Class
 Importance of main() method
 Nesting of Functions
l Functions and Arrays
l Objects as arguments
l Keyword ‘this’
l Pure and Impure functions
l Call by value (CbyV) and call by Reference (CbyR)
l Keyword ‘static’
l Constructors
 Default Constructor
 Parameterized constructor
l Packages

METHOD OR FUNCTION
A method or a function is a named unit that has an aim and contains a single/
multiple line code.
Methods make a program easy to understand. They help in code reusability. They
also implement code abstraction by separating complex code.
Function Prototype
It is the way of defining a function. The prototype is the first line of the function. The
following statement shows the prototype of a function :
Return_type Function_name (Argument List)
Return_type : A function can return only one value, which may be a primitive of
any type or an object. No return is denoted by void.

175
ISC COMPUTER SCIENCE – XI

Function_name : Any identifier can be used to name a function. It should suggest


the work it is doing. A function is addressed by its name followed
with (). For e.g., Add().
Argument/ : A function can accept one or more arguments, which can be either
Parameter List a primitive or an object.
Super and Sub Function
In a function call, the calling function is called the Super function and the called
function is called the Sub function. We can say that a SUPER function calls a SUB function.
Function and Class
A class may contain one or multiple functions, called member functions. Program
code can be written only in a function of a class.
Local Data of A Function
Data that are declared in a function are called local data of that function. Scope of
these local data is within that particular function.
Member Data of A Class
Data which are declared in a class, outside all the member functions, are called
member data of that class. Scope of this member data is within that particular class. They
can be accessed by all the members of that class. Any function can change a member
data. The effect of the change can be seen from any other function of the class.
Importance of main() Method
Every program should contain a controlling method called main(). Conventionally
program execution begins from the main() method.
Actual and Formal Parameters
The parameters that are used in the Super function, while calling the Sub function,
are called Actual parameters.
The parameters that are used in the Sub function are called Formal parameters.
Program Examples :
1. Print the 1st n natural numbers. Input ‘n’ in main(), print in the function. Use a
function whose prototype is given as - void fnNaturalNum(int k).
Algorithm
• The input of n is taken in main().
• main() calls the sub function fnNaturalNum(int k).
• main() terminates.
In the sub function fnNaturalNum(int k), a loop is run from 1 to k, using say j.
• All the values of j are printed inside the loop.
• The sub function terminates.

176
METHODS (FUNCTIONS)

import java.util.*;
public class ProgA
{
void fnNaturalNum(int k)// k is a formal parameter
{
System.out.println(“\n The natural numbers from 1 to” + k + “ are ...”);
for(int j = 1; j <= k; j++)
{
System.out.print(“ ...” + j); //variable j travels from 1 to k
}
}
public void main()
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter n : ”);
n = sc.nextInt();
fnNaturalNum(n); //n is an actual parameter
}
}
OUTPUT :
The natural numbers from 1 to 5 are
... 1 ... 2 … 3 … 4 … 5
2. Write a function that returns a that returns a Boolean value depending on
whether an argument is Prime or not. Assume the name of the function to be fnIsPrime()
that takes an argument nf from main(). The function returns a boolean result back to
main().
Program Idea
u The program execution begins from function main(), which is the controlling
function.
u The function is expected to return a boolean result of either true or false depending
on whether the argument sent to it is prime or not.
u The function does the work by counting the total number of factors and then
comparing that by 2. We know that a number is called Prime if it has exactly 2
factors.
u In the main(), the function’s return is stored in a boolean type variable. The
output takes place from main().

177
ISC COMPUTER SCIENCE – XI

//To verify Prime status


import java.io.*;
public class ProgE
{
boolean fnIsPrime(int nf)
{
boolean isp = false;
int f = 0, cf = 0;
for(f = 1; f <= nf; f++)
{
if(nf % f == 0)
{
cf = cf + 1;
}
}
if(cf == 2) //logically cf cannot be < 2 for any number
{
isp = true;
}
return isp;
}
public void main() throws IOException
{
int nm = 0; boolean prst = true;
BufferedReader buf = new BufferedReader
(new InputStreamReader (System.in));
System.out.print(“\n Enter a number (in main() variable nm) : ”);
nm = Integer.parseInt(buf.readLine());
prst = fnIsPrime(nm);
System.out.print(“\n The Prime Status of ” + nm + “ is ” + prst);
}
}
OUTPUT :
Enter a number (in main() variable nm) : 23
The Prime Status of 23 is true

178
METHODS (FUNCTIONS)

Nesting of Functions
This concept is implemented when one function makes a call to another function.
The following example shows nesting of functions, where fnTotalFactors() is the
sub-function and fnIsPrime() is the super-function. Also note that fnIsPrime() is the sub-
function of main().
import java.io.*;
public class ProgK
{
int fnTotalFactors(int nt)
{
int cf = 0;
for(int f = 1; f <= nt; f++)
{
if(nt % f == 0)
{
cf = cf + 1;
}
}
return cf;
}
boolean fnIsPrime(int nf)
{
boolean isp = false;
int tf = fnTotalFactors(nf); //fn calling another fn
if(tf == 2)
isp = true;
return isp;
}
public void main()
{
int v = 29;
boolean prst = fnIsPrime(v);
if(prst == true)
{

179
ISC COMPUTER SCIENCE – XI

System.out.print(“ Value ” + v + “ is Prime”);


}
else
{
System.out.print(“ Value ” + v + “ is NOT Prime”);
}
}
}
OUTPUT :
Value 29 is Prime

FUNCTIONS AND ARRAYS


The syntax of a function to accept an array is as parameter is as follows :
void fnArray1(int ar[], int n)

The syntax of a function to return an array is as follows :


int[ ] fnArray2(int ar[ ], int n)
I. Program Example on Function taking an array as argument :
Fill an array with random numbers. Print the total number of even elements.

import java.util.*;
public class clArReturn
{
int fnCountEven(int ar[], int n) // formal parameters (ar, n)
{
int c = 0;
for(int j = 0; j <= n – 1; j++)
{
if(ar[j] % 2 == 0)
{
c++;
}
}
return c;
}

180
METHODS (FUNCTIONS)

void main()
{
int dc[] = new int[10];
int ce = 0;
//filling the array with random numbers
for(int j = 0; j <= 9; j++)
{
dc[j] = (int) (Math.random() * 1000);
}
System.out.print(“\n The array with random numbers is ---- \n\t”);
for(int j = 0; j <= 9; j++)
{
System.out.print(dc[j] + “ ”);
}
ce = fnCountEven(dc, 10); // actual parameters ( dc, 10 )
System.out.print(“\n\n The total number of even elements present = ” + ce);
}
}
OUTPUT :
The array with random numbers is ------------
66 645 787 172 597 695 129 708 59 300
The total number of even elements present = 4
II. Program Example on Function taking and returning array as argument :
Set Operations :
Create two sets using 1D-Array. In a set no element should repeat. Create its Union
set, a set that has elements of both the sets except the repetitive elements.
PROGRAM IDEA
Two member array nov[] and dec[] with size sn, sd resp.
• fnFillSet() is accepting an array, filling it with unique random numbers ranging
between 10 and 20, and is returning the filled array.
• fnDisplay() is accepting an array as an argument and printing its values. Since 0
is not a valid element, it is not printed. Logically the union set may contain a few
0’s at the end in place of repetitive values.
• fnUnion() is taking 2 arrays (sets) as arguments and returning an array (the union
set). It applies the concept of a function returning an array.
181
ISC COMPUTER SCIENCE – XI

• In main() the function calls are made.


import java.util.*;
public class clSet
{
int nov[ ], dec[ ];
int sn, sd;
clSet(int m, int n)
{
sn = m;
sd = n;
nov = new int [sn];
dec = new int [sd];
}
void main()
{
nov = fnFillSet(nov, sn);
dec = fnFillSet(dec, sd); // filling the arrays with non duplicate elements

System.out.print(“\n First Array : ”);

fnDisplay(nov);
System.out.print(“\n Second Array : ”);
fnDisplay(dec);

int union[ ] = fnUnion(nov, dec);


System.out.print(“\n Union Array : ”);
fnDisplay(union);
}
int[ ] fnFillSet(int tmp[], int s)
{
for(int j = 0; j <= s – 1; j++)
{
boolean isp;
int d;

182
METHODS (FUNCTIONS)

do // loop to fill tmp[] with unique values


{
d = (int)(Math.random() * 100);
isp = false;
for(int k = 0; k <= j – 1; k++)
{
if(d == tmp[k])
{
isp = true;
break;
}
}
}
while(isp == true || d < 10);
tmp[j] = d;
}
return tmp; // returning array
}
void fnDisplay(int tmp[])
{
System.out.print(“ \n The array is :: ”);
for(int j = 0; j <= tmp.length – 1 && tmp[j] != 0; j++) // && tmp[j] ! = 0
{
System.out.print(tmp[j] + “ ”);
}
}
int[] fnUnion(int set1[], int set2[])
{
int uni[] = new int [set1.length + set2.length];
int j = 0, nj = 0;
for(j = 0; j <= set1.length – 1; j++)
{
uni[j] = set1[j];
}
nj = j;

183
ISC COMPUTER SCIENCE – XI

for(j = 0; j <= set2.length – 1; j++)


{
boolean isp = false;
for(int k = 0; k <= set1.length – 1; k++)
{
if(set2[j] == set1[k])
{
isp = true;
break;
}
}
if(isp == false)
{
uni[nj] = set2[j];
nj++;
}
}
return uni; //returning the union array
}
}
OUTPUT :
First Array :
The array is :: 15 10 16 19 18 13 12 17
Second Array :
The array is :: 15 18 12 14 20 16
Union Array :
The array is :: 15 10 16 19 18 13 12 17 14 20
III. Program Example on Function taking an array and modifying it [pass by reference] :
When an array is sent to a function as an argument, any change in it, is reflected back
in the actual parameter in the super function as well. It implements “pass by reference”
feature of an array.
Observe the following example :

import java.util.*;
public class clArTest
{

184
METHODS (FUNCTIONS)

void main()
{
int tmp[] = new int[10];

for(int j = 0; j <= 9; j++) //filling the array with random numbers


{
tmp[j] = (int)(Math.random() * 100);
}
System.out.print(“ \n Round 1 : ”);
fnDisplay(tmp);
fnChange(tmp);
System.out.print(“ \n Round 2 : ”);
fnDisplay(tmp);
}
void fnChange(int tmp1[]) // filling the array with 100 in all cells
{
for(int j = 0; j <= 9; j++)
{
tmp1[j] = 100;
}
} // the function is not returning any argument
void fnDisplay(int tmp[ ])
{
System.out.print(“ The array is :: ”);
for(int j = 0; j <= tmp.length – 1; j++)
{
System.out.print(tmp[j] + “ ”);
}
}
}
OUTPUT :
Round 1 : The array is :: 55 7 2 26 58 24 57 1 63 7
Round 2 : The array is :: 100 100 100 100 100 100 100 100 100 100

185
ISC COMPUTER SCIENCE – XI

OBJECTS AS ARGUMENTS

Member methods of a class can use objects of the same class. Java allows the objects
to be created and used in member methods of a class during the creation of the class.
I. Objects can be sent and returned as parameters of member methods.
The above concept is illustrated through the following program examples.
Example : Sending Objects to the methods of the same class. Program on Complex
Numbers. Create a class named clComplex whose details are as follows :
Class Name : clComplex
Member Data : int a, int b
Member Methods :
(i) clComplex() : Constructor to initialize member data to null.
(ii) void fnInput() : to input values for member data.
(iii) void fnShow() : to print member data as Complex Number [ ( a + b i ) ].
(iv) void fnAddComplex(clComplex c1, clComplex c2) : Add the two complex
numbers c1 and c2 sent as parameters to the method. The function prints the two complex
numbers and their sum.
(v) void main() : The controlling function to create two objects of clComplex
and input two complex numbers and send them to method fnAddComplex (clComplex,
clComplex).

import java.io.*;
import java.util.*;
public class clComplex
{
int a, b;
public clComplex()
{
a = 0;
b = 0;
}
void fnInputComplex()
{
Scanner sc = new Scanner(System.in);
System.out.print(“\n Enter value of Real Part : ”);

186
METHODS (FUNCTIONS)

a = sc.nextInt();
System.out.print(“Enter value of Imaginary Part : ”);
b = sc.nextInt();
}
public void fnShowComplex()
{
System.out.print(“ ” + a + “ + ” + b + “ i”);
}
void fnAddComplex(clComplex c1, clComplex c2) // c1, c2 are formal parameters
{
clComplex cAdd = new clComplex(); //Creating object to store result
cAdd.a = c1.a + c2.a;
cAdd.b = c1.b + c2.b;

//printing the complex numbers


System.out.print(“\n Complex Number c1 : ”);
c1.fnShowComplex();
System.out.print(“\n Complex Number c2 : ”);
c2.fnShowComplex();

System.out.print(“\n The SUM of c1 & c2 :: ”);

cAdd.fnShowComplex();
}
public void main()
{
clComplex cA = new clComplex();
clComplex cB = new clComplex();

System.out.println(“ Enter the 1st Complex Number cA : ”);


cA.fnInputComplex();

System.out.println(“\n Enter the 2nd Complex Number cB : ”);


cB.fnInputComplex();

System.out.print(“\n The SUM of cA & cB :– ”);


fnAddComplex(cA, cB); //cA, cB are actual parameters
}
}

187
ISC COMPUTER SCIENCE – XI

OUTPUT :
Enter the 1st Complex Number cA :
Enter value of Real Part : 11
Enter value of Imaginary Part : 22
Enter the 2nd Complex Number cB :
Enter value of Real Part : 20
Enter value of Imaginary Part : 30

The SUM of cA & cB :-


Complex Number c1 : 11 + 22 i
Complex Number c2 : 20 + 30 i
The SUM of c1 & c2 :: 31 + 52 i
II. Sending and modifying Objects as parameters
Changes made in formal value are reflected back in the actual value when objects
are sent.
Example : Fraction Handling. Create a class named clFraction whose details are as
follows :
Class Name : clFraction
Member Data : int Numerator, int Denominator
Member Methods :
(i) clFraction(…) : Parameterized Constructor to initialize member data.
(ii) voidfnPrintFraction() : To print member data as Fraction [Numerator/
Denominator].
(iii) fnReduceFraction(clFraction F1) : Reduce the fraction F1 using the hcf of its
numerator and denominator and return the reduced object F1.
(iv) void main() : The controlling function to input a fraction and reduce it. Print the
fraction before and after reduction.
(v) int fnHCF(int p, int q) : Returns the Highest Common Factor of arguments p, q.

import java.util.*;
public class clFraction
{
int Numerator, Denominator;
clFraction(int pn, int pd)
{
Numerator = pn;

188
METHODS (FUNCTIONS)

Denominator = pd;
}
public void main()
{
clFraction ph = new clFraction(90, 55); //creating object ph of class clFraction
System.out.print(“\n Fraction Before Reduction is : ”);
ph.fnPrintFraction();
fnReducefraction(ph);
System.out.print(“\n Fraction After Reduction is : ”);
ph.fnPrintFraction();
}
void fnPrintFraction()
{
System.out.print(“\n The Fraction is \t” + Numerator + “ / ”+ Denominator);
}
void fnReducefraction(clFraction F1) // method in which formal parameter is being
modified
{
int hc = fnHCF(F1.Numerator, F1.Denominator); //both arguments are integers
System.out.println(“\n HCF of ” + F1.Numerator + “ & ” +
F1.Denominator + “ is ” + hc);
F1.Numerator = F1.Numerator/hc;
F1.Denominator = F1.Denominator/hc; //modifying the object
}
int fnHCF(int p, int q)
{
int hcf = 1;
int sm = (p < q) ? p : q;
for(int h = sm; h >= 1; h– –)
{
if(p % h == 0 && q % h == 0)
{
hcf = h;
break;
}
}

189
ISC COMPUTER SCIENCE – XI

return hcf;
}
}
OUTPUT :
Fraction Before Reduction is :
The Fraction is 90 / 55
HCF of 90 & 55 is 5

Fraction After Reduction is :


The Fraction is 18 / 11

KEYWORD ‘this’
The keyword this is used to create an instance of the local class.
In other words we can say that the members of a class form a single object under
the keyword this.
The following program explains the keyword this.
Example : Using keyword this find the sum and difference of money in rupees and
paisa.
Create a class named clMoney whose details are as follows :
Class Name : clMoney
Member Data : int rs, int ps
Member Methods :
(i) clMoney() : Constructor to initialize member data to null.
(ii) void fnInput() : To input values for member data.
(iii) void fnShow() : To print member data as Money [ Rs 819.75 ].
(iv) clMoney fnAddAmount(clMoney m1, clMoney m2) : Add m1 and m2. Store
the result in corresponding member data. Return an object using operator this.
(v) void main() : The controlling function, to create two objects of clMoney. Find
their sum using the given member methods.

import java.util.*;
public class clMoney
{
int rs, ps;
clMoney()
{

190
METHODS (FUNCTIONS)

rs = 0;
ps = 0;
}
void fnInput()
{
Scanner sc = new Scanner(System.in);
System.out.print(“\n Enter Amount, Rupees part : ”);
rs = sc.nextInt();
System.out.print(“Paise part : ”);
ps = sc.nextInt();
}
void fnShow()
{
System.out.print(“ ` ” + rs + “.” + ps);
}
clMoney fnAddAmount(clMoney m1, clMoney m2)
{
rs = m1.rs + m2.rs; //filling the member data
rs = this.rs;
ps = this.ps
ps = m1.ps + m2.ps;
if(ps >= 100)
{
rs++;
ps –= 100;
}
return this; // creating object (this) using member data
}
public void main()
{
clMoney BookCost = new clMoney();
clMoney PenCost = new clMoney();

System.out.print(“\n Enter the Cost of Book ”);

BookCost.fnInput();

191
ISC COMPUTER SCIENCE – XI

System.out.print(“\n Enter the Cost of Pen ”);


PenCost.fnInput();

clMoney TotalCost = fnAddAmount(BookCost, PenCost);


//storing the method’s return in object TotalCost
System.out.print(“\n Cost of Book ”);
BookCost.fnShow();
System.out.print(“\n Cost of Pen ”);
PenCost.fnShow();
System.out.print(“\n Total Cost ”);
TotalCost.fnShow();
}
}
OUTPUT :
Enter the Cost of Book
Enter Amount, Rupees part : 64
Paise part : 50

Enter the Cost of Pen


Enter Amount, Rupees part : 9
Paise part : 75

Cost of Book ` 64.50


Cost of Pen ` 9.75
Total Cost ` 74.25

PURE AND IMPURE FUNCTIONS


Pure functions are those which do not change the values of arguments sent to it.
Example of pure functions :
• Display the value of arguments.
• Print the multiplication table of a number sent as an argument.
• Return the sum of two arguments sent as arguments.
Impure functions are those which change the values of arguments sent to it.
Example of impure functions :
• Increase the value of its argument by 1, each time the function is called.
• M
 odify the length of a ribbon by taking the length (as object having values of mt
and cm) and the amount of change (say c). The function changes the length by c.

192
METHODS (FUNCTIONS)

Shown below are two functions showing Pure and Impure functions. They work on
two objects of a class.
Example : Pure Function : Assume class clTime has two member data hh and mm.
For two objects T1, T2 of class clTime, the following function will not cause the actual
parameters (T1 and T2) to change.
void fnPure(clTime T1, clTime T2)
{
clTime T3 = new clTime();
T3.hh = T1.hh + T2.hh;
T3.mm = T1.mm + T2.mm;
T3.display();
}
Example : Impure Function : This following function will change actual parameter
(T1). In case of objects as parameters, any change in formal parameter value causes
change in actual parameters value.
void fnImpure(clTime T1, clTime T2)
{
T1.hh = T1.hh + T2.hh;
T1.mm = T1.mm + T2.mm;
}

CALL BY VALUE (CBYV) AND CALL BY REFERENCE (CBYR)


In case of CbyV, the changes taking place in the arguments are not reflected back in
the original values. The functions create a local copy of the arguments sent to it.
In case of CbyR, the changes taking place in the arguments are reflected back in the
original values. The functions work on the original arguments sent to it.

Call by Value : Call by Reference :


class CbyV class CbyR
{ {
int fnSample4(int y) public int s1, s2;
{ public CbyR()
y = 45; {
return y; s1 = 1;
} s2 = 2;
void main() }
{ public void Sample5(CbyR obj2)
int x = 15, z = 30; {
System.out.println(“ X = ” + x); obj2.s1 = 55;
z = fnSample4(x); obj.s2 = 66;
}

193
ISC COMPUTER SCIENCE – XI

System.out.println(“ Z = ” + z); public void fnShow()


System.out.println(“ X = ” + x); {
} System.out.print(“ s1 = ” + s1 +
} “ s2 = ” + s2);
OUTPUTS : }
X = 15
Z = 45 void main()
X = 15 {
CbyR doj = new CbyR();
doj.fnShow();
fnSample5(doj);
doj.fnShow();
}
}
OUTPUTS :
s1 = 1 s2 = 2
s1 = 55 s2 = 66

KEYWORD ‘static’

A class can have multiple objects, where the objects have their own copy of the class
members.
But some members of the class are unique which are not meant to be accessible to
the objects. Those members are called static members. They are common to all objects.
Static members of a class are called Class Members and non-static members of a
class are called Instance Members.
Non static variables cannot be used in a static method.
Example : Given below are some member data/functions of class School. Define
the class.
Member Data :
String schoolName, boardName, Principal
int totalStudents, totalTeachers, yearEstablished

Member Methods :
School_Examination, Board_Examination, Childrens_Day, Annual_Day
The class definition is shown below. The details of the methods are not given here.

194
METHODS (FUNCTIONS)

class School
{
String schoolName, boardName, Principal;
int totalStudents, totalTeachers, yearEstablished;
void School_Examination();
static void Board_Examination(); //not independent for objects
static void Childrens_Day(); /
/not independent for objects
void Annual_Day();
}

Note :
l From real life, we observe the difference between methods School_Examination()
and Board_Examination(). The first method can be different for different objects but
the second method is not different for the objects but for the class.

CONSTRUCTORS
A constructor is a member function of a class. It has some special features.
• A constructor has the same name as that of the class.
• It cannot be called as other functions. It gets automatically executed whenever an
object of that class is created.
• It does not have any return type, not even void.
• It may or may not take arguments.
A constructor is used to initialize the member data of a class to their initial values.
In general, the member data are initialized to null.
Note :
l The null value varies from one data type to another. For example null value of data
type int is 0, double is 0.0, char is ‘ ’ and string is “ ”.

Difference between a Constructor and a Normal Method of a Class


S.No. Normal Method Constructor
(i) It has to be invoked for execution. It gets automatically executed when an
object is created of that class.
(ii) It contains a block of code having It is used to assign member data to their
an aim (in order to do some initial value, (null in general).
mathematical or logical task).
(iii) It has some return type. It has no return type.
(iv) It has a name other than the class- It shares the same name as that of the
name. class.
(v) It can have any access specifier. It can only have ‘public’ access specifier.

195
ISC COMPUTER SCIENCE – XI

Default Constructor
When a program does not contain any constructor, java compiler provides a default
constructor. This constructor cannot be seen in the program. It initializes the member
data variables to their respective null values and it gets activated only when the program
does not contain any constructor.
Parameterized Constructor
It is a constructor having a list of arguments (or parameters). Since a constructor gets
executed automatically at the time of object creation, the values of these parameters must
be supplied during object creation.
Program Example :
import java.io.*;
public class ProgConstD
{
int m, gm;
public ProgConstD() //default constructor
{
m = 0;
gm = 0;
}
public ProgConstD(int cm, int cgm) //parameterized constructor
{
m = cm;
gm = cgm;
}
public void fnPrint()
{
System.out.print(“\n Member Data m = ” + m + “ and Member Data gm
= ” + gm);
}
}
OUTPUT :
The object creation will vary for the two constructors.

PACKAGES
A java package is a collection of classes that are related to each other in some way.
One class can access classes from another package by using the command ‘import’. Given
below is the list of java packages and their uses.

196
METHODS (FUNCTIONS)

java.lang — basic language functionality and fundamental types.


java.util — collection of data structure classes.
java.io — file operations.
java.math — multi-precision arithmetic.
java.nio — the New I/O framework for Java.
java.net — networking operations, sockets, DNS lookups, ...
java.security — key generation, encryption and decryption.
java.sql — Java Database Connectivity (JDBC) to access databases.
java.awt — basic hierarchy of packages for native GUI components.
—h
ierarchy of packages for platform-independent rich GUI
javax.swing
components.
java.applet — classes for creating an applet.

EXERCISE

1. Fill in the blanks :


(a) ___ (Impure/Pure) functions do not change the values of arguments sent to it.
(b) Keyword ___ (this/that) is used to create an instance of the local class.
(c) Member methods of a class ___ (can/cannot) use objects of the same class.
(d) ___ (Formal/Actual) parameters are used in the Super function.
(e) ___ (Static/Non-static) members of a class are called Class Members.

2. State True or False [correct the false statements] :

(a) In case of Call by Value, the changes that take place in the arguments are not
reflected back in the original values.
(b) Static members of a class are called Instance Members.
(c) Constructors can have any access specifier.
(d) Non static variable cannot be used in a static method.
(e) Java compiler provides a default constructor.
3. Write the difference between :
(a) Constructor and Normal Method.
(b) Call by Value and Call by Reference.
(c) Pure function and Impure function.
(d) Class member and Instance member.
(e) Super function and Sub function.
qq

197
ISC COMPUTER SCIENCE – XI

9 PROGRAM TOOLS
AND ARRAYS

l An Array and its use


l Dynamic and Static Array Allocation
l Use of Keyword ‘new’
l Programs on 1D arrays
l Nested Loop and 1D array
l Two Dimensional Arrays
l Programs on 2D arrays
l Advantage of use of Math.random()

AN ARRAY AND ITS USE


An array is a collection of multiple variables which share the same name and data
type. It is used in cases where a large number of similar type of data has to be used.
Suppose we want to store the marks obtained by 50 students in a subject (say maths).
We can either use 50 variables (which would not be a good option) or we can use one
array of size 50 (data type of the array being integer or double).
Each array has a name, type and size. It can store multiple values depending on its
size. All the values have to be of the same type. The array stores the values in cells. The
cells can be addressed by using the cell number. [Cell numbers are also called subscript
or index number.]
Syntax of declaring an array : Data-type array-name[ ] = new Data-type [size];
For example : int ar[ ] = new int [5];
ABOUT ARRAYS :
1. The [ ] brackets in the declaration statement indicates the size of the array.
2. In the working code, the [ ] brackets indicate the cell numbers.
3. The cell numbers begin with 0.
(It may sound confusing in the beginning; cell number of the 1st cell is 0).
4. If the array size is n then cell numbers range from 0 to (n–1).

ar[5] 15 64 97 82 56
Cell numbers 0 1 2 3 4
By seeing the above diagram, we can say :
198
PROGRAM TOOLS AND ARRAYS

ar[0] = 15; ar[1] = 64; ar[2] = 97; ar[3] = 82; ar[4] = 56;

DYNAMIC AND STATIC ARRAY ALLOCATION


An array is a collection of variables, where each variable is present in each cell of the
array. The cell numbers are continuous integers and hence can be generated by using a
loop. It is called Dynamic allocation. In dynamic allocation, even the size of the array
can be a variable.
An array can also be declared along with its values. The syntax is :–
int ra[ ] = {11, 22, 33, 44, 55};
In this case, the array gets declared and filled simultaneously. This is called Static
allocation.

USE OF KEYWORD ‘NEW’

Keyword new is used to allocate memory. In case of an array, memory requirement


varies with the size of the array. So, keyword new is used to allocate memory to an array
depending on its requirement.

PROGRAM LIST ON EXPLAINING ARRAYS

I Fill an array of type int and size 10 with variables.


1. Print the elements of the array in forward and reverse order.
2. … Print the even elements of the array.
3. … Print the sum and average of the elements present in the array.
4. … Print the factors of the first element from the elements present in the array.
5. Fill the marks obtained by 10 students in the array. Count & print how many of
them scored marks >= 80.
II. Fill 2 arrays of type int and size 5 each. Create another array and
6. fill each cell with the sum of the corresponding elements.
7. fill each cell with the larger value of the corresponding elements.
III. Application :
8. Fill an array of size 10 and type integer. Print those elements that appear after an
odd element.
9. Print those elements of the array that are larger than the average of the elements
of the array.
10. (i) Find the largest element in an array.
(ii) Print the smallest element in an array with its position.
IV. Nested Loop and 1D Array
11. Print the array with the effect of nested loop.

199
ISC COMPUTER SCIENCE – XI

V. Sample Codes
12. Print the array with the effect of nested loop.
1. Fill an array of type int and size 10 with variables. Print the elements of the
array in forward and reverse order.
Program Plan
u Fill the array car[ ] with 10 variables. Run a loop for input values.
u Run 2 more loops, one for forward traversal, one for reverse traversal.
PROGRAM
import java.util.*;
public class ArrayProgram
{
public void main()
{
int car[ ] = new int [10];
int c = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n Enter 10 elements of the array : \n”);
for(c = 0; c <= 9; c++)
{
System.out.println(“Enter the element for cell number” + c + “ : ”);
car[c] = sc.nextInt();
}
System.out.print(“\n\n The array elements in (Forward Order) – \n”);
for(c = 0; c <= 9; c++)
{
System.out.print(“ ” + car[c]);
}
System.out.print(“\n\n The array elements in (Reverse Order) – \n”);
for(c = 9; c >= 0; c– –)
{
System.out.print(“ ” + car[c]);
}
}
}

200
PROGRAM TOOLS AND ARRAYS

OUTPUT :
Enter 10 elements of the array :
Enter the element for cell number 0 : 11
Enter the element for cell number 1 : 22 (….Similarly enter 8 more elements)
The array elements in (Forward order) :
11 22 33 44 55 66 77 88 99 110
The array elements in (Reverse order) :
110 99 88 77 66 55 44 33 22 11
2. Fill an array of type int and size 10 with variables. Print the even elements of
the array.
Program Plan
u Fill the array car[ ] with 10 variables. Run a loop for input values.
u Run a loop, use a condition for even test. If the element is even then print it.
PROGRAM
import java.util.*;
public class ArrayProgram
{
public void main()
{
int car[ ] = new int [10];
int c = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n Enter 10 elements of the array : \n”);
for(c = 0; c <= 9; c++)
{
System.out.println(“Enter the element for cell number ” + c + “ : ”);
car[c] = sc.nextInt();
}
System.out.print(“\n\n The EVEN elements are : \n”);
for(c = 0; c <= 9; c++)
{
if(car[c] % 2 == 0)
{
System.out.print(car[c] +“ ”);
}
}
}
}

201
ISC COMPUTER SCIENCE – XI

OUTPUT (using random numbers) :


Enter 10 elements of the array :
Enter the element for cell number 0 : 11
Enter the element for cell number 1 : 22 (…. Similarly enter 8 more elements)
The EVEN elements are :
22 44 66 88 110

3. Fill an array of type int and size 10 with variables. Print the Sum and Average
of the elements present in the array.
Program Plan
u Fill the array with 10 variables. Run a loop for inputs.
u Run another loop to add the elements and store the sum in s.
u Calculate the average by using the formula av = s/10
u Print the average av.
PROGRAM
import java.util.*;
public class ArrayProgram
{
public void main()
{
int car[ ] = new int [10];
int c = 0;
double s = 0.0, av = 0.0;
Scanner sc = new Scanner(System.in);
System.out.print(“\n Enter 10 elements of the array : \n”);
for(c = 0; c <= 9; c++)
{
System.out.println(“Enter the element for cell number” + c + “ : ”);
car[c] = sc.nextInt();
}
System.out.print(“\n\n The array elements are : \n”);
for(c = 0; c <= 9; c++)
{
System.out.print(car[c] +“ ”);
s = s + car[c];
}
av = s/10;
202
PROGRAM TOOLS AND ARRAYS
System.out.print(“\n\n The average of the array elements is”+ av);
}
}
OUTPUT
Enter 10 elements of the array :
Enter the element for cell number 0 : 11
Enter the element for cell number 1 : 44 (…. Similarly enter 8 more elements)
The array elements are :
11 44 33 55 66 22 77 99 88 100
The average of the array elements is 59.5.

4. Fill an array of type int and size 10 with variables. Print the factors of the first
element from the elements present in the array.
Program Plan
u Fill the array ar[ ] with 10 variables. Run a loop for input values.
Run
u  a loop of c, inside it verify whether each element at cell c is a factor of the
first element (ar[0])
u If so then print it.
u This program is an example of “Condition inside a Loop”.
PROGRAM
import java.util.*;
public class ArrayProgram
{
public void main()
{
int ar[ ] = new int [5];
int c = 0, cnt = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“ Enter the elements of the array : \n”);
for(c = 0; c <= 9; c++)
{
System.out.println(“Enter the element for cell number ” + c + “ : ”);
ar[c] = sc.nextInt();
}
System.out.print(“\n The factors of the first element are : \n”);
for(c = 0; c <= 9; c++)
{

203
ISC COMPUTER SCIENCE – XI

if(ar[0] % ar[c] == 0)
{
System.out.print(ar[c]+“ ”);
}
}
}
}
OUTPUT :
Enter the elements of the array :
Enter the element for cell number 0 : 120
Enter the element for cell number 1 : 100
Enter the element for cell number 2 : 20 (…. Similarly enter 7 more elements)
The factors of the first element are :
120 20 10 ……
5. Fill an array of type int and size 10 with variables. Fill the marks obtained by
10 students in the array. Count and print how many of them scored marks >= 80.
Program Plan
u Fill the array marks[ ] with 10 variables. Run a loop for input values.
u Initialize a counter cnt to 0.
u Run a loop of j, and for each marks[j] >= 80, increase cnt by 1.
u Finally out of the loop, print cnt.
PROGRAM
import java.util.*;
public class ArrayProgram
{
public void main()
{
int marks[ ] = new int [5];
int j = 0, cnt = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the marks : \n”);
for(j = 0; j <= 9; j++)
{
System.out.println(“Enter the marks for roll number” + (j + 1) + “ : ”);
marks[j] = sc.nextInt();
}
204
PROGRAM TOOLS AND ARRAYS

for(j = 0; j <= 9; j++)


{
if(marks[j] >= 80)
{
cnt++;
}
}
System.out.print(“\n Number of students scoring >= 80 is ” + cnt);
}
}
OUTPUT :
Enter the marks :
Enter the marks for roll number 1 : 75
Enter the marks for roll number 2 : 82 (…. Similarly enter 8 more marks)
Number of students scoring >= 80 is 4
6. Fill 2 arrays of type int and size 5 each. Create another array and fill each cell
with the sum of the corresponding elements.
Program Plan
Fill
u  2 arrays m1[ ] and m2[ ] with 5 variables each. Run a loop each for filling
both the arrays.
u Run a loop of j, and at each value, add the corresponding elements.
u Print all the three arrays using 3 loops.
m1[5] 15 64 97 82 56
Cell numbers 0 1 2 3 4

m2[5] 5 12 3 9 10
Cell numbers 0 1 2 3 4

m3[5] 20 76 100 91 66
Cell numbers 0 1 2 3 4

PROGRAM
import java.util.*;
public class ArrayProgram
{
public void main()
{

205
ISC COMPUTER SCIENCE – XI

int m1[ ] = new int [5];


int m2[ ] = new int [5];
int m3[ ] = new int [5];
int j = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“Fill the first array : \n”);
for(j = 0; j <= 4; j++)
{
System.out.println(“Enter the value for cell” + (j) + “ : ”);
m1[j] = sc.nextInt();
}
System.out.print(“Fill the second array : \n”);
for(j = 0; j <= 4; j++)
{
System.out.println(“Enter the value for cell” + (j) + “ : ”);
m2[j] = sc.nextInt();
}
for(j = 0; j <= 5; j++)
{
m3[j] = m1[j] + m2[j];
}
System.out.print(“ \n\n The First array is : \n”);
for(j = 0; j <= 4; j++)
System.out.print(m1[j]+“ ”);
System.out.print(“ \n\n The Second array is : \n”);
for(j = 0; j <= 4; j++)
System.out.print(m2[j]+“ ”);
System.out.print(“ \n\n The Third array with their sum is : \n”);
for(j = 0; j <= 4; j++)
System.out.print(m3[j]+“ ”);
}
}
OUTPUT :
Fill the first array :
Enter the value for cell 0 : 15

206
PROGRAM TOOLS AND ARRAYS

Enter the value for cell 1 : 64 (….Similarly enter rest data )
Fill the second array :
Enter the value for cell 0 : 5
Enter the value for cell 1 : 12
 (….Similarly enter rest data…the third array gets filled)
The First array is :
15 64 …..
The Second array is :
5 12 …..
The Third array with their sum is :
20 76 …..
7. Fill two arrays of type int and size 5 each, fill each cell with the larger value of
the corresponding elements.
Program Plan
u Fill the two arrays using 2 separate loops.
u To fill the third array, use a loop and compare the corresponding elements.
An
u  element from either the first array or the second array will go to the third
array.
m1[5] 10 8 1 19 7
Cell numbers 0 1 2 3 4

m2[5] 5 12 3 9 6
Cell numbers 0 1 2 3 4

m3[5] 10 12 3 19 7
Cell numbers 0 1 2 3 4
PROGRAM
The loop to fill the third array will be :
for(j = 0; j <= 5; j++)
{
if(m1[j] > m2[j])
{
m3[j] = m1[j];
}
else
{

207
ISC COMPUTER SCIENCE – XI

m3[j] = m2[j];
}
}
8. Print those elements that appear after an odd element.

5 12 3 4 9
Example : java.lang.arrayindexoutofboundsexception

Note :
l The above program will give an exception of array index out of bounds as there is
no element after the last element.

 9. Fill an array of size 10 and type integer. Print those elements of the array that
are larger than the average of the elements of the array.
Hint : One loop to find the average. One loop again to print those elements that
are larger than the average.
10. (i) Find the largest element in an array.
Program Plan
u Fill the array.
u To find the largest element, a variable named max is used.
u Variable max begins with the value in the first cell.
Then
u  one by one all the elements are compared with it. Whenever any other
element of the array becomes larger than max, the value of max is overwritten
by that.
u Thus, when finally the array traversal ends, max contains the largest element.

am[5] 10 8 1 19 7
Cell numbers 0 1 2 3 4
PROGRAM
// declare and fill the array m[5]
int max = am[0];
//Finding the maximum element
for(c = 1; c <= 9; c++)
{
if(max < car[c]) //whenever max becomes smaller, it is overwritten
{
max = car[c];
}
}
System.out.print(“\n The largest element of the array is : ” + max);

208
PROGRAM TOOLS AND ARRAYS

10. (ii) Print the smallest element in an array with its position.
Program Plan
u To find the smallest element, variable min = am[0]; also minp = 0.
Each
u  time a smaller element is found in the array, overwrite min with that
particular element and minp with its position.
u Thus, min finally stores the smallest element and minp stores its position.
am[5] 10 8 1 19 7
Cell numbers 0 1 2 3 4
Min = am[0] = 10; minp = 0; /
/these values will change
PROGRAM
…………..
// declare and fill the array m[5]
int min = am[0], minp = 0;
//Finding the minimum element

for(c = 1; c <= 9; c++)


{
if(min > am[c]) //whenever max becomes smaller, it is overwritten
{
min = am[c];
minp = c;
}
}
System.out.print(“\n The smallest element is : ” + min + “less at position” + minp);

NESTED LOOP AND 1D ARRAY


11. Observe the outputs of the following codes :
// declare and fill the array am[10] assume [ 55 44 33 22 11 99 88 77 66 50 ]
(a) for(int r = 0; r <= 9; r++)
{
for(int c = r; c <= 9; c++)
{
System.out.print(am[c] + “ ”);
}
System.out.println();
}

209
ISC COMPUTER SCIENCE – XI

(b) for(int r = 9; r >= 0; r– –)


{
for(int c = 0; c <= r; c++)
{
System.out.print(am[c] + “ ”);
}
System.out.println();
}
(c) for(int r = 0; r <= 9; r++)
{
for(int c = 0; c < r; c++)
{
System.out.print(“ ”);
}
for(int c = r; c <= 9; c++)
{
System.out.print(am[c] + “ ”);
}
System.out.println();
}
(d) for(int r = 9; r >= 0; r– –)
{
for(int c = 0; c < r; c++)
{
System.out.print(“ ”);
}
for(int c = r; c <= 9; c++)
{
System.out.print(am[c] + “ ”);
}
System.out.println();
}
Write complete programs for the above codes and observe their outputs.

210
PROGRAM TOOLS AND ARRAYS

SAMPLE CODES
12. Write the outputs of the following codes :
(i) import java.util.*;
public class clD
{
void fnMon()
{
int arMon[ ] = {33, 55, 77, 99, 11, 22, 88, 44, 66};
int k = 0;
for(k = 0; k <= 7; k = k + 2)
{
arMon[k] = arMon[k + 1];
}
System.out.println(“The modified array is :: ”);
for(k = 0; k <= 7; k++)
{
System.out.print(“ ” + arMon[k]);
}
}
}
(ii) import java.util.*;
public class clE
{
void fnTue()
{
int arTue[ ] = {33, 55, 77, 99, 11, 22, 88, 44, 66};
int k = 0;
for(k = 1; k <= 8; k = k + 2)
{
arTue[k] = arTue[k – 1];
}
System.out.println(“The array after modification is :: ”);
for(k = 0; k <= 7; k++)
{
System.out.print(“ ” + arTue[k]);
}
}
}

211
ISC COMPUTER SCIENCE – XI

(iii) import java.util.*;


public class clF
{
void fnWed()
{
int arWed[ ] = {33, 55, 77, 99, 11, 22, 88, 44, 66};
int k = 0;
for(k = 1; k <= 8; k = k + 2)
{
arWed[k – 1] = arWed[k] * 2;
}
System.out.println(“The array after modification is :: ”);
for(k = 0; k <= 7; k++)
{
System.out.print(“ ” + arWed[k]);
}
}
}
(iv) import java.util.*;
public class clG
{
void fnThu()
{
int arThu[ ] = {3, 5, 7, 9, 1, 2, 8, 4, 6};
int k = 0, quen = 0;
for(k = 0; k <= 8; k++)
{
if(k % 2 == 0)
{
quen = quen + arThu[k];
}
else
{
quen = quen * arThu[k];
}
System.out.println(“During calculation ” + arThu[k] + “The Result
is :: ” + quen);
}
System.out.println(“The Final Result is :: ” + quen);
}
}

212
PROGRAM TOOLS AND ARRAYS

(v) import java.util.*;


public class clH
{
void fnFri()
{
int arFri[ ] = {3, 5, 7, 9, 1, 2, 8, 4, 6};
int k = 0, tot1 = 0, tot2 = 0;
for(k = 0; k <= arFri.length; k++)
{
tot1 = tot1 + arFri[k];
}
tot1 = tot1/arFri.length;
for(k = 0; k <= arFri.length; k++)
{
if(arFri[k] > tot1)
{
tot2 = tot2 + arFri[k];
}
}
System.out.println(“Result One is :: ” + tot1);
System.out.println(“Result Two is :: ” + tot2);
}
}

TWO DIMENSIONAL ARRAYS


A two-dimensional array is a collection of elements where the elements are logically
arranged in rows and columns. A 2-D array is used for handling data arranged in tabular
form. It can work with more data than in a 1-D array.
We can visualize a 2-D array, TA[4][5] as shown below :

The name of the array here is TA. It has 4 rows and 5 columns.

213
ISC COMPUTER SCIENCE – XI

Syntax of declaring a 2D array in Java :


Data-type array-name[ ][ ] = new Data-type [row-size][col-size];
For example :
int TA[ ][ ] = new int [4][5];
The row and column numbers begin with 0. Each element is located with the help
of its row and column value.
Let us assume another example of a 2D array containing random integers :

RA[3][5] 0 1 2 3 4
0 25 45 50 49 39
1 63 67 60 89 29
2 47 41 20 79 19
From the above diagram, we can say :
The first element is 25 and its location is [0][0]. Thus RA[0][0] = 25
The last element is 19 and its location is [2][4]. Thus RA[2][4] = 19
For other elements, RA[0][4] = 39; RA[1][0] = 63; RA[2][2] = 20;
If we draw the array with its cell positions, then we will see :
For an array RA[3][5] :
Col 1 Col 2 Col 3 Col 4 Col 5
Row 0 [0][0] [0][1] [0][2] [0][3] [0][4]
Row 1 [1][0] [1][1] [1][2] [1][3] [1][4]
Row 2 [2][0] [2][1] [2][2] [2][3] [2][4]

Note :
l Elements of a 2D array are accessed using a nested loop of order 2.

PROGRAMS ON 2D ARRAYS
 rogram 1 : Program to input variables in a 2D array of order 3 × 4. Print the
P
elements in matrix form with 3 rows and 4 columns.
Program Plan
u The array has 3 rows and in each row, there are 4 columns.
u  A nested loop is used to access the element’s position. The outer loop representing
the rows and the inner loop representing the columns.
u  Since all the values are variables, the input statement should be inside the inner
loop.
While
u  printing, all elements of each row should be in the same line. After
finishing each row, next row elements should appear in the next line. So, a new
line command is required after the inner loop gets over.

214
PROGRAM TOOLS AND ARRAYS

PROGRAM
//To fill a 2D Array and print it in Matrix Form

import java.util.*;
public class ProgA
{
public void main()
{
int RA[ ][ ] = new int [3][4];
int r = 0, c = 0;
Scanner sc = new Scanner(System.in);
// Entering the elements in the array
for(r = 0; r <= 2; r++)
{
for(c = 0; c <= 3; c++)
{
System.out.print(“ \n Enter the value for cell number ”+ r + “ ” + c + “ :: ”);
RA[r][c] = sc.nextInt();
}
}
System.out.print(“\n\n Printing the elements of the array : \n”);
for(r = 0; r <= 2; r++)
{
for(c = 0; c <= 3; c++)
System.out.print(“ ” + RA[r][c]);
System.out.print(“\n”);
}
}
}
OUTPUT :
Entering Values :
Enter the value for cell Enter the value for cell Enter the value for cell
number 0 0 :: 54 number 1 0 :: 76 number 2 0 :: 12
Enter the value for cell Enter the value for cell Enter the value for cell
number 0 1 :: 45 number 1 1 :: 67 number 2 1 :: 21
Enter the value for cell Enter the value for cell Enter the value for cell
number 0 2 :: 65 number 1 2 :: 87 number 2 2 :: 23
Enter the value for cell Enter the value for cell Enter the value for cell
number 0 3 :: 56 number 1 3 :: 78 number 2 3 :: 32

215
ISC COMPUTER SCIENCE – XI

Printing the elements of the array :


54 45 65 56
76 67 87 78
12 21 23 32
Automatic Filling a 2d Array
Using Method Math.random().
To fill an array with random numbers, java method random can be used. This
method generates random numbers. Method details are given below :
Header file required : java.math.*;
Method call statement : Math.random();
Return type : double, a value > 0 and < 1.
Advantage of Using Math.random()

The advantage of using this method is that we can have multiple cells filled with
variables without executing the input statement.

Program Code Example 1 :


import java.math.*;
……….
double p = Math.random();
System.out.print(“ p = ” + p);
// variable p gets a random number, for example p = 0.8971717880153237

Program Code Example 2 :


import java.math.*;

double ar[10] = new double[5];


for(int j = 0; j <= 5; j++)
{
ar[j] = Math.random() * 10;
}
// 5 values of datatype double will get automatically filled in the array ar[ ]
// 10 is multiplied move the point to the right. Ex – 8.971717880153237

Program Code Example 3 :


import java.math.*;

int dr[4][5] = new int [4][5];

216
PROGRAM TOOLS AND ARRAYS

for(int r = 0; r <= 3; r++)


{
for(int c = 0; c <= 4; c++)
{
dr[r][c] =(int) (Math.random() * 100);
/* random numbers converted to 2 digit
integers */
}
}

 rogram 2 : Program to fill variables in a 2D array of order 4 × 3. Count and print


P
the number of values >= 40.
Program Plan
u The array has 4 rows and in each row, there are 3 columns.
Use
u  a nested loop to fill the elements of the array. [use Math.random(), convert
to int]
u Traverse the array and count the values that are >= 40, and print them.
PROGRAM
// Program to input variables in a 2D array of order 4 × 3. Print the array in matrix form.
// Also count the number of values >= 40.
import java.io.*;
import java.math.*;
public class ProgB
{
public void main()
{
int RB[][] = new int [3][4];
int r = 0, c = 0;
// Filling random numbers in the array
for(r = 0; r <= 2; r++)
{
for(c = 0; c <= 3; c++)
{
RB[r][c] = (int) (Math.random());
}
}

217
ISC COMPUTER SCIENCE – XI

// Counting elements which are >= 40 in the array


int cnt = 0;
for(r = 0; r <= 2; r++)
{
for(c = 0; c <= 3; c++)
{
if(RB[r][c] >= 40)
{
cnt++;
}
}
}
System.out.print(“\n\n Printing the elements of the array : \n”);
System.out.print(“\n Number of elements >= 40 is :” + cnt);
}
}
OUTPUT :
Printing the elements of the array :
50 40 10 20
70 90 80 60
30 15 95 75
Number of elements >= 40 is : 7

 rogram 3 : Program to create a 2D array of order 5 × 6. Fill the first cell with a
P
variable and fill the rest of the cells with continuous numbers row-wise. Print the
array in matrix form.

Program Plan
Only
u  the first cell’s value is entered by the user. Rest of the cells are filled with
continuous numbers.
Use
u  a counter to generate the numbers that fill the cells.

PROGRAM CODE
int RC[ ][ ] = new int [5][6];
int r = 0, c = 0, rsize = 5, csize = 6, val;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the value for the first cell : ”);

218
PROGRAM TOOLS AND ARRAYS

val = sc.nextInt();
// Filling the array
for(r = 0; r < rsize; r++)
{
for(c = 0; c < csize; c++)
{
RC[r][c] = val;
++val;
}
}
System.out.print(“\n\n Printing the array : \n”);
for(r = 0; r < rsize; r++)
{
for(c = 0; c < csize; c++)
{
System.out.print(RC[r][c]+ “ ”);
}
System.out.print(“\n”);
}
OUTPUT :
Enter the value for the first cell : 25
Printing the array :
25 26 27 28 29 30
31 32 33 34 35 36
37 38 39 40 41 42
43 44 45 46 47 48
49 50 51 52 53 54
 rogram 4 : Program to fill a 2D array of order 3 × 4. Print the row-wise sum of
P
the elements.
Program Plan
u Fill the array.
Calculate
u  the sum of each row and print it. After working for each row, refresh
the sum.
PROGRAM
int RD[ ][ ] = new int [3][4];
int r = 0, c = 0;

219
ISC COMPUTER SCIENCE – XI

// Calculating row-wise sum


for(r = 0; r <= 2; r++)
{
int sum = 0; // for each row, sum should start with 0
for(c = 0; c <= 3; c++)
{
sum = sum + RD[r][c];
}
System.out.print(“\n Sum of the elements of row ” + r + “ = ” + sum);
}
OUTPUT :
The array :
55 33 22 44
66 44 10 80
60 40 20 30
Sum of the elements of row 0 = 154
Sum of the elements of row 1 = 200
Sum of the elements of row 2 = 150
 rogram 5 : Program to fill a 2D array of order 3 × 4. Print the row-wise maximum
P
and its position (row and column).
Program Plan
u Fill the array.
u For each row, find the max and print it and then refresh max.
PROGRAM
// Finding row-wise max and its position
for(r = 0; r <= 2; r++)
{
int max = 0, maxpc = 0;
for(c = 0; c <= 3; c++)
{
if(max < RE[r][c]) // if max is lesser than the next number then overwrite it
{
max = RE[r][c];
maxpc = c; // store the row, col position of the max
}
} // closing c

220
PROGRAM TOOLS AND ARRAYS

// printing the largest element for each row


System.out.print(“\n Largest element of row number ” + r + “ = ” + max +
“ at col position ” + maxpc);
} // closing loop of r
OUTPUT :
Printing the elements of the array :
11 22 33 44
55 66 99 88
77 11 55 22
Largest element of row number 0 = 44 at col position 3
Largest element of row number 1 = 99 at col position 2
Largest element of row number 2 = 77 at col position 0
Q. Complete the following code to find col-wise min and its position :
for( ___ ; ____ ; ___ )
{
int min = ___ , minpr = ___ ;
for( ___ ; ___ ; ___ )
{
if( ___ ___ RE[ ___ ][ ___ ] )
{
min = RE[ ___][ ___ ];
minpr = r;
}
} // closing c
System.out.print(“\n Smallest element of col number ” + c + “ = ” + min +
“ at row position ” + minpr);
} // closing loop of r

EXERCISE

1. Answer the following in brief :


(a) What is the use of keyword ‘new’ ?
(b) What is the difference between static and dynamic array allocation ?
(c) How is an array different from a variable ?
(d) What is the importance of loop in array handling ?
(e) What is the syntax of declaring a 2D array ?
2. Given below are some codes. Rewrite the erroneous codes without the errors :
(a) int MAY[5][10] = new int [ ][ ];
(b) double Day[ ] = new Day[7];

221
ISC COMPUTER SCIENCE – XI

(c) Int JUL[ ] = new Int [5];


(d) Double Da[ ] = [2.2, 6.1, 4.3, 7.5, 5.4];
(e) int Apr{} = {11, 21, 31, 41, 51, 61, 71};
(f) int Mar = new int {50; 60; 70; 80; 90};
(g) int Jun[ ] = new int [5];
for(int k = 1; k <= 5; k++)
{
Jun[k] = k * 10;
}
(h) int Feb = new int [10];
for(int k = 10; k >= 0; k++)
{
feb[k] = 100;
}
(i) int aug[ ] = new int [10];
aug[0] = 5;
for(int k = 0; k <= 9; k++)
{
aug[k + 1] = aug[k] * 2;
}
(j) double JAN[10 ] = new int [10];
for(int k = 0; k <= JAN.length(); k++)
{
JAN [k] = k;
}
3. The Aim of the following code is to create an array by removing the duplicate
elements. It applies a left shift on the elements for each duplicate element.
The following code contains some logical errors. Debug the code.
import java.util.*;
public class Array1
{
public void main()
{
Scanner sc = new Scanner(System.in);
int ar[ ] = new int[10];
int i, k, limit = 10;

222
PROGRAM TOOLS AND ARRAYS

boolean alr = false;


for(i = 0; i < 10; i++)
{
System.out.println(“Enter the element at index no. ”+ i);
ar[i] = sc.nextInt();
}
System.out.println(“\f The Array is ”);
for(i = 0; i < limit; i++)
System.out.print(ar[i] + “ ”);
for(i = 1; i < 10; i++)
{
alr = isAlready(ar, i);
if(alr == true)
{
for(k = i; k < 9; k++)
{
ar[k] = ar[k + 1];
}
limit–  –;
}
}
System.out.println(“\n The Modified Array is”);
for(i = 0; i < limit; i++)
System.out.print(ar[i] + “ ”);
}
boolean isAlready(int ar[ ], int p)
{
boolean isA = false;
int j;
for(j = 0; j < p; j++)
{
if(ar[j] == ar[p])
{
isA = true;
break;
}
}
return isA;
}
}

223
ISC COMPUTER SCIENCE – XI

ERRNEOUS OUTPUT :
The Array is 11 22 33 22 44 33 55 22 66 22
The Modified Array is 11 22 33 [this is wrong output]
 [output should be …. 11 22 33 44 55 66]
4. Given below is a partial code that reverses an array. Complete the code :
void fnContrary(int Rn[ ])
{
System.out.println(“\n The elements …”);
for(int r = 0; r <= _____; r++)
System.out.print( _______ + “ ”);
for(int k = 0; k <= ra.length/2 – 1; k++)
{
int tm = ________;
______ = Rn [Rn.length – k – 1];
_______ = tm;
}
System.out.println(“\n The elements after Reversal …”);
for(int r = 0; r <= _____; r++)
System.out.print( ____ + “ ”);
}
5. Given below is a code. Guess its output :
import java.util.*;
public class clH
{
void fnHR()
{
int hr[ ] = new int [10];
int val = (int)(Math.random() * 10);
val = (val == 0) ? 5 : val;
hr[0] = val;
for(int j = 1, k = 2; j <= 9; j++)
{
if(j % 2 == 0)
hr[j] = hr[j – 1] /2;
else
hr[j] = hr[j – 1] * k++;
}

224
PROGRAM TOOLS AND ARRAYS

System.out.println(“ The Final Array : ”);


for(int j = 0; j <= 9; j ++)
System.out.print(“ ” + hr[j]);
}
}
6. Given below is a code. Guess its aim :
import java.util.*;
public class clH
{
void fnHR()
{
int dr[ ] = new int [6];
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the 1st element : ”);
dr[0] = sc.nextInt();
int j = 1;
while(j <= 5)
{
System.out.print(“Enter next element : ”);
dr[j] = sc.nextInt();
if(dr[j] > dr[j – 1])
j++;
else
System.out.println(“ Invalid. ”);
}
System.out.println(“ The Final Array : ”);
for(j = 0; j <= 5; j++)
{
System.out.print(“ ” + dr[j]);
}
}
}
7. Given below is a code. Guess its aim :
import java.util.*;
class D2
{
void fnTD(int A2[ ][ ]) // Sub function
{

225
ISC COMPUTER SCIENCE – XI

for(int j = 0; j < A2.length; j++)


{
for(int k = 0; k < A2[j].length; k++)
System.out.print(A2[j][k] + “ ”);
System.out.println();
}
}
void fnTM() //Super function
{
int R2[ ][ ] = new int [5][4];
for(int j = 0; j <= 3; j++)
{
for(int k = 0; k <= 3; k++)
{
R2[j][k] = (int)(Math.random() * 100);
}
}
fnTD(R2);
}
}
8. Given below is a code. Guess its aim :
void ST()
{
String S2[ ][ ] = new String[3][4];
Scanner sc = new Scanner(System.in);
for(int j = 0; j <= 2; j++)
{
for(int k = 0; k <= 3; k++)
{
System.out.print(“Enter a word : ”);
S2[j][k] = sc.nextLine();
}
}
System.out.print(“ The string array : ”);
for(int j = 0; j <= 2; j++)
{
for(int k = 3; k >= 0; k– –)
{
System.out.print(“ ” + S2[j][k]);
}
System.out.println();
}
}
qq

226
ARRAY
10 APPLICATIONS–SORT
AND SEARCH
l Sorting
 Different types of Sorting
 Selection, Bubble and Insertion
l Search
 Linear and Binary
l Comparison of linear and Binary Search Processes

SORTING
Sorting means to arrange elements in order :
For example :
(i) Books on the study table in order of their size.
(ii) Students standing in the morning assembly line according to their heights.
(iii) Newspapers kept in order of date.
(iv) Marks obtained by the students of a class arranged from highest to lowest.
We sort elements from random order to ascending / descending order. When we
sort them in real life, we may apply a variety of techniques. But when we have to write
their algorithm, we have to work in a specific order.
Different types of Sorting
There are many types of sorting techniques available to sort a group of elements,
such as Bubble Sort, Selection Sort, Insertion Sort, Quick Sort and so on. Which sorting
algorithm to choose, depends on the size and values of the elements in the list.
In this chapter we will learn the program code of Sorting Algorithm—Selection,
Bubble, Insertion.
Selection Sort
The principal of Selection Sort for arranging an unordered list in ascending order is :
(i) Select the smallest element in the unsorted list of size n.
(ii) Swap it with the first element of the unsorted list [BG & SM in the example].
(iii) Modify the unsorted list by moving the initial or the starting element.
ISC COMPUTER SCIENCE – XI

(iv) Repeat the steps for (n – 1) times.


Example :
Step 1 :

85 50 20 40 60
BG SM
0 1 2 3 4
Step 2 :

20 50 85 40 60
BG SM
0 1 2 3 4
Step 3 :

20 40 85 50 60
BG SM
0 1 2 3 4
Step 4 :

20 40 50 85 60
BG SM
0 1 2 3 4
Step 5 :

20 40 50 60 85
0 1 2 3 4
Program : Sort an array in ascending order using Selection Sort.

import java.io.*;
class clSelSort
{
int ra[ ] = {85, 50, 20, 40, 60};
void fnSelectionSort( )
{
int bg = 0, sm = 0, psm = 0, r = 0, tmp = 0;
for(bg = 0; bg <= 3; bg++)
{
sm = ra[bg];
228
ARRAY APPLICATIONS–SORT AND SEARCH

psm = bg;
for(r = bg + 1; r <= 4; r++)
{
if(sm > ra[r])
{
sm = ra[r];
psm = r; // position of the smallest element
}
}
/* swapping the element in the beginning of the unsorted array with the
smallest element */
tmp = ra[bg]; ra[bg] = ra[psm]; ra[psm] = tmp;
}
System.out.println(“The elements in Ascending order after Selection Sort …”);
for(r = 0; r <= 4; r++)
System.out.print(ra[r] + “ ”);
}
}
Q. Why does bg range from 0 to 3 ?
Ans. In the example n = 5. The cells range from 0 to n – 1 (= 4). To arrange five
elements in ascending order, placing 4 elements in order automatically puts the 5th in
place. So, after putting element in cell number 3, there is only the last element left.
Hence, bg ranges from 0 to n – 2 (5 – 2 = 3).
Bubble Sort
The principal of Bubble Sort for arranging an unordered list in ascending order is :
(i) Compare two consecutive elements and swap if required.
(ii) The largest unsorted element gets its place after each complete traversal.
(iii) Repeat the process (n – 1) number of times.
(iv) Modify the unsorted list by reducing the size of the list by 1 each time.
Program : Sort an array in ascending order using Bubble Sort.
import java.io.*;
class clSort
{
int ra[ ] = {95, 50, 20, 40, 60};
int n = 5;

229
ISC COMPUTER SCIENCE – XI

void fnBubbleSort()
{
int s, j, tmp, r;
for(s = 1; s <= 4; s++)
{
for(j = 0; j <= (n – 1) – s; j++)
{
if(ra[j] > ra[j + 1])
{
tmp = ra[j];
ra[j] = ra[j + 1];
ra[j + 1] = tmp;
}
}
}
System.out.println(“ The elements in Ascending order after Bubble Sort …”);
for(r = 0; r <= 4; r++)
{
System.out.print(ra[r] + “ ”);
}
}
}
Example : Given list is 50 20 40 10 5
Stage 1 :
1 2 3 4 5
S
50 J=0 20 20 20 20
W
A S
20 J+1 P 50 J=1 40 40 40
W
A S
40 40 J+1 50 J=2 10 10
P W
A S
10 10 10 J+1 P 50 J=3 W 5
A
5 5 5 5 J+1 P 50
Two consecutive elements are compared and interchanged (swapped), if required.
At the end of stage 1, the last position gets the largest element [50 in this case].
Stage 2 :
1 2 3 4
20 J=0 20 S 20 20
40 J+1 40 J=1W 10 S 10

230
ARRAY APPLICATIONS–SORT AND SEARCH

10 10 J+1A 40 J=2W 5
5 5 P 5 J+1A 40
50 50 50 P 50
nd
At the end of stage 2, the 2 last position gets the next largest element.
Stage 3 :

1 2 3
20 J=0S 10 10

10 J+1W 20 J=1S 5
5 A 5 J+1W 20
40 P 40 A 40
50 50 P 50

At the end of stage 3, the 3rd last position gets the next largest element.
Stage 4 :

1 2
10 J=0S 5
5 J+1W 10
20 A 20

40 P 40

50 50
At the end of stage 4, the 4th last position gets the next largest element. And there
are no more elements left to be compared. So, this stage gives the final sorted array.

Insertion Sort

The principal of Insertion Sort for arranging an unordered list in ascending order is :

(i) Pick an element and find its suitable position on its left.

(ii) Insert the element by right shifting the other elements by one place.

(iii) Repeat the process for elements in 2nd to last position.

Example : Given list is 85 25 10 70 60 35

[Note that the process begins from 2nd element as the 1st element has nothing on
its left.]

231
ISC COMPUTER SCIENCE – XI

Step 1 :
85 25 10 70 60 35
0 1 2 3 4 5

Step 2 :
25 85 10 70 60 35
0 1 2 3 4 5

Step 3 :
10 25 85 70 60 35
0 1 2 3 4 5

Step 4 :
10 25 70 85 60 35
0 1 2 3 4 5
Step 5 :
10 25 60 70 85 35
0 1 2 3 4 5
Step 6 :
10 25 35 60 70 85
0 1 2 3 4 5
PROGRAM
import java.io.*;
class clSort
{
int ra[ ] = {85, 25, 10, 70, 60, 35};
int n = 6;
void fnInsertionSort()
{
for(int p = 1; p <= n – 1; p++)
{
int lp = 0;
while(ra[lp] < ra[p])
{
lp++;
} //lp gives the position of insert
int tmp = ra[p];

232
ARRAY APPLICATIONS–SORT AND SEARCH

for(int k = p – 1; k >= lp; k– –) // shifting right


{
ra[k + 1] = ra[k];
}
ra[lp] = tmp;
}
System.out.println(“\n The elements in Ascending order after Insertion Sort …”);
for(int r = 0; r <= n – 1; r++)
System.out.print(ra[r] + “ ”);
}
}

SEARCH
Search, as the name suggests, is the process of searching for an element in a array. In
general, the process of search results in a boolean value of true or false.
In this chapter, we will learn about linear search (also called sequential) and binary
search.
Linear Search
This process is simple. Compare all the elements one by one with the element that
is being searched.
(i) Run a loop from the beginning to the end of the array.
(ii) Compare the element being searched with the current element.
(iii) If a match is found, then the element is present. Terminate the loop.
(iv) If no match is found till the end of the loop, the element is not present.
Example :
import java.io.*;
class clSearch
{
int ra[ ] = {79, 58, 42, 61, 79, 66, 34, 62, 94, 73};
int n = 10;
boolean fnLinearSearch(int val)
{
boolean found = false;
for(int p = 0; p <= n – 1; p++)
{
if(ra[p] == val)

233
ISC COMPUTER SCIENCE – XI

{
found = true;
break;
}
}
if(found == true)
System.out.print(“ Element ” + val + “ IS Present.”);
else
System.out.print(“ Element ” + val + “ IS NOT Present.”);
return found;
}
}
Binary Search
This process works only on presorted arrays. It is a time saving algorithm for very
long list of values. It works by halving the arrays with each failed search comparison.
(i) Assume the lower limit to be low and the upper limit to be high.
(ii) Find the middle position of low and high, say mid.
(iii) Compare the search element with the element at position mid.
(iv) If a match is found then the process terminates.
(v) If a match is not found then—
u Change low to (mid + 1) if the element being searched is larger than the
element in mid.
u Change high to (mid – 1) if the element being searched is smaller than the
element in mid.
(vi) The element is not present if low becomes > high.
Example :
import java.io.*;
class clSearch
{
int ra[ ] = {79, 58, 42, 61, 79, 66, 34, 62, 94, 73};
int n = 10;
void main()
{
fnInsertionSort(); // to sort the source array
fnBinarySearch(58); // searching a random number
}

234
ARRAY APPLICATIONS–SORT AND SEARCH

void fnBinarySearch(int val)


{
boolean found = false;
int low = 0, high = n – 1, mid = 0;
while(low <= high)
{
mid = (low + high) / 2;
System.out.print(“\n Element at the middle position” + mid + “ IS”
+ ra[mid]);
if(ra[mid] == val)
{
found = true;
break;
}
else if(ra[mid] > val)
high = mid – 1;
else
low = mid + 1;
}
if(found == true)
System.out.print(“\n Element” + val + “ IS Present.”);
else
System.out.print(“\n Element” + val + “IS NOT Present.”);
}
void fnInsertionSort()
{
for(int p = 1; p <= n – 1; p++)
{
int lp = 0;
while(ra[lp] < ra[p])
{
lp++;
} //lp gives the position of insert
int tmp = ra[p];
for(int k = p – 1; k >= lp; k– –) //shifting right
{
ra[k + 1] = ra[k];
}

235
ISC COMPUTER SCIENCE – XI

ra[lp] = tmp;
}
System.out.println(“\n The elements in Ascending order after Insertion Sort …”);
for(int r = 0; r <= n – 1; r++)
{
System.out.print(ra[r] + “ ”);
}
}
}
Example 1 : Dry run of Binary Search algorithm.
Given the array RS[ ]. Let the element to search (VAL) be 295.
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low Mid High

Step 1 : Low = 0; High = 14; → Mid = 7; RS[Mid] = 185


Val = RS[Mid] → False
⇒ Val > RS[Mid]
⇒ Low = Mid + 1 = 8
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low Mid High

Step 2 : Low = 8; High = 14; → Mid = 11; RS[Mid] = 325


Val = RS[Mid] → False
⇒ Val < RS[Mid]
⇒ High = Mid – 1 = 10
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low Mid High

Step 3 : Low = 8; High = 10; → Mid = 9; RS[Mid] = 295


Val = RS[Mid] → True
The search is successful.

236
ARRAY APPLICATIONS–SORT AND SEARCH

Note :
Binary
l  Search takes 3 steps here, Sequential Search would have taken 9 steps.
Example 2 : Dry run of Binary Search algorithm.
Given the array RS[ ]. Let the element to search (VAL) be 300.
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low Mid High

Step 1 : Low = 0; High = 14; → Mid = 7; RS[Mid] = 185


Val = RS[Mid] → False
⇒ Val > RS[Mid]
⇒ Low = Mid + 1 = 8
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low Mid High

Step 2 : Low = 8; High = 14; → Mid = 11; RS[Mid] = 325


Val = RS[Mid] → False
⇒ Val < RS[Mid]
⇒ High = Mid – 1 = 10
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low Mid High

Step 3 : Low = 8; High = 10; → Mid = 9; RS[Mid] = 295


Val = RS[Mid] → False
⇒ Val > RS[Mid]
⇒ Low = Mid + 1 = 10
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Low
High
Mid

237
ISC COMPUTER SCIENCE – XI

Step 4 : Low = 10; High = 10; → Mid = 10; RS[Mid] = 310


Val = RS[Mid] → False
⇒ Val < RS[Mid]
⇒ High = Mid – 1 = 9
Here, the process continues as long as (Low <= High).
10 25 60 70 85 115 136 185 250 295 310 325 355 370 395
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
High Low
Mid
The Element is Not Present in the array.
Note :
Binary
l  Search takes 4 steps here, Sequential Search would have taken 15 steps.
Q. If we have easy sequential search why use such complicated binary search ?
What does speed mean, when we see no difference in both the processes when
we work ?
Ans. : Imagine a Situation : A library has 70,000 books. Members have issued books
of their choice.
If the books are not kept in order then it will require sequential search process to
help a member request. It will be a slower process. Binary search here would be a faster
process.

COMPARISON OF LINEAR AND BINARY SEARCH PROCESSES

Sequential Search : In case of sequential search, the process is simple. No need to


rearrange the elements. The process is better when the number of elements are relatively
less. In case of huge number of elements, and very frequent search operations, this
process is considered very slow.
Binary Search : In this case, the process is relatively complicated. The array has to be
sorted in either ascending or descending order. In case of huge number of elements, and
very frequent search operations, this process is considered very fast.

EXERCISE
1. Answer the following :
(a) What is meant by sort ? Give two real life cases where sort is applied.
(b) What is search ? Give two real life cases where search is applied.
(c) Does sorting a list cause a change in the list ? Justify your answer.
(d) Does searching an element in a list cause a change in the list ? Justify your
answer.
(e) What does a searching process return ?

238
ARRAY APPLICATIONS–SORT AND SEARCH

2. Given the set of data : 55 22 11 77 33 66


What will the source list become upon the following operations ?
(a) 1st round of Bubble Sort for descending order.
(b) 1st round of Selection Sort for ascending order.
(c) 1st round of Insertion Sort for descending order.
(d) The 3rd round of Bubble Sort for ascending order.
(e) The 3rd round of Selection Sort for descending order.
(f) The 3rd round of Insertion Sort for ascending order.

3. Perform dry run on the following data :


(a) Given the set of data : 700, 500, 800, 200, 300, 600
Apply Selection Sort for Ascending order and show the changes in each round.
(b) Given the set of data : 70, 50, 80, 20, 30
Apply Insertion Sort for Ascending order and show the changes in each round.
(c) Given the set of data : 70, 50, 80, 30, 20
Apply Bubble Sort for Ascending order and show the changes in each round.
(d) Write the complete menu driven program (fill an unsorted array of type int and
size 10, sort the array and print the array) for the above three sorting methods,
in ascending order and in descending order. Use functions and call them upon
choice.
4. Given the partial codes, identify the aim and complete the blanks :
(a)
_____ fnTest1(int Ra[ ], int r)
{
boolean hasr = ____;
int low = 0;
int _____ = Ra.length – 1;
int mid = 0;

while(low <= high)


{
mid = _____;
System.out.print(“\n Element at mid” + mid + “IS” + ______ );
if(ra[mid] == ___)
{
____;

239
ISC COMPUTER SCIENCE – XI

break;
}
else if(_____)
{
high = ___;
}
else
{
low = _____;
}
}
return hasr;
}
(b)
boolean fnTest2(_____ , _____ )
{
for(int p = _____; p <= Rs.length – 1; p++)
{
if(Rs[p] == w)
{
return _____;
}
}
return _____;
}
(c)
void fnTest3(int Rd[ ])
{
for(int p = 1; p <= _____; p++)
{
int left = _____;
while(_____)
{
left++;
}

240
ARRAY APPLICATIONS–SORT AND SEARCH

int tmp = _____;


for(int r = ____; r >= left; _____)
{
Rd[ _____ ] = Rd[r];
}
_____
}
System.out.println(“ \n The elements after modification are ….. ”);
for(int p = 0; _____ ; p++)
System.out.print(Rd[p] + “ ”);
}
(d)
void fnTest4(int Rh [ ])
{
_______
for(st = 1; st <= _____; st++)
{
for(j = 0; j <= _____; j++)
{
if(_____)
{
m = ra[j];
ra[j] = _____;
______ = m;

}
}
}
System.out.println(“ The elements in Descending order are …”);
for(r = 0; r <= _____; r++)
System.out.print( _____ + “ ”);
}
(e)
void fnTest5(int Rk[ ])
{
________

241
ISC COMPUTER SCIENCE – XI

for(start = 0; start <= ______; start++)


{
small = _______;
position = ______;
for(k = _____;_____; k++)
{
if(______)
{
small = Rk[k];
______
}
}
temp = _____;
_____
______ = temp;
}
System.out.println(“ The elements in Ascending order are …”);
for(k = 0; ______ ; k++)
System.out.print(_____ + “ ”);
}
5. Given below is an erroneous code that applies Insertion Sort on an array. Analyze,
justify and debug the code :

void fnInsertionSort2()
{
int left = 0;
for(int p = 1; p <= n – 1; p++)
{
while(ra[left] > ra[p]);
{
left++;
}
int tmp = ra[p];
for(int k = p – 1; k >= left; k– –)
{
ra[k + 1] = ra[k];
}

242
ARRAY APPLICATIONS–SORT AND SEARCH

ra[left] = tmp;
}
System.out.println(“\n The elements in Decending order after Insertion
Sort …”);
for(int r = 0; r <= n – 1; r++)
System.out.print(ra[r] + “ ”);
}
6. Given below is the code of Selection Sort with a logical error. It attempts to find
the maximum element each time and sort the array in ascending order. Rectify the
code :
void fnSelectionSort()
{
int AD[ ] = {22, 10, 65, 45, 29, 98, 41, 78};
int st = 0, max = 0, pmax = 0, r = 0, tmp = 0;
for(st = 0; st <= AD.length – 2; st++)
{
max = AD[st];
pmax = st;
for(r = st + 1; r <= AD.length – 1; r++)
{
if(max < AD[r])
{
max = AD[r];
pmax = r; // position of the largest element
}
}
/* swapping the element at the end of the unsorted array with the largest
element */
tmp = AD[st];
AD[st] = AD[pmax];
AD[pmax] = tmp;
}
System.out.println(“ The elements in Ascending order after Selection Sort …”);
for(r = 0; r <= AD.length – 1; r++)
System.out.print(AD[r] + “ ”);
}
qq

243
STRINGS AND
11 LIBRARY METHODS

l Strings and Characters


Features of Java Characters and Strings

l String Library Methods : Detail and Example


l Worked programs on String Handling
l Other Library Methods
l Mathematical Library Functions
l Scanner Class
l Array of Strings
l Worked Programs on String Arrays

STRINGS AND CHARACTERS


All the keyboard characters fall under the primitive category char. A char value can
have only one character in it and they are enclosed within single quotes ‘’.
For example : char ch = ‘p’; c har c2 = ‘!’;
A group of characters form a string. Java provides us with a class called String that
helps to create and manipulate strings. The String class in Java also has a set of library
methods.
For example : String sr = “The world is ours.”;
Features of Java Characters and Strings
(i) Characters fall under the primitive category char.
A String is a Java class that creates a word or sentence using a group of
characters.
(ii) A character is enclosed within single quotes ”.
A string is enclosed within double quotes “ ”.
(iii) Characters have a fixed size of 2 bytes.
Size of string is not fixed.
STRINGS AND LIBRARY METHODS

(iv) Java has a Wrapper Class called Character that provides character handling
methods.
String is not a primitive class but it is a Java class that provides string handling
methods.
String Library Methods : List of a few commonly used methods :
1. int length() 9. String concat(String s1)
2. char charAt(int p) 10. boolean startsWith(String s1)
3. int indexOf(char c1) 11. String replace(char oldChar, char
4. int lastIndexOf(char c1) newChar)

5. int compareTo(String s1, String s2) 12. String substring (int beginIndex,
int endIndex)
6. boolean endsWith(String s1)
13. String toLowerCase()
7. boolean equals(String s1)
14. String toUpperCase()
8. boolean equalsIgnoreCase(String s1)
15. String trim()
16. String valueOf(any data-type)
String Library Methods : Detail and Example
1. int length() It returns the length of the string.
String st1 = “CASTELLO-FARARNA”;
int len = st1.length(); // len = 16
2. char charAt(int p) It returns the character present at position p of the
string.
String st2 = “AMAZON-RAINFOREST”;
char c1 = st2.charAt(0); // c1 = A
char c2 = st2.charAt(5); // c2 = N
char c4 = st2.charAt(17); // error
char c5 = st2.charAt(16); // c5 = T
3. int indexOf(char c1) It returns the first index of character c1 in the string.
String st3 = “THIRUVANANTHAPURAM”;
int p1 = st3.indexOf(‘A’); // p1 = 6
int p2 = st3.indexOf(‘R’); // p2 = 3
4. int lastIndexOf(char c1) It returns the last index of character c1 in the string.
String st4 = “CASTELRO-FARARNA”;
int p3 = st4.lastIndexOf(‘A’); // p3 = 15
int p4 = st4.lastIndexOf(‘R’); // p4 = 13
int p5 = st4.lastIndexOf(‘S’); // p5 = 2

245
ISC COMPUTER SCIENCE – XI

It returns the numeric difference between the


5. int compareTo(String s2)
characters of the current string and the argument
string s2. It uses the ASCII values and subtracts the
2nd string from the 1st string.
In case of mismatch, the difference of the 1st
mismatch is returned.
If the strings are of unequal lengths and if the
present characters match then it subtracts the
length of the second string from the length of the
first string and returns it.
String st5 = “DA”;
int cm1 = st5.compareTo(“HP”); // cm1 = –4
int cm2 = st5.compareTo(“BE”); // cm2 = 2
int cm3 = st5.compareTo(“DA”); //cm3 = 0
int cm4 = st5.compareTo(“DZ”); //cm3 = –25
String sr5 = “ZYXWV”;
int cm5 = sr5.compareTo(“A”); //cm5 = 25
int cm6 = st5.compareTo(“ZY”); //cm6 = 3
int cm7 = st5.compareTo(“ZYXWVTU”); //cm7 = –2
6. boolean endsWith(String s2) It returns the boolean result of comparison of the
argument string s2 present at the end of the 1st
string. It is case sensitive.
String st6 = “PONDICHERRY”;
boolean r1 = st6.endsWith(“CHERRY”); //r1 = true
boolean r2 = st6.endsWith(“CHER”); // r2 = false
boolean r3 = st6.endsWith(“erry”); // r3 = false
7. boolean equals(String s2) It returns the boolean result of comparison
of equality between the current string and the
argument string s2. It is case sensitive.
String st7 = “RISTORANTE”;
boolean er1 = st7.equals(“RISTORANTE”);
//er1 = true
boolean er2 = st7.equals(“RISTORante”);
//er2 = false
8. boolean equalsIgnoreCase It returns the boolean result of comparison of
(String s2) equality between the current string and the
argument string s2. It is not case sensitive. (It
ignores the difference between uppercase and
lowercase alphabets present in both the strings)
String st8 = “PIZZERIA”;

246
STRINGS AND LIBRARY METHODS

boolean er1 = st8.equalsIgnoreCase(“PIZZERIA”);


// er1 = true
boolean er2 = st8.equalsIgnoreCase(“pizzeria”);
// er2 = true
boolean er3 = st8.equalsIgnoreCase(“PASTA”);
// er3 = false
9. String concat(String s2) It concatenates the argument string s2 behind the
current string and returns the new string.
String st9 = “HINDUSTAN”;
String stc1 = st9.concat(“–COPPER”);
// stc1 = HINDUSTAN-COPPER
String stc2 = st9.concat(“ZINC”);
// stc2 = HINDUSTANZINC
10. boolean startsWith It returns the boolean result of comparison of the
(String s2) argument string s2 present at the beginning of the
1st string. It is case sensitive.
String st10 = “JAMSHEDPUR”;
boolean r1 = st10.startsWith(“JAM”); // r1 = true
boolean r2 = st10.startsWith(“AM”); // r2 = false
11. String replace(char old It returns a new string using the current string in
Char, char newChar) which one character is replaced by another. It can
also replace substrings in the same way.
String st11 = “GELATERIACREAM”;
String stre = st11.replace(‘E’,‘O’); //stre =
GOLATORIACROAM
12. String substring(int It returns a new string using the current string whose
(beginIndex, int endIndex) starting and ending character index numbers are
given.
If the 2nd numeric argument is not given then it
goes till the end. It includes the 1st position number
but excludes the 2nd position number.
String st12 = “MIZORAM”;
String stsub1 = st12.substring(3, 6); //stsub1 = ORA
String stsub2 = st12.substring(0, 3); // stsub1 = MIZ
String stsub3 = st12.substring(3); // stsub1 = ORAM
13. String toLowerCase() It converts the current string to lower case and
returns it.
String st13 = “KERELA”;
String stlow = st13.toLowerCase(); // stlow = kerela
247
ISC COMPUTER SCIENCE – XI

14. String toUpperCase() It converts the current string to upper case and
returns it.
String st14 = “jammu”;
String stup = st14.toUpperCase(); // stup = JAMMU
15. String trim() It trims the spaces present before and after the 1st and
last character of the current string and returns it.
String st15 = “RIENA”;
st15.length() = 11;
String strim = st15.trim;
strim.length() = 5;
16. String valueOf It converts an argument of any type to string.
(any data-type) int st16 = 2596;
String stval = string. valueOf(st16);
//stval gets string “2596”

WORKED PROGRAMS ON STRING HANDLING


1. Write a program to input a string and print each word of the string and the
number of characters present in it.
2. Write a program to input a string and count the frequency of the first alphabet
of the string.
3. Write a program to input a string and print the last letter of each word.
4. Write a program to input a string and print each word of the sentence in a new
line.
5. Write a program to input a string and print the words that begin with letter ‘s’.
6. Write a program to input a string and make a new string in which character
variable p is replaced by character variable q and print it.
7. Write a program to input a string and count the number of vowels in the string
and print it.
8. Write a program to input a string and count the number of vowels in each word
of the string and print it.
9. Write a program to input a name as a string and print the name in the format –
Usain St Leo Bolt => U.S.L.Bolt
10. Write a program to print the ASCII characters from 55 to 65.
11. Write a program to input a string and print the frequency of upper/lower case
letters and digits.
12. Write a program to input a string and convert lower case letters to upper case
and vice versa … ignore non alphabets.
13. Write a program to input a string and print the next character for each alphabet
in a string … circular – A after Z.

248
STRINGS AND LIBRARY METHODS

14. Write a program to input a string and shift the characters of a string - p –
positions in the alphabet list and print the new string. Assume the alphabets are
placed circularly, i.e., A appears after Z.
15. Write a program to input a string and convert the 1st letter of each word to upper
case and the rest of the letters to lower case.
16. Write a program to input a string and print the reverse of each word.
17. Write a program to input a string and print the longest word in a sentence.
18. Write a program to input a string and print the frequency of a substring.
19. Write a program to input a string and verify whether the longest word ends
with the shortest word or not.
20. Write a program to make a new string by swapping the first and the last char of
each word.
21. Write a program to input a string sentence and verify if it is a V-Free sentence
or not. A sentence is called V-Free if it contains at least one word that does not
contain any vowel in it.
Program Solutions
1. Write a program to input a string and print each word of the string and the
number of characters present in it.
Program Idea
• A word ends with a space. To identify the last word, add a space to the sentence.
• Input a sentence and declare the strings word and wlen to store a word and its
length respectively.
• Pick up each character (ch).
 If it is not a space then add it to word, and increase wlen by 1.
 If it is a space, then print word and wlen and then refresh both variables.
import java.util.*;
public class clStringTest
{
void fnWordLength()
{
String s1= “ ”;
int len = 0;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a sentence : ”);
s1 = sc.nextLine();
s1 = s1 + “ ”;
len = s1.length();
String word = “”;

249
ISC COMPUTER SCIENCE – XI

int wlen = 0;
for(int j = 0; j <= len – 1; j++)
{
char ch = s1.charAt(j);
if(ch != ‘ ’)
{
word = word + ch;
wlen++;
}
else
{
System.out.println(word + “ ” + wlen);
word = “ ”;
wlen = 0; //refreshing word & word-length
}
}
}
}
OUTPUT :
Enter a sentence : MADAGASCAR IS ON INDIAN OCEAN
MADAGASCAR 10
IS 2
ON 2
INDIAN 6
OCEAN 5
2. Write a program to input a string and count the frequency of the first alphabet
of the string.
Program Idea
• Input a string say st.
• Store the first letter in a variable, say fch.
• Run a loop of j from 0 to string (length – 1).
• Pick each character using method st.charAt(j) and store in say ch.
• Compare each value of ch with fch. If they match, increase counter cnt by 1.
• After verifying all the characters of the string st, print cnt.
** To count the frequency of any random character, input that character and rest of
the logic is similar.

250
STRINGS AND LIBRARY METHODS

// Frequency of the first character


import java.util.*;
public class Prog1
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
char fch= ‘’, ch = ‘’;
int cnt = 0;
System.out.println(“Enter the string : ”);
st = sc.nextLine();
fch = st.charAt(0);
int j = 0, len = st.length();
for(j = 0; j <= len – 1; j++)
{
ch = st.charAt(j);
if(ch == fch)
{
cnt++;
}
}
System.out.print(“ Frequency of the first letter is : ” + cnt);
// one time printing, out of loop
}
}
OUTPUT :
Enter the string : en de eldo dela pierre
Frequency of the first letter is : 6
3. Write a program to input a string and print the last letter of each word.
Program Idea
• Input a string, say st.
• Run a loop of j from 0 to string length() – 1.
• Pick up each character, in say ch.
• If ch is space or dot, then pick char at its previous position (j – 1)

251
ISC COMPUTER SCIENCE – XI

// Print the last letter of each word


import java.util.*;
public class clLastLetter
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
char tch= ‘’, ch = ‘’;
System.out.println(“Enter the string that ends with a full stop : ”);
st = sc.nextLine();
int j, len = st.length();
for(j = 1; j <= len – 1; j++)
{
ch = st.charAt(j);
if(ch == ‘ ’ || ch == ‘.’) //if the char is a space or dot(.), then print its
previous char
{
tch = st.charAt(j – 1);
System.out.print(“ ” + tch); //to print multiple times
}
}
}
}
OUTPUT :
Enter the string that ends with a full stop : Lisbon is the capital of PORTUGAL.
nselfL
4. Write a program to input a string and print each word of the sentence in a new
line.
Program Idea
• Input a string, say st.
• Pick each character (in ch) and if it is not a space or a ‘ . ’ add it to word.
• I f a space or ‘ . ’ is found, it is printed in a new line and the variable word is
cleared.
• Repeat the process for all characters.
// Print the words in a new line each
import java.util.*;

252
STRINGS AND LIBRARY METHODS

public class clWordsInNewLIne


{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”, word = “”;
char ch;
System.out.println(“ Enter the string that ends with a full stop : ”);
st = sc.nextLine();
int j, len = st.length();
System.out.println(“ The sentence is :: ” + st);
for(j = 0; j <= len – 1; j++)
{
ch = st.charAt(j);
if(ch != ‘ ’ && ch != ‘.’) //if the char is neither a space nor a dot
{
word = word + ch; // then add it to word
}
else //if ch is a space or a dot, then print the word
{
System.out.println(“ WORD :: ” + word);
word = “”; //after printing each word, clear the variable, for the
next word
}
}
}
}
OUTPUT :
Enter the string that ends with a full stop : Save the Trees.
The sentence is :: Save the Trees.
WORD :: Save
WORD :: the
WORD :: Trees
5. Write a program to input a string and print the words that begin with letter ‘s’.
Program Idea
• Program logic is similar to the previous program.
• In this case, whenever a word is ready, its first letter is compared with ‘s’ / ‘S’.
253
ISC COMPUTER SCIENCE – XI

• The word is printed only if its first letter matches.


• Upgrade : the program can input a character in place of ‘s’.
// Print those words which begin with letter ‘s.’
import java.util.*;
public class clWordsSelect
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”, word = “”;
char ch;
System.out.println(“ Enter the string that ends with a full stop : ”);
st = sc.nextLine();
int j, len = st.length();
System.out.println(“The sentence is :: ” + st);
for(j = 0; j <= len – 1; j++)
{
ch = st.charAt(j);
if(ch != ‘ ’ && ch != ‘.’) //if the char is neither a space nor a dot
{
word = word + ch; // then add it to word
}
else //if ch is a space or a dot, then the word is ready
{
if(word.charAt(0) == ‘s’ || word.charAt(0) == ‘S’) //only if word
starts with ‘s’
{
System.out.println(“ WORD :: ” + word); //or ‘S’ then to print
}
word = “”; //clear the variable before making new word
}
}
}
}

254
STRINGS AND LIBRARY METHODS

OUTPUT :
Enter the string that ends with a full stop : The Sunday Special movie was Superman.
The sentence is :: The Sunday Special movie was Superman.
WORD :: Sunday
WORD :: Special
WORD :: Superman
6. Write a program to input a string and make a new string in which character
variable p is replaced by character variable q and print it.
Program Idea
• Input a string, say st.
• Create a new empty string newst.
• Pick each character of st in ch.
• If a character matches with variable character p then add variable character q to
newst else add ch itself to newst.
• Repeat the process for all characters.

Note :
l Upgrade the given program to work with two variable characters.
// Replace letter ‘p’ by ‘q’
import java.util.*;
public class clReplaceLetter
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”, newst = “”;
char ch;
System.out.println(“ Enter the string that ends with a full stop : ”);
st = sc.nextLine();
int j, len = st.length();
System.out.println(“ The sentence is :: ” + st);
for(j = 0; j <= len – 1; j++)
{
ch = st.charAt(j);
if(ch == ‘a’) //if the char is ‘a’
{

255
ISC COMPUTER SCIENCE – XI

newst = newst + ‘o’; // then add ‘o’ to it


}
else //if ch is not ‘a’ then add the same char
{
newst = newst + ch;
}
}
System.out.println(“ The new sentence is :: ” + newst);
}
}
OUTPUT :
Enter the string that ends with a full stop : Happy went for a picnic in the park.
The sentence is :: Happy went for a picnic in the park.
The new sentence is :: Happy went for a qicnic in the qark.
7. Write a program to input a string and count the number of vowels in the string
and print it.
Program Idea
• Input a string, say st. Send it to the function, store the function’s return in vc and
print it.
• The function takes a string and returns the number of vowels in it.
• A loop of p from 0 to string (length – 1).
• Pick each character using method st.charAt(p) and store in say ch.
• Compare each value of ch with vowel list. If they match, increase the counter c
by 1.
• After verifying all the characters of string st, return c.
import java.util.*;
public class clTotalVowels
{
void main()
{
Scanner sc = new Scanner(System.in);
String st = “”, wd = “”;
char ch = ‘’;
int vc = 0;
System.out.println(“Enter the string : ”);
st = sc.nextLine();

256
STRINGS AND LIBRARY METHODS

vc = fnTotalVowels(st); // sending st to the fn , the return c is taken in vc


System.out.println(“ Number of vowels in .... ” + st + “ ... is ” + vc);
}
int fnTotalVowels(String ww) //to count total number of vowels in ww
{
int c = 0; char ch;
System.out.println(“ The String is ” + ww);
for(int p = 0; p <= ww.length() – 1; p++) // loop run for all characters
{
ch = ww.charAt(p);
if(ch = = ‘a’ || ch = = ‘A’ || ch == ‘e’ || ch == ‘E’ || ch == ‘i’ || ch == ‘I’
|| ch = = ‘o’||ch = = ‘O’||ch == ‘u’||ch == ‘U’)
//if a vowel, then count
{
c++; // increment of c if ch is a vowel
}
}
return c;
}
}
OUTPUT :
Enter the string : August is the Eighth Month
Number of vowels in .... August is the Eighth Month... is 8
8. Write a program to input a string and count the number of vowels in each
word of the string and print it.
Program Idea
• A word is a set of characters that have a space after (except the last word).
• Pick each word, count its vowels by using a function, and print both the word
and the counter.
Use function int fnCountVowels(String se)
• Refresh the variable storing word each time.
import java.util.*;
public class clStringTest
{
int fnCountVowels(String se)
{

257
ISC COMPUTER SCIENCE – XI

int c = 0;
se = se.toUpperCase();

for(int j = 0; j <= se.length() – 1; j++)


{
char ch = se.charAt(j);

if (ch == ‘A’ || ch == ‘E’ || ch == ‘I’ || ch == ‘O’ || ch == ‘U’ )


{
c++;
}
}
return c;
}
void main()
{
String s1=“”;
int len = 0;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a sentence that ends with ‘.’: ”);
s1 = sc.nextLine();
len = s1.length();
String word = “”;
int wv = 0;
for(int j = 0; j <= len – 1; j++)
{
char ch = s1.charAt(j);

if(ch != ‘’ && ch != ‘.’)


{
word = word + ch;
}
else
{
wv = fnCountVowels(word);
System.out.println(word + “\t has ” + wv + “ Vowels.”);
word = “”;

258
STRINGS AND LIBRARY METHODS

wv = 0; //refreshing word
}
}
}
}
OUTPUT :
Enter a sentence that ends with ‘.’ : Madagascar is in the Indian Ocean.
Madagascar has 4 Vowels.
is has 1 Vowels.
in has 1 Vowels.
the has 1 Vowels.
Indian has 3 Vowels.
Ocean has 3 Vowels.
9. Write a program to input a name as a string and print the name in the form of
initials and surname.
For example :
input – Usain St Leo Bolt output – U.S.L.Bolt
input – Mansoor Ali Khan Pataudi output – M.A.K.Pataudi
Program Idea
• The program logic is to print the first letter of each word except the last word
and to print the full last word.
• Assume the length of the string is stored in say len1. In order to print the initials,
the position of the last space (using method lastIndexOf( )) is stored in say len2.
Then from positions (len2 + 1) to (len1 – 1), all characters are printed.
M a n s o o r A l i K h a n P a t a u d i
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Len2 Len1
//printing a name in initial and surname form
import java.util.*;
public class clNameInitials1
{
public void main()
{
Scanner sc = new Scanner(System.in);
String fullName = “”, iniName = “”;
char ch = ‘’;

259
ISC COMPUTER SCIENCE – XI

int len1 = 0, len2 = 0;


System.out.print(“\n Enter the full name of a person :”);
fullName = sc.nextLine();
len1 = fullName.length();
len2 = fullName.lastIndexOf(‘ ’);
//upto last index of space, print first letter of each word
iniName = fullName.charAt(0) + “.”;
for(int j = 1; j <= len2 – 1; j++)
{
ch = fullName.charAt(j);
if(ch == ‘ ’) //for each space, print the next character
{
iniName += fullName.charAt(j + 1) + “.”;
}
}
iniName += fullName.substring(len2 + 1);
System.out.print(“\n The name in initials is : ” + iniName);
}
}
OUTPUT :
Enter the full name of a person : Mansoor Ali Khan Pataudi
The name in initials is : M.A.K.Pataudi
10. Write a program to print the ASCII characters from 55 to 65.
Program Idea
• All keyboard characters are numbered using ASCII values.
• All ASCII values are integers. [upgrade the program to print the chart of ASCII
values]
// ASCII characters from 55 to 65
import java.util.*;
public class clASCIIChar
{
public void main()
{
System.out.println(“The ASCII Codes from 50 to 100 are :: ”);
for(int j = 55; j <= 65; j++)
{
char ch = (char) j;
260
STRINGS AND LIBRARY METHODS

System.out.println(“ ASCII ” + j + “ .... char ” + ch);


}
}
}
OUTPUT :
The ASCII Codes from 50 to 100 are ::
ASCII 55 .... char 7
ASCII 56 .... char 8
ASCII 57 .... char 9
ASCII 58 .... char :
ASCII 59 .... char ;
ASCII 60 .... char <
ASCII 61 .... char =
ASCII 62 .... char >
ASCII 63 .... char ?
ASCII 64 .... char @
ASCII 65 .... char A
11. Write a program to input a string and print the frequency of characters that are
Upper case, Lower case, digits.
Program Idea
• All keyboard characters are numbered using ASCII values.
• All ASCII values are integers.
• Important ASCII Codes.
Upper case characters range from 65 to 90 where ASCII value of A = 65.
Lowercase characters range from 97 to 122 where ASCII value of a = 97.
Digits range from 48 to 57 where ASCII value of 0 = 48.
• Pick each character, and verify its ASCII value. If the ASCII value belongs to any
of the above range then increase the corresponding counter.
• The following program shows the frequency of Upper case only.
// Frequency of UpperCase character in a string using ASCII codes
import java.util.*;
public class clFreqUppercase
{
public void main()
{
Scanner sc = new Scanner(System.in);

261
ISC COMPUTER SCIENCE – XI

String st = “”;
int c = 0;
System.out.println(“Enter the string :”);
st = sc.nextLine();
for(int j = 0; j <= st.length() – 1; j++)
{
char ch = st.charAt(j);
int pch = ch;
if(pch >= 65 && pch <= 90)
{
c++;
}
}
System.out.print(“ Number of UpperCase Characters ” + c);
}
}
OUTPUT :
Enter the string : WORLD Environment Day
Number of UpperCase Characters 7
12. Write a program to input a string and convert Lower case letters to Upper case
letters and vice versa … ignore non alphabets.
Program Idea
• To convert an Upper case character to Lower case, add 32 to its ASCII value and
store it back in a character.
• Similarly to convert a character from Lower case to Upper case, subtract 32 from
its ASCII value.
• Ignore if the ASCII of the character does not belong to any of the alphabets range.
// Convert UpperCase to LowerCase and vice versa
import java.util.*;
public class clToggleCase
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
char ch1 = ‘’, ch2 = ‘’;
System.out.println(“Enter the string : ”);
st = sc.nextLine();

262
STRINGS AND LIBRARY METHODS

String nst = “”;


for(int j = 0; j <= st.length() – 1; j++)
{
ch1 = st.charAt(j);
if(ch1 >= 65 && ch1 <= 90)
{
ch2 = (char)(ch1 + 32);
}
else if(ch1 >= 97 && ch1 <= 122)
{
ch2 = (char)(ch1 – 32);
}
else
{
ch2 = ch1;
}
nst = nst + ch2;
}
System.out.println(“ The new string is :: ” + nst);
}
}
OUTPUT :
Enter the string : LAZY LeoParD
The new string is :: lazy lEOpARd
13. Write a program to input a string and print the next character for each alphabet
in a string … circular – A after Z.
Program Idea
• Similar to the above algorithm, pick each character.
• Verify if its ASCII value belongs to the range of alphabets.
• If it falls in the range then modify its ASCII value and add that to the new string.
• Special case of ‘Z’ as it is the last character of the range, its modification also
includes subtraction of 32 from the incremented value for bringing it back to the
alphabet range.
// Print the next character for each alphabet, circular A after Z
import java.util.*;
public class clCircularShift
{

263
ISC COMPUTER SCIENCE – XI

public void main()


{
Scanner sc = new Scanner(System.in);
String st = “”;
char ch1 = ‘’, ch2 = ‘’;
System.out.println(“Enter the string : ”);
st = sc.nextLine();
String nst = “”;
for(int j = 0; j <= st.length() – 1; j++)
{
ch1 = st.charAt(j);
if(ch1 >= 65 && ch1 <= 89)
{
ch2 = (char)(ch1 + 1);
}
else if(ch1 == 90)
{
ch2 = 65;
}
else if(ch1 >= 97 && ch1 <= 121)
{
ch2 = (char)(ch1 + 1);
}
else if(ch1 == 122)
{
ch2 = 97;
}
else
{
ch2 = ch1;
}
nst = nst + ch2;
}
System.out.println(“ The new string is :: ” + nst);
}
}

264
STRINGS AND LIBRARY METHODS

OUTPUT :
Enter the string : ZOOMY ZEBRAS
The new string is :: APPNZ AFCSBT
//ALTERNATE METHOD
//Print next character for each alphabet, circular A after Z
import java.util.*;
public class clCircularShift
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
char ch1 = ‘’, ch2 = ‘’;
System.out.println(“Enter the string :”);
st = sc.nextLine();
String nst = “”;
for(int j = 0; j <= st.length() – 1; j++)
{
ch1 = st.charAt(j);
if(ch1 >= ‘A’ && ch1 <= ‘Y’)
ch2 = ++ch1;
else if(ch1 == ‘Z’)
ch2 = ‘A’;
else if(ch1 >= ‘a’ && ch1 <= ‘Y’)
ch2 = ++ch1
else if(ch1 == ‘Z’)
ch2 = ‘a’;
else
ch2 = ch1;
nst = nst + ch2;
}
System.out.println(“The new string is :: ” + nst);
}
}
OUTPUT :
Enter the string : 321zyx 786BCA/.,
The new string is :: 321azy 786CDB/.,

265
ISC COMPUTER SCIENCE – XI

14. Write a program to input a string and shift the characters of a string by p
positions in the alphabet list and print the new string. Assume the alphabets are
placed circularly, i.e., A appears after Z.
Program Idea
• Similar to the above algorithm.
• Here the ASCII value changes by p.
• If the ASCII value crosses the range of alphabets then modify the value by either
adding or subtracting 32 to it.
• The following program handles only Upper case characters. Upgrade the program
to handle both Upper and Lower case.
// Shifting the characters p positions , circular A after Z
import java.util.*;
public class clCharShift
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
char ch1 = ‘’, ch2 = ‘’;
System.out.println(“Enter the string : ”);
st = sc.nextLine();
int p = 0;
System.out.println(“Enter number of character shift :”);
p = sc.nextInt();
String nst = “”;
for(int j = 0; j <= st.length() – 1; j++)
{
ch1 = st.charAt(j);
if(ch1 >= 65 && ch1 <= 90)
{
ch1 = (char)(ch1 + p);
if(ch1 > 90)
{
ch1 = (char)(ch1 – 26);
}

266
STRINGS AND LIBRARY METHODS

ch2 = (char)(ch1);
}
else
{
ch2 = ch1;
}
nst = nst + ch2;
}
System.out.println(“ The new string is :: ” + nst);
}
}
OUTPUT :
Enter the string : FUNNY FOX
Enter the number of character shift : 3
The new string is :: IXQQB IRA
15. Write a program to input a string and convert the 1st letter of each word to
upper case and the rest of the letters to lower case.
Program Idea
• Input the string in say st and convert it to lower case. [Assume only alphabets]
• Similar to the above algorithm, pick each character, in ch1.
• For each space, pick the next character, in ch2.
• Verify the ASCII value range of ch2.
 If it is between 97 and 122 then it is an alphabet in lower case and has to be
converted to upper case by subtracting 32 from it.
 Any other ASCII value indicates that it does not need conversion.
• Make a new string that adds either the modified character or the current character
accordingly.
// Title Case, 1st letter of each word in upper case, rest all in lower case
import java.util.*;
public class clFirstLetter
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
char ch1 = ‘’, ch2 = ‘’;

267
ISC COMPUTER SCIENCE – XI

System.out.println(“Enter the string :”);


st = sc.nextLine();
st = “ ” + st.toLowerCase();
// space added in the beginning to make each word to appear after a space
String nst = “”;
for(int j = 0; j <= st.length() – 1; j++)
{
ch1 = st.charAt(j);
if(ch1 == ‘ ’)
{
ch2 = (char)(st.charAt(j + 1) – 32);
nst = nst + ch1 + ch2;
j++;
}
else
{
nst = nst + ch1;
}
}
System.out.println(“The new string is :: ” + nst);
}
}
OUTPUT :
Enter the string : tHE LOnely plaNET
The new string is :: The Lonely Planet
16. Write a program to input a string and print the reverse of each word of a
sentence.
Program Idea
• Pick each word, and reverse it using a function String fnReverse(String wd).
• The function is called for each word. The reversed word is added to create a new
sentence.
• Refresh the variable storing the word each time.
import java.util.*;
public class clStringTest
{

268
STRINGS AND LIBRARY METHODS

String fnReverse(String wd)


{
String wr = “”;
for(int j = wd.length() – 1; j >= 0; j – –)
{
char ch = wd.charAt(j);
wr = wr + ch;
}
return wr;
}
void main()
{
String s1 = “”;
int len = 0;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a sentence that ends with ‘.’: ”);
s1 = sc.nextLine();
len = s1.length();
String word = “”, newst = “”, wv = “”;
for(int j = 0; j <= len – 1; j++)
{
char ch = s1.charAt(j);
if(ch != ‘’ && ch != ‘.’)
{
word = word + ch;
}
else
{
wv = fnReverse(word);
newst = newst + wv + “ ”;
word = “”; //refreshing word
}
}
System.out.println(“The modified sentence is : ” + newst);
}
}

269
ISC COMPUTER SCIENCE – XI

OUTPUT :
Enter a sentence that ends with ‘.’ : WINDHOEK IS CAPITAL OF NAMIBIA.
The modified sentence is : KEOHDNIW SI LATIPAC FO AIBIMAN
17. Write a program to input a string and print the longest word of a sentence.
Program Idea
• Assume maxwrd to store the value of the largest word.
• Pick each word and compare its length with maxwrd. If the current word is larger,
then overwrite maxwrd.
• Refresh the variable word each time.
import java.util.*;
public class clStringTest
{
public void fnLongestWord()
{
String sen = “”;
int len1 = 0, len2 = 0;
Scanner sc = new Scanner(System.in);
String word = “”, maxwrd = “”;
System.out.println(“Enter the sentence : ”);
sen = sc.nextLine();
for(int j = 0; j <= sen.length() – 1; j++)
{
char ch = sen.charAt(j);
if(ch != ‘ ’)
{
word = word + ch;
}
else
{
if(word.length() > maxwrd.length())
{
maxwrd = word;
}
word = “”; //refreshing word
}
}
270
STRINGS AND LIBRARY METHODS

System.out.println(“\n Longest word is : ” + maxwrd);


}
}
OUTPUT :
Enter the string : World Environment Day is on Fifth June.
Longest word is : Environment
18. Write a program to input a string and print the frequency of a substring.
Program Idea
• Input the sentence and the substring (say sen and smi), store their lengths in len1
and len2 respectively.
• In string sen, substring smi can be present any number of times.
• To search smi in sen—
 Pick len2 number of characters from sen each time in tmp and compare tmp
and smi for equality.
 The loop should stop at (len1 – len2) to pick the last set of len2 number of
characters.
• Assume sen = “the-arch-was-made-in-march” ; smi = “arch”
len1 = 26; len2 = 4
Need to pick 4 char from sen each time & to compare with smi.
The last set of 4 char will be at position 26 – 4 = 22.
Given is the list of substring in tmp for comparison with smi
the- he-a e-ar -arc arch rch- ch-w h-wa -was
was- as-m s-ma -mad …….. marc arch
import java.util.*;
class clTestString
{
public void fnFreqSubstr()
{
Scanner sc = new Scanner(System.in);
String sen = “”, smi = “”;
int len1 = 0, len2 = 0, frq = 0;
System.out.println(“Enter the sentence : ”);
sen = sc.nextLine();
System.out.println(“\n Enter the sub string : ”);
smi = sc.nextLine();

271
ISC COMPUTER SCIENCE – XI

len1 = sen.length();
len2 = smi.length();
for(int j = 0; j <= len1 – len2; j++)
{
String tmp = sen.substring(j, j + len2);
if(tmp.equalsIgnoreCase(smi) == true)
{
frq++;
}
}
System.out.println(“\n Frequency of” + smi + “ :: ” + frq);
}
}
OUTPUT :
Enter the sentence : never ever they saw such music fever
Enter the sub string : ever
Frequency of ever :: 3
19. Write a program to input a string sentence. Verify whether the longest word
ends with the shortest word or not.
Program Idea
l Input the string sentence.
l Find the largest and the smallest word in lngwrd & shrtwrd.
l String method endsWith() helps in verification.
// Verify if the Longest word ends with the shortest word in the string
import java.util.*;
public class clWordMatch
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “ ”;
String wrd = “”, lngwrd = “”, shrtwrd = “”;
System.out.print(“Enter the string : ”);
st = sc.nextLine();
st = st + “ ”;
shrtwrd = st;
for(int j = 0; j <= st.length() – 1; j++)
{

272
STRINGS AND LIBRARY METHODS

char ch1 = st.charAt(j);


if(ch1 == ‘ ’)
{
if(wrd.length() > lngwrd.length())
{
lngwrd = wrd;
}
if(wrd.length() < shrtwrd.length())
{
shrtwrd = wrd;
}
wrd = “”;
}
else
{
wrd = wrd + ch1;
}
}
System.out.println(“Longest word is : ” + lngwrd + “ Shortest word is :” +
shrtwrd);
if(lngwrd.endsWith(shrtwrd) == true)
{
System.out.println(“\n Longest word ” + lngwrd + “ ends with Shortest word”
+ shrtwrd);
}
else
System.out.println(“No match”);
}
}
OUTPUT :
Enter the string : BIGGER ELEPHANT SMALLER ANT
Longest word is : ELEPHANT Shortest word is : ANT
Longest word ELEPHANT ends with Shortest word ANT

Enter the string : ELEPHANT SMALL WHALE BIG


Longest word is : ELEPHANT Shortest word is : BIG
No match
273
ISC COMPUTER SCIENCE – XI

20. Write a program to make a new string by swapping the first and the last char
of each word.
Program Idea
l Pick each word, modify it and make a new string.
l A function takes a word, modifies it and returns it.
l To make the new word, pick the last character, add all characters from position 2
to second last to it then add character at position 1.
// Interchange the first and the last letter of each word
import java.util.*;
public class clLetterSwap
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”, wrd= “”, nwrd = “”, nst = “”;
System.out.println(“Enter the string : ”);
st = sc.nextLine();
st = st + “ ”;
for(int j = 0; j <= st.length() – 1; j++)
{
char ch1 = st.charAt(j);
if(ch1 == ‘’)
{
nwrd = fnSwapLetter(wrd); // modify the word by using the function.
nst = nst + “” + nwrd;
wrd = “”;
}
else
{
wrd = wrd + ch1;
}
}
System.out.println(“\n Modified String :: ”+ nst);
}

274
STRINGS AND LIBRARY METHODS

String fnSwapLetter(String ww)


{
int len = ww.length();
String nw = “”;
nw = ww.charAt(len – 1) + ww.substring(1, len – 1) + ww.charAt(0);
return nw;
}
}
OUTPUT :
Enter the string : DENSE FOREST OF CONGO
Modified String :: EENSD TORESF FO OONGC
21. Write a program to input a sentence and verify if it is a V-Free sentence or not.
A sentence is called V-Free if it contains at least one word that does not contain any
vowel in it.
Program Idea
l Pick up the characters to make the words.
l Verify whether any word is such that it contains no vowels.
l A function fnHasNoVowel() verifies that a string contains no vowels.
l Each word is sent to the function. True result for any word, makes the sentence
V-Free.
// V-Free sentence
import java.util.*;
public class clVFree
{
public void main()
{
Scanner sc = new Scanner(System.in);
String st = “”;
String wrd = “”;
boolean vfree = true;
System.out.println(“Enter the string :”);
st = sc.nextLine();
st = st + “ ”;
for(int j = 0; j <= st.length() – 1; j++)
{

275
ISC COMPUTER SCIENCE – XI

char ch1 = st.charAt(j);


if(ch1 == ‘ ’)
{
vfree = fnHasNoVowel(wrd);
System.out.println(“\n Word :: ” + wrd + “ \t\t VFree Status :: ” +
vfree);
wrd = “”;
if(vfree == true)
{
break;
}
}
else
{
wrd = wrd + ch1;
}
}
System.out.println(“\n Given string is V-Free :: ” + vfree);
}
boolean fnHasNoVowel(String ww)
{
boolean hasNoVowel = true;
ww = ww.toUpperCase();
for(int j = 0; j <= ww.length() – 1; j++)
{
char ch = ww.charAt(j);
if(ch == ‘A’ || ch == ‘E’ || ch == ‘I’ || ch == ‘O’ || ch == ‘U’)
{
hasNoVowel = false;
break;
}
}
return hasNoVowel;
}
}

276
STRINGS AND LIBRARY METHODS

OUTPUT :
Enter the string : The Summer night was Cold
Word :: The VFree Status :: false
Word :: Summer VFree Status :: false
Word :: night VFree Status :: false
Word :: was VFree Status :: false
Word :: Cold VFree Status :: false
Given string is V-Free :: false
Enter the string : The Winter Sky was Blue.
Word :: The VFree Status :: false
Word :: Winter VFree Status :: false
Word :: Sky VFree Status :: true
Given string is V-Free :: true

OTHER LIBRARY METHODS

Character Wrapper Class


The methods of this class perform operations on characters. Some methods either
return a boolean result or any character. The method names indicate their operation.
Method detail Program Syntax
boolean isDigit(char ch) char ch = ‘M’;
boolean dc = Character.isDigit(ch);
System.out.print(“\n dc is” + dc); //value of dc is false
boolean isLetter(char ch) char ch = ‘n’;
boolean lc = Character.isLetter(ch);
System.out.print(“\n lc is” + lc); //lc is true
boolean isLetterOrDigit char ch = ‘8’;
(char ch) boolean cld = Character.isLetterOrDigit(ch);
System.out.print(“\n cld is” + cld); //cld is true

boolean isLowerCase(char char ch = ‘K’;


ch) boolean rc = Character.isLowerCase(ch);
System.out.print(“\n rc is” + rc); // rc is false

boolean isUpperCase(char char ch = ‘W’;


ch) boolean uc = Character.isUpperCase(ch);
System.out.print(“\n uc is” + uc); //uc is true

277
ISC COMPUTER SCIENCE – XI

char toLowerCase(char ch) char ch = ‘M’;


char rc = Character.toLowerCase(ch);
System.out.print(“\n rc is” + rc); //rc is m
char toUpperCase(char ch) char ch = ‘n’;
char pc = Character.toUpperCase(ch);
System.out.print(“\n pc is” + pc); //rc is N

MATHEMATICAL LIBRARY FUNCTIONS


pow(x, y) log(x) sqrt(x) ceil(x) floor(x) rint(x)
abs(x) max(a, b) min(a, b) random() sin(x) cos(x) tan(x)
Math class is present under the package java.lang.
The following table shows the details of certain Mathematic and Logical methods :
Method detail Program Syntax
double pow(double x, double y) double yy = Math.pow(p, q);
It returns the value of a variable to the power
of another.
Example : double g = Math.pow(3.2, 2.1);
System.out.print(“ g =” + g);
// g = 11.503101568235094
double log(double a) double lg = Math.log(x);
It returns the natural logarithm (base e) of a

number.
Example :
double g = Math.log(12);
System.out.print(“ g =” +g);
//g = 2.4849066497880004
double sqrt(double a) double sq = Math.sqrt(x);
It returns the positive square root of a number.
Example :
double q = Math.sqrt(25);
// q = 5.0
double q = Math.sqrt(20);
// q = 4.47213595499958
double ceil(double a) double cl = Math.ceil(x);
It returns the nearest next integer value.
Example :
double g = Math.ceil(8.4);

278
STRINGS AND LIBRARY METHODS

double floor(double a) double fl = Math.floor(x);


It returns the nearest previous integer value.
Example :
double g = Math.floor(8.5)
// g = 8.0
// g = 9
double rint(double a) double rt = Math.rint(x);
It returns the nearest integer value.
Example :
double g = Math.rint(8.4);
// g = 8
double g = Math.rint(8.7);
// g = 9
int abs(int a) int ab = Math.abs(p1);
abs() is an overloaded function which works for
data types like int/long/float/double as well.
So, long nb = Math.abs(p2);
is also valid. Similarly, method abs() is applicable
on other data types as well.
Example :
int b = Math.abs(–9);
// b = 9
int max(int a, int b) int gt = Math.max(p1, q1);
max() is an overloaded function which works for
data types like int/long/float/double as well.
long ht = Math.max(p2, q2); // is valid
Example :
int y = Math.max(23, 45);
// y = 45
int min(int a, int b) int st = Math.min(p1, q1);
min() is also an overloaded function which works
for other data types like int/long/float/double
as well.
Example :
int t = Math.min(23, 45);
// t = 23
double random() double rn = Math.random();
It returns a positive random number lying

between 0.0 and 1.0
Example :
double m = Math.random();
// m = 0.02

279
ISC COMPUTER SCIENCE – XI

double sin(double a) double sn = Math.sin(x);


It returns the trignometric sine value of an angle
passed as parameter.
Example :
double g = Math.sin(45);
// g = 0.85090352453
double cos(x) double cn = Math.cos(x);
It returns the trignometric cosine value of an
angle passed as parameter,
Example :
double g = Math.cos(45);
// g = 0.52532198881
double tan(x) double tn = Math.tan(x);
It returns the trignometric tangent value of an
angle passed as parameter.
Example :
double g = Math.tan(45);
//g = 1.61977519054

SCANNER CLASS

Method detail Program Syntax


int nextInt() Returns an integer.
Scanner sc = new Scanner(System.in);
int d = sc.nextInt();
int nextDouble() Returns a double.
double db = sc.nextDouble();
int nextFloat() Returns the next floating (number).
float ft = sc.nextFloat();
int next() Returns the next word.
String sw = sc.next();
int nextLine() Returns the next sentence.
String st = sc.nextLine();

ARRAY OF STRINGS
An array of strings contain a list of strings. Each element of the array possesses
properties of a string. Shown below is an illustration of a string array.

280
STRINGS AND LIBRARY METHODS

Example 1 : Create a String array, fill and print it.


public class clStringArray
{
void fnStAr()
{
String stAr[ ] = {“January”, “March”, “May”, “July”, “September”};
for(int j = 0; j <= stAr.length – 1; j++)
{
System.out.println(stAr[j]);
}
}
}
Example 2 : Create a String array. Input values in it and print it. Also print the
length of each string.
import java.util.*;
public class clStringArray
{
void fnStAr()
{
Scanner sc = new Scanner(System.in);
String stAr[ ] = new String [5];
for(int j = 0; j <= stAr.length – 1; j++)
{
System.out.println(“Enter a string :: ”);
stAr[j] = sc.nextLine();
}
System.out.print(“\f”); //clearing output screen
for(int j = 0; j <= stAr.length – 1; j++)
{
int len = stAr[j].length();
System.out.println(stAr[j] + “ ” + len);
}
}
}

281
ISC COMPUTER SCIENCE – XI

OUTPUT : (Assuming the same set of values for input as Example 1)


January 7
March 5
May 3
July 4
September 9

WORKED PROGRAMS ON STRING ARRAYS

1. Fill an array of 10 strings. Print the 1st letter of each string.


2. Fill an array of 10 strings. Count and print how many of them end with character
‘a’ and also print them.
3. Fill an array of n strings. Print the longest string.
4. Fill an array of n strings. Print those strings whose length is smaller than the
length of the last string.
5. Store the name of 10 Indian cities in an array of strings. Input the name of a city
and search that in the array.
6. Input the name of n volcanoes. Arrange them in alphabetical order and print
them.
[(i) Germany (ii) Argentina (iii) Japan (iv) Netherlands (v) Brazil (vi) Spain
(vii) Portugal (viii) Columbia (ix) Italy (x) France (xi) Nigeria (xii) England]
7. Input a string sentence. Print the words in reverse order and also arrange the
words lexicographically (ascending order of alphabets).
8. In a string array store the name of n books. Store the author name in another
string array. Input the name of a book and print the name of the author.
9. Input the name of 10 students in a string array. Store the age of the students in
another integer array. Find the average age. Print the names of those students
whose age is less than the average age.
10. Fill a string array with 10 string sentences. Print the strings such that alternate
strings are reversed.
Program Solutions :
1. Fill an array of 10 strings. Print the 1st letter of each string.
import java.util.*;
public class clStringArray
{
void fnStAr()
{

282
STRINGS AND LIBRARY METHODS

Scanner sc = new Scanner(System.in);


String stAr[ ] = new String [10];
for(int j = 0; j <= stAr.length – 1; j++)
{
System.out.println(“Enter a string :: ”);
stAr[j] = sc.nextLine();
}
for(int j = 0; j <= stAr.length – 1; j++)
{
System.out.print(stAr[j].charAt(0) + “ ”);
}
}
}
OUTPUT :
Enter a string :: January
Enter a string :: February
Enter a string :: March
Enter a string :: April
Enter a string :: May
Enter a string :: June
Enter a string :: July
Enter a string :: August
Enter a string :: September
Enter a string :: October
J F M A M J J A S O
2. Fill an array of 10 strings. Count and print the strings ending with character ‘a’
and also print them.
import java.util.*;
public class clStringArray
{
void fnStAr()
{

283
ISC COMPUTER SCIENCE – XI

Scanner sc = new Scanner(System.in);


String stAr[ ] = new String [10];
int count = 0;
//Input
for(int j = 0; j <= stAr.length – 1; j++)
{
System.out.print(“Enter string num” + (j + 1) + “ :: ”);
stAr[j] = sc.nextLine();
}
//Count and Print
System.out.println(“Strings that end with letter ‘a’ are : ”);
for(int j = 0; j <= stAr.length – 1; j++)
{
int len = stAr[j].length(); //finding the length of each string
char ch = stAr[j].charAt(len – 1); //finding the last character
if(ch == ‘a’)
{
System.out.println(stAr[j]);
count++;
}
}
System.out.println(“Number of strings that end with ‘a’ are” + count);
}
}
OUTPUT :
Enter string num 1 :: Barcelona
Enter string num 2 :: Venice
Enter string num 3 :: Innsbruck
Enter string num 4 :: Pisa
Enter string num 5 :: Vienna
Enter string num 6 :: Moscow
Enter string num 7 :: Milan
Enter string num 8 :: Roma
Enter string num 9 :: Lucerne
Enter string num 10 :: Odessa

284
STRINGS AND LIBRARY METHODS

Strings that ends with letter ‘a’ are :


Barcelona
Pisa
Vienna
Roma
Odessa
Number of strings that ends with ‘a’ are 5.
3. Fill an array of n strings. Print the longest string.
import java.util.*;
public class clStringArray
{
void fnStAr()
{
Scanner sc = new Scanner(System.in);
String stAr[ ] = new String [10];
int count = 0;
//Input
for(int j = 0; j <= stAr.length – 1; j++)
{
System.out.println(“Enter string num” + (j + 1) + “ :: ”);
stAr[j] = sc.nextLine();
}
// Finding the longest string
int max = stAr[0].length();
int maxp = 0;
for(int j = 1; j <= stAr.length – 1; j++)
{
if(max < stAr[j].length())
{
max = stAr[j].length();
maxp = j;
}
}

285
ISC COMPUTER SCIENCE – XI

// Printing the longest string


System.out.println(“The longest string is” + stAr[maxp]);
}
}
OUTPUT :
Enter string num 1 :: Pompeii
Enter string num 2 :: Scotland
Enter string num 3 :: Masaimaraa
Enter string num 4 :: Zimbabwe
Enter string num 5 :: Mexico
Enter string num 6 :: Canada
Enter string num 7 :: Tokyo
Enter string num 8 :: Salzburg
Enter string num 9 :: Linz
Enter string num 10 :: Greenland
The longest string is Masaimaraa
4. Fill an array of n strings. Print those strings whose length is smaller than the
length of the last string.
import java.util.*;
public class clStringArray
{
void fnStAr()
{
Scanner sc = new Scanner(System.in);
int n;
System.out.println(“Enter the number of strings : ”);
n = sc.nextInt();
String flush = sc.nextLine(); // to clear the buffer before next string input
String stAr[ ] = new String [n];
//Input
for(int j = 0; j <= n – 1; j++)
{
System.out.println(“Enter string num” + (j + 1) + “ :: ”);
stAr[j] = sc.nextLine();
}

286
STRINGS AND LIBRARY METHODS

// Finding the length of the last string


int min = stAr[n – 1].length();
System.out.println(“Strings whose length is smaller than the last string are ”);
for(int j = 0; j <= n – 1; j++)
{
if(stAr[j].length() < min)
{
System.out.println(stAr[j]);
}
}
}
}
OUTPUT :
Enter the number of strings : 5
Enter string num 1 :: Vesuvius
Enter string num 2 :: Fujiama
Enter string num 3 :: Hekla
Enter string num 4 :: Rainer
Enter string num 5 :: Kilauea
Strings whose length is smaller than the last string are :
Hekla
Rainer
5. Store the name of 10 Indian cities in an array of strings. Input the name of a
city and search that in the array.
import java.util.*;
public class clStringArray
{
void fnStAr()
{
Scanner sc = new Scanner(System.in);
String stCities[ ] = {“PUNE”, “DISPUR”, “AGRA”, “JAIPUR”, “VIZAG”
“MUMBAI”, “DELHI”, “MEERUT”, “KOVALAM”, “PUDUCHERRY”};
String stNewCity = “”;
int j = 0;
System.out.println(“Enter the city to be searched :”);
stNewCity = sc.nextLine();
287
ISC COMPUTER SCIENCE – XI

for(j = 0; j <= stCities.length – 1; j++)


{
if(stNewCity.equalsIgnoreCase(stCities[j]) == true)
{
System.out.println(“City name found.”);
break;
}
}
if(j == stCities.length)
{
System.out.println(“City name Not found.”);
}
}
}
OUTPUT :
Enter the city to be searched : Puducherry
City name found.
Enter city to search : Nagpur
City name Not found.
6. Input the name of n volcanoes. Arrange them in alphabetical order and print
them.
import java.util.*;
public class clStringArray
{
void fnStAr()
{
Scanner sc = new Scanner(System.in);
int n;
System.out.println(“Enter the number of volcanoes : ”);
n = sc.nextInt();
String flush = sc.nextLine(); // to clear the buffer, flush contains
String stCountry[ ] = new String [n];
//Input
for(int j = 0; j <= n – 1; j++)
{

288
STRINGS AND LIBRARY METHODS

System.out.println(“Enter volcano num” + (j + 1) + “ :: ”);


stCountry[j] = sc.nextLine();
}
//Sorting using Selection Sort algorithm
for(int r = 0; r <= stCountry.length – 2; r++)
{
String stMin = stCountry[r];
int minp = r;
for(int j = r + 1; j <= stCountry.length – 1; j++)
{
if(stCountry[j].compareTo(stMin) < 0)
{
stMin = stCountry[j];
minp = j;
}
}
// Swap
String tmp = stCountry[r];
stCountry[r] = stCountry[minp];
stCountry[minp] = tmp;
}
System.out.println(“\nThe volcano names in Alphabetical order are : ”);
for(int j = 0; j <= n – 1; j++)
{
System.out.print(“ ” + stCountry[j]);
}
}
}
OUTPUT :
Enter the number of countries : 6
Enter country num 1 :: Vesuvius
Enter country num 2 :: Fujiyama
Enter country num 3 :: Kilauea
Enter country num 4 :: Fuji
Enter country num 5 :: Skaftar
Enter country num 6 :: Pinatubo
289
ISC COMPUTER SCIENCE – XI

The volcano names in Alphabetical order are :


Fuji Fujiyama Kilauea Pinatubo Skaftar Vesuvius
7. Input a string sentence. Print the words in reverse order and also arrange them
lexicographically (ascending order of alphabets).
PROGRAM IDEA
• Extract the words of the string.
• Put the words of the string in an array.
• Sort the array to arrange the words lexicographically. [As done in the above
program num 6.]
import java.util.*;
public class clTest
{
void main()
{
Scanner sc = new Scanner(System.in);
String sentence = new String();
String word = “”;
System.out.println(“Enter sentence upto 10 words :”);
sentence = sc.nextLine();
sentence += “ ”;
String stArSen[ ] = new String[10];
int k = 0;
for(int j = 0; j <= sentence.length() – 1; j++)
{
char ch = sentence.charAt(j);
if(ch == ‘ ’)
{
stArSen[k++] = word;
word = “”;
}
else
{
word += ch;
}
}

290
STRINGS AND LIBRARY METHODS

// The words in a String Array


for(int j = 0; j <= k – 1; j++)
{
System.out.print(stArSen[j] + “ ”);
}
//Sort the array to arrange the words lexicographically as done in prog. 6
}
}
OUTPUT :
Enter sentence : Hard work is the key.
Hard work is the key.
8. In a string array store the name of n books. Store the author name in another
string array. Input the name of a book and print the name of the author.
import java.util.*;
public class Book
{
void main()
{
int n = 0, i;
String bn;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number of books :”);
n = sc.nextInt();
String tmp = sc.nextLine(); //to flush the memory
String BookName[] = new String [n];
String Author[] = new String [n];
for(i = 0; i <= n – 1; i++)
{
System.out.print(“Enter the Name of Book number” + (i + 1) + “ : ”);
BookName[i] = sc.nextLine();
System.out.print(“Enter the Name of the author :”);
Author[i] = sc.nextLine();
}
System.out.print(“Now enter the name of a book and get to know it author’s
name :”);

291
ISC COMPUTER SCIENCE – XI

bn = sc.nextLine();
boolean found = false;
for(i = 0; i < n; i++)
{
if(bn.equals(BookName[i]) == true)
{
found = true;
System.out.print(“Name of the author is :” + Author[i]);
}
}
if(found == false)
{
System.out.print(“Sorry No such book present in this list.”);
}
}
}
OUTPUT :
Enter the number of books : 8
Enter the Name of Book number 1 : Harry Potter
Enter the Name of the author : J. K. Rowling
Enter the Name of Book number 2 : Charlie and the Chocolate Factory
Enter the Name of the author : Roald Dahl
Enter the Name of Book number 3 : Tom Gates
Enter the Name of the author : Liz Pichon
Enter the Name of Book number 4 : Diary of a Wimpy Kid
Enter the Name of the author : Jeff Kinney
Enter the Name of Book number 5 : Swami and Friends
Enter the Name of the author : R. K. Narayan
Enter the Name of Book number 6 : The Hardy Boys
Enter the Name of the author : Franklin W. Dixon
Enter the Name of Book number 7 : Asterix
Enter the Name the author : Rene Goscinny
Enter the Name of Book number 8 : The Guide
Enter the Name of the author : R. K. Narayan
Now enter the name of a book and get to know its author’s name : Tom Gates
Name of the author is : Liz Pichon

292
STRINGS AND LIBRARY METHODS

9. Input the name of n students in a string array. Store the age of the students in
another integer array. Find the average age. Print the names of those students whose
age is less than the average age.
import java.util.*;
public class Age
{
void main()
{
int n = 0, i;
double sum = 0, avg;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number of student :”);
n = sc.nextInt();
String tmp = sc.nextLine(); //to flush the memory
String StName[] = new String [n];
int StAge[] = new int [n];
for(i = 0; i <= n – 1; i++)
{
System.out.print(“Enter the Name of Student number” + (i + 1) + “ : ”);
StName[i] = sc.nextLine();
System.outprint(“Enter the age of the student : ”);
StAge[i] = sc.nextInt();
temp = sc.nextLine();
}
for(i = 0; i < n; i++)
{
sum = sum + StAge[i];
}
avg = sum/n;
System.out.println(“Names of students whose age is below average :”);
for(i = 0; i < n; i++)
{
if(StAge[i] < avg)
{

293
ISC COMPUTER SCIENCE – XI

System.out.println(StName[i]);
}
}
}
}
OUTPUT :
Enter the number of students : 5
Enter the Name of Student number 1 : Vaishali
Enter the age of the student : 15
Enter the Name of Student number 2 : Teyasha
Enter the age of the student : 14
Enter the Name of Student number 3 : Rakkishore
Enter the age of the student : 16
Enter the Name of Student number 4 : Pronoy
Enter the age of the student : 13
Enter the Name of Student number 5 : Narendra
Enter the age of the student : 17
Names of students whose age is below average :
Teyasha
Pronoy
10. Fill a string array with 10 string sentences. Print the strings such that alternate
strings are reversed.
import java.util.*;
public class clTest
{
void main()
{
Scanner sc = new Scanner(System.in);
String stSen[ ] = new String[10];
for(int j = 0; j <= stSen.length – 1; j++)
{
System.out.println(“Enter sentence num” + (j + 1) + “ : ”);
stSen[j] = sc.nextLine();
}
for(int j = 0; j <= stSen.length – 1; j++)
{
294
STRINGS AND LIBRARY METHODS

if(j % 2 == 0)
System.out.println(stSen[j]);
else
System.out.println(“\t” + fnReverse(stSen[j]));
}
}
String fnReverse(String s)
{
String s2 = “”;
for(int j = s.length() – 1; j >= 0; j – –)
{
s2 = s2 + s.charAt(j);
}
return s2;
}
}
OUTPUT :
Enter sentence num 1 : Mount Pinatubo in Philippines
Enter sentence num 2 : Vesuvius in Italy
Enter sentence num 3 : Krakatau in Indonesia
Enter sentence num 4 : Katmai in Alaska
Enter sentence num 5 : St Helens USA
Enter sentence num 6 : El Chichon in Mexico
Enter sentence num 7 : Skaftar in Iceland
Enter sentence num 8 : Asama in Japan
Enter sentence num 9 : Hekla in Iceland
Enter sentence num 10 : Surtsey in Iceland
Mount Pinatubo in Philippines
ylatI ni suivuseV
Krakatau in Indonesia
aksalA ni iamtaK
St Helens USA
ocixeM ni nohcihC lE
Skaftar in Iceland
napaJ ni amasA
Hekla in Iceland
dnalecI ni yestruS
295
ISC COMPUTER SCIENCE – XI

EXERCISE

1. Answer the following :


(a) Write any three differences between Character and String in Java.
(b) Name the String library method that performs the following :
(i) Removes the spaces from front and end of a string.
(ii) Adds one string behind another.
(iii) Compares equality irrespective of the case.
(iv) Compares two strings and returns their ASCII difference.
(v) Converts data of any type to string.
2. What will the following methods return :
(a) String s4 = “MAHABALIPURAM”;
(i) s4.endsWith(“PURA”);
(ii) s4.replace(‘A’, ‘O’);
(iii) s4.replace(“PURAM”, “SHWAR”)
(iv) s4.equals(“mahabalipuram”);
(b) String s8 = “JUPITER”; String s9 = “URANUS”
(i) s8.concat(“TITAN”);
(ii) s8.toLowerCase();
(iii) s8.substring(2)
(iv) s8.charAt(s9.lastIndexOf(‘U’));
3. Given the following codes ……..
Code I.
boolean fnCano(String ww1, String ww2)
{
int len1 = ww1.length(), len2 = ww2.length();
String st3 = ww1.substring((len1 – len2));
if(st3.equals(ww2) == true)
{
return true;
}
return false;
}

296
STRINGS AND LIBRARY METHODS

What will the method fnCano() return if :


(a) ww1 = “SPARK” ; ww2 = “DARK”
(b) ww1 = “A lot of ice in Iceland” ; ww2 = “land”
(c) ww1 = “volcanoes are violent” ; ww2 = “volcano”
(d) What is the AIM of the method fnCano() ?
Code II.
String fnTaly(String ww)
{
int len1 = ww.length();
String nw = “”;
nw = nw + ww.charAt(len1 – 1);
for(int j = 1; j <= len1 – 2; j++)
{
nw = nw + ww.charAt(j);
}
nw = nw + ww.charAt(0);
return nw;
}
What will the method fnTaly() return if :
(a) ww = “Leaf”
(b) ww = “work on”
(c) What is the AIM of the method fnTaly() ?
Code III.
boolean fnWell(String nm)
{
String nv = “aeiouAEIOU”;
for(int j = 1; j <= nv.length() – 1; j++)
{
if(nm.indexOf(nv.charAt(j)) != –1)
{
System.out.print(nv.charAt(j));
return true;
}
}

297
ISC COMPUTER SCIENCE – XI

return false;
}
What will the method fnWell() print and return if :
(a) nm = “TRIANGLE”
(b) nm = “skylrk”
(c) nm = “wbrown”
(d) What is the AIM of the method fnWell() ?
Code IV.
String fnTram(String sa, String pa)
{
String na = “”;
int ten = Math.min(sa.length(), pa.length());
for(int j = 0; j <= ten – 1; j++)
{
na = na + pa.charAt(j) + sa.charAt(j);
}
return na;
}
What will the method fnTram() return if :
(a) sa = “ab” ; pa = “pqrs”
(b) sa = “london” ; pa = “pisa”
(c) What will happen if the following modification is done in fnTram() –
int ten = Math.max(sa.length(), pa.length());
Code V.
void fnRow(String sen)
{
int len = sen.length();
do
{
int d = sen.lastIndexOf(‘ ’);
System.out.println(sen.substring(0, d) + “ ** ** ** ” + sen.substring(d));
sen = sen.substring(0, d);

298
STRINGS AND LIBRARY METHODS

len = sen.length();
}while(len > 0);
}
What will the method fnRow() print if :
(a) sen = “Santorini errupted in Greece”
(b) sen = “The water was pure and clear”
(c) What will happen if the following modification is done in fnRow() –
System.out.println(sen.substring(d));
Code VI.
void fnZing(String pk[], char sk)
{
for(int j = 0; j <= pk.length – 1; j++)
{
if(pk[j].charAt(0) == sk)
{
System.out.print(pk[j] + “ ”);
}
}
}
void fnZ()
{
String k1[] = {“Mica”,“Home”,“Times”,“Height”,“Ropo”,“Honabi”};
char c2 = ‘H’;
fnZing(k1, c2);
}
What will be the output if fnZ() is invoked ?
Code VII.
void fnKrop(String pk[], String sk)
{
for(int j = 0; j <= pk.length – 1; j++)
{

299
ISC COMPUTER SCIENCE – XI

if(pk[j].charAt(pk[j].length() – 1) == sk.charAt(sk.length() – 1))


{
System.out.print(pk[j] + “ ”);
}
}
}
void fnK()
{
String k1[] = {“Mica”,“Home”,“Time”,“Height”,“Rope”,“Honabi”};
String k2 = “Tree”;
fnKrop(k1, k2);
}
What will be the output if fnK() is invoked ?
qq

300
DATA FILE
12 HANDLING

l Need for data file


l Stream

Byte
v Streams
Character
v Streams
Standard Streams
v

l Operations on Files

NEED FOR DATA FILE


Data is one of the most integral parts of a program. Data has to be read and data has
to be written by a program for the purpose of doing any kind of task.
There are some cases where the data to be read and written need not be preserved,
they are temporarily taken from the user and is lost after the program execution is over.
On the other hand there are some cases where the data to be used, has to be preserved
for a longer period of time. Also, there are some cases where the program output is very
long and do not fit in the console. It is then when data files are required.
Data files are text files that are placed in the computer memory and are used to store
data. A Java program can read data from a data file and can write data in a data file.
The advantages of data files are :
• They store the data in text files in the computer memory.
• They have a huge capacity of data storage.
• They can be accessed even without the Java program.

STREAM
A stream can be defined as a sequence of data. There are two kinds of Streams :
• InputStream : The InputStream is used to read data from a source.
• OutputStream : The OutputStream is used to write data to a destination.
ISC COMPUTER SCIENCE – XI

Source Program Destination

Byte Streams
Java byte streams are used to perform input and output of bytes where each byte
has 8-bits.
To perform these operations the following classes are used :
• FileInputStream.
• FileOutputStream.
Following is an example which makes use of these two classes to copy an input file
into an output file. The contents of data file “myFriends.txt” is getting copied into another
data file “yourFriends.txt”.
import java.io.*;
class clFileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream Fin = new FileInputStream(“myFriends.txt”);
FileOutputStream Fout = new FileOutputStream(“yourFriends.txt”);
int c;
while((c = Fin.read()) != –1)
{
Fout.write(c);
}
Fin.close();
Fout.close();
}
}
Now let’s have a file myFriends.txt with the following content :
Sunita Anil Lina Kalyan Sreemanty
When the above program is compiled and executed, it creates the File Output Stream
object Fout with the value as “yourFriends.txt” in write mode and copies the contents
from the File Input Stream object Fin with the value as “myFriends.txt”.

Note :
l The entire input file gets copied on to the output file.

302
DATA FILE HANDLING

Character Streams
Java Character streams are used to perform input and output for 16-bit unicode. To
perform reading and writing in files the following character stream classes are used :
• FileReader. 
• FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but the major difference is that FileReader reads two bytes at a time
and FileWriter writes two bytes at a time.
We can re-write the above example, using these two classes to copy an input file
(having unicode characters) into an output file :
Example :
public static void main(String args[]) throws IOException
{
FileReader Fin = new FileReader(“myFriends.txt”);
FileWriter Fout = new FileWriter(“yourFriends.txt”);
int c;
while((c = Fin.read()) != –1)
{
Fout.write(c);
}
Fin.close();
Fout.close();
}
Now let’s have a file myFriends.txt with the following content :
Manish Poornima Ajit Sujoy Pritha
When the above program is compiled and executed, it creates the File Writer object
Fout with the value as “yourFriends.txt” in write mode and copies the contents from the
File Reader object Fin with the value as “myFriends.txt”.

Note :
l The entire input file gets copied on to the output file.

Standard Streams
Java provides three standard streams for data input and output :
• Standard Input : This is used to supply data to the user’s program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output : This is used to print the data produced by the user’s program
and usually a computer monitor is used for standard output stream and
represented as System.out.
303
ISC COMPUTER SCIENCE – XI

• Standard Error : This is used to output the error data produced by the user’s
program and usually a computer monitor is used for standard error stream and
represented as System.err.
BufferedReader and BufferedWriter
BufferedReader class in Java performs reading of text from a character-input stream.
Buffered input streams read data from a memory area known as a buffer. The buffer size
may be specified. If not, the default size, which is predefined, may be used.
In the same way, BufferedWriter class in Java performs writing of text on a character-
output stream. Buffered output streams write data from a memory area known as a buffer.

OPERATIONS ON FILES
In this section, we will look into the various operations on data files such as :
Creating; Closing; Reading; Writing; Appending; Searching;
Shown below are the syntax statements for opening a file, using String variable
filename :
For creating a new file to write into, open the file using FileWriter
FileWriter fr = new FileWriter(filename);
For Reading from a file, open the file using FileReader.
FileReader fr = new FileReader(filename);
To append data in an existing file, open the existing file using FileWriter with
append status true. It appends data at the end of existing data.
FileReader fr = new FileReader(filename, true);
For closing a file :
FileObject.close();

Note :
l Always close the data file after the file operation is over.

The following programs demonstrate the process and working on data files.
Program List :
1. Perform the operation of creating a file and writing data in it and then closing it
and another operation of opening a file and reading data from it.
Use the following methods :
void fnWriteInFile() : Create a file named “MyFriends.txt”. Take data from
standard input and write that data in the file and finally close the file.
void fnReadFromFile() : Open file named “MyFriends.txt”. Read data from the
file and print it on the standard output and then finally close the file.
Write the controlling method main().
2. Create a file named “Salesmen.txt” and fill it with the names of 10 salesmen and
their order booked amount. After data input, close the file.
304
DATA FILE HANDLING

In another operation, open the file “Salesmen.txt” and search and print the names
of those salesmen whose order booked amount is more than 75000.
3. Create a file named “Cars.txt” and fill it with the names and cost of n cars.
In another operation, open the file “Cars.txt” and search and print the names of
those cars whose cost is more that Rs x. [Input n, x]
4. Create a file named “ContinentCountryCap.txt” and fill it with N country names,
their capitals and the continents of the world.
In another operation, input a continent name and create another data file (by the
name of the continent) in which transfer the countries and capitals present in it
from the 1st file “CountryCapContinent.txt”. 
5. Create a file named “Euro.txt” in which fill the names of the countries that are
playing the Euro cup along with their captain’s name and the total goals scored
by that country in the entire tournament. Transfer the names of those countries
to another file “Golden.txt”, which scored more than 5 goals.  
6. Create a file named Currency.txt and store the famous currencies of the world
along with their country’s name and their rupees equivalent. In the program,
input the rupees amount and the desired currency and print the equivalent
amount in that currency. 
7. Create a file named Rainfall.txt and store the annual approximate rainfall (in
inches) collected in a year in various cities across the world. Read the data from
the file. Print the cities which get rainfall below 50 inch.
8. Create a file named Airplane.txt and store the Names and Nationality of the
passengers of a given flight. Also store the weight of luggage taken by each
passenger.[Assume passenger names are unique.]
In another operation, input a nationality and create another text file of that name.
From the first file, input data and write the names and luggage weight of the
passengers of the specified nationality accordingly in the second file.
9. A music store was auctioning some of its old music instruments. Create a file
named Instrument.txt and store the Name, cost price and sell price of the music
instruments on auction.
In another operation, create another text file named Profit.txt in which transfer
the names of those instruments which incurred profit on auction, also write the
amount of profit incurred.
10. Input the name of a Country and the name of its Capital. Create a text file by the
name of the capital. Input names of various cities of that country and the distance
(in km) between the capital city and each of the other cities.
In another operation, create a file named Parcel.txt in which write the name of
the other city and the minimal parcel cost depending on the distance from the
capital as per the given chart :

305
ISC COMPUTER SCIENCE – XI

City Distance from Capital (d) Min Parcel Cost (c)


d <= 100 100
d > 100 && d <= 300 200
d > 300 && d <= 500 300
d > 500 400
Program Solution :
1. import java.io.*;
// Input 5 names and store them in a data file named “MyFriends.txt”.
public class HandlingFile
{
public void fnWriteInFile() throws IOException
{
String fileName = “MyFriends.txt”;
String name = “ ”, pnum = “ ”;
BufferedReader buf = new BufferedReader(new InputStreamReader
(System.in));
FileWriter fw = new FileWriter(“MyFriends.txt”, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
for(int j = 1; j <= 5; j++)
{
System.out.print(j + “. Enter name .. ”);
name = buf.readLine();
System.out.print(“Enter pnum .. ”);
pnum = buf.readLine();
pw.println(name);
pw.println(pnum);
}
pw.close();
}
// Read the records from file “MyFriends.txt”.
public void fnReadFromFile() throws IOException
{
FileReader fr = new FileReader(“MyFriends.txt”);
BufferedReader br = new BufferedReader(fr);

306
DATA FILE HANDLING

String fname = “ ”, fpnum = “ ”;


int j = 1;
fname = br.readLine();
while(fname != null)
{
fpnum = br.readLine();
System.out.print(“\n ” + j + “. Friend Name : ” + fname + “ ...
pnum = ” + fpnum);
fname = br.readLine();
j++;
}
br.close();
fr.close();
}
public void main() throws IOException
{
fnWriteInFile();
 //it creates data file, writes in it, and then closes the file
fnReadFromFile(); // it opens a file in
}
}
OUTPUT :
1. Enter name .. Surya
Enter phone number .. 2356
2. Enter name .. Kiran
Enter phone number .. 6589
3. Enter name .. Sajid
Enter phone number .. 8754
4. Enter name .. Indra
Enter phone number .. 5465
5. Enter name .. Raj
Enter phone number .. 4589
1. Friend Name : Surya ... pnum = 2356
2. Friend Name : Kiran ... pnum = 6589
3. Friend Name : Sajid ... pnum = 8754
4. Friend Name : Indra ... pnum = 5465
5. Friend Name : Raj ... pnum = 4589

307
ISC COMPUTER SCIENCE – XI

2. import java.util.*;
import java.io.*;
class Salesman
{
Scanner sc = new Scanner(System.in);
public void fnFillDataInFile()
{
String Name = “ ”;
int amt = 0;
try
{
FileWriter obj1 = new FileWriter(“Salesman.txt”);
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
BufferedReader br = new BufferedReader(new InputStream
Reader(System.in));
for(int j = 1; j <= 10; j++)
{
System.out.print(j + “. Enter the Name of Salesman : ”);
Name = br.readLine();
System.out.print(“Enter the Amount Booked : ”);
amt = sc.nextInt();
obj3.println(Name); //writing data in files
obj3.println(amt);
}
}
catch(Exception e)
{
System.out.println(“Error in Input ”);
}
}
public void fnPrintDataFromFile()
{
String Name = “”;
int amt = 0;
308
DATA FILE HANDLING

System.out.println(“\n\n\nSalesman with High Amount Booked :”);


try
{
FileReader obj1 = new FileReader(“Salesman.txt”);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
Name = obj2.readLine();
if(Name.equals(“”))
{
break;
}
amt = Integer.parseInt(obj2.readLine());
if(amt > 75000)
{
System.out.println(Name);
}
} while(true); // reading data from file till null
}
catch(Exception e)
{}
}
public void main()
{
fnFillDataInFile();
fnPrintDataFromFile();
}
}
OUTPUT :
1. Enter the Name of Salesman : Vinod
Enter the Amount Booked : 50000
2. Enter the Name of Salesman : Kaif
Enter the Amount Booked : 90000
3. Enter the Name of Salesman : Sayan
Enter the Amount Booked : 78000
4. Enter the Name of Salesman : Sheikh
Enter the Amount Booked : 65000

309
ISC COMPUTER SCIENCE – XI

5. Enter the Name of Salesman : Komal


Enter the Amount Booked : 8000
6. Enter the Name of Salesman : Priya
Enter the Amount Booked : 40000
7. Enter the Name of Salesman : Nikhat
Enter the Amount Booked : 62000
8. Enter the Name of Salesman : Mitali
Enter the Amount Booked : 48000
9. Enter the Name of Salesman : Kabir
Enter the Amount Booked : 59000
10. Enter the Name of Salesman : Roshni
Enter the Amount Booked : 99000
Salesman with High Amount Booked :
Kaif
Sayan
Komal
Roshni

3. import java.util.*;
import java.io.*;
class Cars
{
int n, x;
Scanner sc = new Scanner(System.in);
public void main()
{
Input();
fnFillDataInFile();
fnPrintData();
}
public void Input()
{
System.out.print(“Enter the number of cars ”);
n = sc.nextInt();
System.out.println(“Enter the x value : ”);

310
DATA FILE HANDLING

x = sc.nextInt();
}
public void fnFillDataInFile()
{
String cars = “ ”;
int cost, i = 0, n = 5;
try
{
FileWriter fw = new FileWriter(“Cars.txt”);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
while(i != n)
{
System.out.print(“Enter the Name of the Car : ”);
cars = br.readLine();
System.out.print(“Enter the Cost of the Car : ”);
cost = sc.nextInt();
pw.println(cars);
pw.println(cost);
i++;
}
}
catch(Exception e)
{}
}
public void fnPrintData()
{
String cars = “”;
int cost;
try
{
File Reader fr = new FileReader(“Cars.txt”);

311
ISC COMPUTER SCIENCE – XI

BufferedReader br = new BufferedReader(fr);


do
{
cars = br.readLine();
if(cars.equals(“ ”))
{
break;
}
cost = Integer.parseInt(br.readLine());
if(cost > x)
{
System.out.println(cars);
}
}while(true);
}
catch(Exception e)
{}
}
}
OUTPUT :
Enter the number of cars 6
Enter the x value : 400000
Enter the Name of the Car : Torsa
Enter the Cost of the Car : 400001
Enter the Name of the Car : Qualis
Enter the Cost of the Car : 800000
Enter the Name of the Car : Echo
Enter the Cost of the Car : 200000
Enter the Name of the Car : Bolero
Enter the Cost of the Car : 900000
Enter the Name of the Car : Vitara
Enter the Cost of the Car : 1500000
Torsa
Qualis
Bolero
Vitara

312
DATA FILE HANDLING

4. import java.util.*;
import java.io.*;
class Country_File
{
void MakeDataFile() throws Exception
{
int n;
// for user input, BufferedReader class has been used, Scanner class
could also be used
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
Scanner sc = new Scanner(System.in);
System.out.print(“How many records : ”);
n = sc.nextInt();

try
{
FileWriter obj1 = new FileWriter(“ContinentCountryCap.txt”);
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);

System.out.println(“Enter the Records Continent Country
Capital : ”); // writing heading in Data File
obj3.println(“CONTINENTS COUNTRIES CAPITALS ”);
for(int i = 1; i <= n; i++)
{
System.out.print(“\n Enter CONTINENT number ” + i + “ : ”);
obj3.print(br.readLine() + “ ”);
System.out.print(“\n Enter COUNTRY number ” + i + “ : ”);
obj3.print(br.readLine() + “ ”);
System.out.print(“\n Enter CAPITAL number ” + i + “ : ”);
obj3.println(br.readLine());
}
obj3.close();
}

313
ISC COMPUTER SCIENCE – XI

catch(IOException ignored)
{}
}
void MakeSecondFile()throws Exception
{
String continent, text;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the name of the CONTINENT : ”);
continent = sc.nextLine();
String file2Name = continent + “.txt”;
System.out.println(“ \t\t\t Continent Filename : ” + file2Name);
try
{
FileWriter obj1 = new FileWriter(file2Name);
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
FileReader obj4 = new FileReader(“ContinentCountryCap.txt”);
BufferedReader obj5 = new BufferedReader(obj4);
do
{
text = obj5.readLine();
if(!text.equalsIgnoreCase(null))
{
System.out.println(“ Record : ” + text);
String con = text.substring(0, text.indexOf(‘ ’));
}
if(con.equalsIgnoreCase(continent) )
{
String councap = text.substring(text.indexOf(‘ ‘));
if(!councap.equalsIgnoreCase(null))
obj3.println(councap);
}
} while(! text.equals(null));
}

314
DATA FILE HANDLING

catch(NullPointerException e)
{}
}
void DisplayFile()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the name of the Continent File you want to
open : ”);
String file2Name = sc.nextLine();
try
{
BufferedReader obj2 = new BufferedReader(new FileReader
(file2Name));
String text;
do
{
text = obj2.readLine();
if(!text.equals(“”))
{
System.out.println(text);
}
} while(! text.equals(“”));
}
catch(NullPointerException | IOException e)
{}
}
void main()throws Exception
{
// Can be upgraded ( for programmers to do ... )
MakeDataFile();
MakeSecondFile();
DisplayFile();
}
}

315
ISC COMPUTER SCIENCE – XI

OUTPUT :
How many records : 6
Enter the Records Continent Country Capital :
Enter CONTINENT number 1 : A
Enter COUNTRY number 1 : a
Enter CAPITAL number 1 : a
[ … more data to enter ]
Enter the name of the CONTINENT : Asia
Continent File name is : Asia.txt
Record : CONTINENTS COUNTRIES CAPITALS
Record : Asia Bhutan Thimpu
Record : Africa Egypt Cairo
Record : Europe France Paris
Record : Asia Nepal Kathmandu
Record : Africa Kenya Nairobi
Record : Asia Japan Tokyo
Enter the name of the FILE you want to open : Asia.txt
Asia Bhutan Thimpu
Asia Nepal Kathmandu
Asia Japan Tokyo

5. import java.io.*;
import java.util.Scanner;
class Euro_File
{
String fileName = “Euro.txt”;
int n;
void main()
{
Input();
FillData();
MakeSecondFile();
Display();
}
void Input()
{

316
DATA FILE HANDLING

Scanner sc = new Scanner(System.in);


System.out.print(“Enter the Number of Countries : ”);
n = sc.nextInt();
}
void FillData()
{
String country, captain;
int goals;
BufferedReaderbr = new BufferedReader(new InputStreamReader
(System.in));
try
{
FileWriterobj1 = new FileWriter(fileName);
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
int i;
obj3.println(“EURO 2016”);
obj3.println();
for(i = 1; i <= n; i++)
{
System.out.println(“Enter the Name of the Country : ”);
country = br.readLine();
System.out.println(“Enter the name of the Captain : ”);
captain = br.readLine();
System.out.println(“Enter the number of Goals by the
country”);
goals = Integer.parseInt(br.readLine());
obj3.println(country + “ ” + captain + “ ” + goals);
}
}
catch(Exception e)
{}
}
void MakeSecondFile()
{

317
ISC COMPUTER SCIENCE – XI

int goals = 2;
String country = “”;
try
{
FileReader obj1 = new FileReader(fileName);
Scanner obj2 = new Scanner(obj1);
FileWriter obj3 = new FileWriter(“Golden.txt”);
BufferedWriter obj4 = new BufferedWriter(obj3);
PrintWriter obj5 = new PrintWriter(obj4);
String data = “ ”;
do
{
data = obj2.nextLine();
String sd = data.substring(data.lastIndexOf(‘ ’) + 1);
goals = Integer.parseInt(sd);
System.out.println(“ line : ” + data + “ goals :” + goals
+ “.”);
if(goals > 5)
{
obj5.println(data);
}
} while(! data.equals(null));
}
catch(Exception e)
{}
}
void Display()
{
System.out.println(“The Name of the countries who scored more than 5
goals :”);
try
{
FileReader obj1 = new FileReader(“Golden.txt”);
Scanner obj2 = new Scanner(obj1);
do
{

318
DATA FILE HANDLING

System.out.println(obj2.nextLine());
} while(!obj2.nextLine().equals(null));
}
catch(Exception e)
{}
}
}

6. import java.io.*;
import java.util.Scanner;
class Currency
{
String fileName = “Currency.txt”;
void main()
{
FillDataInFile();
ReadDataFromFile();
MoneyConverter();
}
void FillDataInFile()
{
String country, currency;
double equ;
BufferedReader br = new BufferedReader(new InputStreamReader
(System.in));
System.out.println(“Enter Country and \“ EXIT \” to stop”);
try
{
FileWriter obj1 = new FileWriter(fileName, true); // opening file
in append mode
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
do
{
319
ISC COMPUTER SCIENCE – XI

System.out.print(“Enter the Name of the country : ”);


country = br.readLine();
if(country.equalsIgnoreCase(“exit”))
{
break;
}
System.out.print(“Enter the Currency :”);
currency = br.readLine();
System.out.print(“Enter the Rupee Equivalence in ” +
currency + “ : ”);
equ = Double.parseDouble(br.readLine());
obj3.println(country);
obj3.println(currency);
obj3.println(equ);
} while(! country.equals(“exit”));
}
catch(Exception e)
{}
}
void ReadDataFromFile()
{
String currency, CC;
int n = 1;
System.out.println(“Country \t Currency \t RsEqvlt”);
try
{
FileReader obj1 = new FileReader(fileName);
BufferedReader obj2 = new BufferedReader(obj1);

do
{
CC = obj2.readLine();
if(CC.equals(null))
break;
System.out.print(CC + “\t\t”);
if(n++ % 3 == 0)

320
DATA FILE HANDLING

System.out.println();
} while(! CC.equals(null));
}
catch(Exception e)
{}
}
void MoneyConverter()
{
String currency;
double rup;
Scanner ob = new Scanner(System.in);
System.out.print(“\f Enter the Currency : ”);
currency = ob.nextLine();
System.out.print(“Enter the Money in Indian Rupees : ”);
rup = ob.nextDouble();
try
{
FileReader obj1 = new FileReader(fileName);
BufferedReader obj2 = new BufferedReader(obj1);
String CC;
do
{
CC = obj2.readLine();
if(CC.equalsIgnoreCase(currency))
{
double c = Double.parseDouble(obj2.readLine());
double money = rup / c;
System.out.println(“In” + CC + “ Rs.” + rup + “ is
equivalent to ” + money);
}
} while(! CC.equals(null));
}
catch(Exception e)
{}
}
}

321
ISC COMPUTER SCIENCE – XI

OUTPUT :
ReadDataFromFile() prints :
Country Currency RsEqvlt
Bangladesh Taka 1.5
Italy Euro 80.0
Japan Yen 0.62
Thailand Baht 2.20
Singapore S.Dollar 52.28
Enter the Currency : Yen
Enter the Money in Indian Rupees : 620
In Yen Rs. 620.0 is equivalent to 1000.0
7. import java.io.*;
import java.util.Scanner;
class Rainfall
{
String fileName = “Rainfall.txt”;
void main()
{
FillDataInFile();
ReadDataFromFile();
PrintDryCity();
}
void FillDataInFile()
{
String city;
double rf;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter City Names (\“ EXIT \” to stop) ”);
try
{
FileWriter obj1 = new FileWriter(fileName, true); // opening file
in append
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
do
{
322
DATA FILE HANDLING

System.out.print(“Enter the Name of the city : ”);


city = sc.nextLine();
if(city.equalsIgnoreCase(“exit”))
{
break;
}
System.out.print(“Enter Annual Rainfall :”);
rf = sc.nextDouble();
String tmp = sc.nextLine(); // for clearing buffer
obj3.println(city);
obj3.println(rf);
} while(! city.equals(“exit”));
}
catch(Exception e)
{}
}
void ReadDataFromFile()
{
String city;
int n = 1;
System.out.println(“City \t Rainfall ”);
try
{
FileReader obj1 = new FileReader(fileName);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
city = obj2.readLine();
if(city.equals(null))
break;
System.out.print(city + “\t\t”);
if(n++ % 2 == 0)
System.out.println();
} while(! city.equals(null));
}

323
ISC COMPUTER SCIENCE – XI

catch(Exception e)
{}
}
void PrintDryCity()
{
String city;
double rf;
System.out.println(“Dry City with Rainfall”);
try
{
FileReader obj1 = new FileReader(fileName);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
city = obj2.readLine();
if(city.equals(null))
break;
rf = Double.parseDouble(obj2.readLine( ));
if(rf < 50)
System.out.println(city + “ ” + rf);
} while(! city.equals(null));
}
catch(Exception e)
{}
}
}
OUTPUT :
Enter City Names (“EXIT ” to stop)
Enter the Name of the city : Tokyo
Enter Annual Rainfall : 60
Enter the Name of the city : Shanghai
Enter Annual Rainfall : 45
[ more data to enter ]

324
DATA FILE HANDLING

Enter the Name of the city : EXIT


City Rainfall
Tokyo 60.0
Tokyo 60.0
Shanghai 45.0
Beijing 25.0
Tel Aviv 21.0
Kolkata 63.0
Dubai 4.0
Doha 9.0
Dhaka 78.0
Dry City with Rainfall
Shanghai 45.0
Beijing 25.0
Tel Aviv 21.0
Dubai 4.0
Doha 9.0

8. import java.io.*;
import java.util.Scanner;
class Airplane
{
String fileName = “Airplane.txt”;
String filename2;
void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“Filling Airplane.txt”);
//FillDataInFile();
System.out.println(“\nPrinting Airplane.txt”);
ReadDataFromFile(fileName);
System.out.println(“\n Making Nationality file”);
SecondFile();
System.out.println(“\nPrinting” + filename2);
ReadDataFromFile(filename2);
}

325
ISC COMPUTER SCIENCE – XI

voidFillDataInFile()
{
String name, nationality;
double wt;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter Name Nationality Lug_Weight (\“ EXIT \”
to stop) ”);
try
{
FileWriter obj1 = new FileWriter(fileName); // opening file in
append
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
do
{
System.out.print(“Enter the Passenger’s Name : ”);
name = sc.nextLine();
if(name.equalsIgnoreCase(“exit”))
{
break;
}
System.out.print(“Enter Nationality of the Passenger :”);
nationality = sc.nextLine();
System.out.print(“Enter Lug_Weight of the Passenger :”);
wt = sc.nextDouble();
String tmp = sc.nextLine(); // for clearing buffer
System.out.println(name + “\n” + nationality + “\n” + wt);
obj3.println(name);
obj3.println(nationality);
obj3.println(wt);
} while(! name.equals(“exit”));
}
catch(Exception e)
{}
}

326
DATA FILE HANDLING

void ReadDataFromFile(String filename2)


{
String name, nationality;
double wt = 0;
int n = 1;
Scanner sc = new Scanner (System.in);
System.out.println(“Passenger’s Name Nationality and Luggage
Weight :”);
try
{
FileReader obj1 = new FileReader(filename2);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
name = obj2.readLine();
if(name.equals(null))
break;
System.out.print(name + “\t\t”);
 if(n++ % 3 == 0) // to print a line gap after printing 3
data in same line
System.out.println();
} while(! name.equals(null));
}
catch(Exception e)
{}
}
void SecondFile()
{
String name, nationality = “ ”, nationality2 = “ ”;
double wt = 0;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter Nationality ”);
nationality2 = sc.nextLine();
filename2 = nationality2 + “.txt”;
System.out.print(“ New Filename : ” + filename2);
try
{
327
ISC COMPUTER SCIENCE – XI

FileReader obj1 = new FileReader(fileName);//file to read from


BufferedReader obj2 = new BufferedReader(obj1);
FileWriter fw = new FileWriter(filename2); // file to write into
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
do
{
name = obj2.readLine();
if(name.equals(null))
break;
nationality = obj2.readLine();
wt = Double.parseDouble(obj2.readLine();
if(nationality.equals(nationality2))
{
pw.println(name + “ \n” + nationality + “\n” + wt);
}
} while(! name.equals(null));
}
catch(Exception e)
{}
}
}
OUTPUT :
Filling Airplane.txt
Printing Airplane.txt
Passenger’s Name Nationality and Luggage Weight :
Dero Nepal 400.0
Wini Thai 250.0
Liza Nepal 150.0
Reno Thai 120.0
Tima Nepal 350.0
Rahi Thai 50.0
Making Nationality file
Enter Nationality Thai
New Filename : Thai.txt
Printing Thai.txt

328
DATA FILE HANDLING

Passenger’s Name Nationality and Luggage Weight :


Wini Thai 250.0
Reno Thai 120.0
Rahi Thai 50.0

9. import java.io.*;
import java.util.Scanner;
class MusicStore
{
String fileName = “Instrument.txt”;
void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“Filling Instrument.txt”);
FillDataInFile();
System.out.println(“\n\nPrinting Instrument.txt”);
ReadDataFromFile();
System.out.println(“\nMaking MakeProfit.txt”);
MakeProfitFile();
System.out.println(“\nPrinting Profit.txt”);
PrintProfitFile();
}
void FillDataInFile()
{
String insName;
double cp, sp;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter Instrument Name, Cost price, Sell price(\“
EXIT \”to stop) ”);
try
{
FileWriter obj1 = new FileWriter(fileName); // opening file in
append
BufferedWriter obj2 = new BufferedWriter(obj1);
PrintWriter obj3 = new PrintWriter(obj2);
do
{

329
ISC COMPUTER SCIENCE – XI

System.out.print(“Enter the Instrument Name : ”);


insName = sc.nextLine();
if(insName.equalsIgnoreCase(“exit”))
{
break;
}
System.out.print(“Enter Cost Price :”);
cp = sc.nextDouble();
System.out.print(“Enter Sell Price :”);
sp = sc.nextDouble();
String tmp = sc.nextLine(); // for clearing buffer
obj3.println(insName);
obj3.println(cp);
obj3.println(sp);
} while(! insName.equals(“exit”));
}
catch(Exception e)
{}
}
void ReadDataFromFile()
{
String name;
int n = 1;
double cp, sp;
System.out.println(“Instrument Name; Cost Price; Sell Price :”);
try
{
FileReader obj1 = new FileReader(fileName);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
name = obj2.readLine();
if(name.equals(null))
break;
System.out.print(name + “\t\t”);

330
DATA FILE HANDLING

if(n++ % 3 == 0)
System.out.println();
} while(! name.equals(null);
}
catch(Exception e)
{}
}
void MakeProfitFile()
{
String name;
double cp = 0, sp = 0;
try
{
FileReader obj1 = new FileReader(“Instrument.txt”);//file to read
from
BufferedReader obj2 = new BufferedReader(obj1);
FileWriter fw = new FileWriter(“Profit.txt”); // file to write into
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
do
{
name = obj2.readLine();
if(name.equals(null))
break;
cp = Double.parseDouble(obj2.readLine());
sp = Double.parseDouble(obj2.readLine());
if(sp > cp)
{
pw.println(name + “\n” + (sp – cp);
}
} while(! name.equals(null));
}
catch(Exception e)
{}
}

331
ISC COMPUTER SCIENCE – XI

void PrintProfitFile()
{
String name;
int n = 1;
double cp, sp;
System.out.println(“Instrument Name; Profit Amount :”);
try
{
FileReader obj1 = new FileReader(“Profit.txt”);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
name = obj2.readLine();
if(name.equals(null))
break;
System.out.print(name + “\t\t”);
if(n++ % 2 == 0)
System.out.println();
} while(! name.equals(null));
}
catch(Exception e)
{}
}
}

OUTPUT :
Filling Instrument.txt
Printing Instrument.txt
Instrument Name; Cost Price; Sell Price :
Sitar 5000.0 6500.0
Guitar 2500.0 3000.0
Drums 10000.0 8000.0
Tabla 3000.0 2000.0
Making MakeProfit.txt
Printing Profit.txt

332
DATA FILE HANDLING

Instrument Name; Profit Amount :


Sitar 1500.0
Guitar 500.0

10. import java.io.*;


import java.util.Scanner;
class CityDistance
{
Scanner sc = new Scanner(System.in);
String fileName = “ ”, country, capital;
void main()
{
Scanner sc = new Scanner(System.in);
country = “ ”;
capital = “ ”;
double dist = 0;
System.out.print(“Enter Country Name : ”);
country = sc.nextLine();
System.out.print(“Enter the capital of ” + country + “ : ”);
capital = sc.nextLine();
fnMakeCapitalFile(capital);
fnReadFromCapitalFile();
MakeParcelFile();
PrintParcelFile();
}
void fnMakeCapitalFile(String capital)
{
String cityName = “ ”;
double distance;
System.out.println(“Enter CityName, its distance from ” + capital
+ “(\“ EXIT \” to stop) : ”);
fileName = capital + “.txt”;
try
{
FileWriter obj1 = new FileWriter(fileName); // opening
file in append

333
ISC COMPUTER SCIENCE – XI

BufferedWriter obj2 = new BufferedWriter(obj1);


PrintWriter obj3 = new PrintWriter(obj2);
do
{
System.out.print(“Enter the City Name : ”);
cityName = sc.nextLine();
if(cityName.equalsIgnoreCase(“exit”))
{
break;
}
System.out.print(“Enter its distance from” +
capital + “ : ”);
distance = sc.nextDouble();
String tmp = sc.nextLine(); // for clearing buffer
obj3.println(cityName);
obj3.println(distance);
} while(! cityName.equals(“exit”));
}
catch(Exception e)
{}
}
void fnReadFromCapitalFile()
{
String cityName;
int n = 1;
double dist;
System.out.println(“\n Capital File : \n City Name & its distance
from ” + capital + “ : ”);
try
{
FileReader obj1 = new FileReader(“Rome.txt”);
BufferedReader obj2 = new BufferedReader(obj1);
do
{

334
DATA FILE HANDLING

cityName = obj2.readLine();
if(cityName.equals(null))
break;
System.out.print(cityName + “\t\t”);
if(n++ % 2 == 0)
System.out.println();
} while(! cityName.equals(null));
}
catch(Exception e)
{}
}
void MakeParcelFile()
{
String name;
double distance, parcelCost;
System.out.println(“\n Making Parcel File :: ”);
try
{
FileReader obj1 = new FileReader(fileName);  //file to
read from
BufferedReader obj2 = new BufferedReader(obj1);
FileWriter fw = new FileWriter(“Parcel.txt”);  // file to
write into
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
do
{
name = obj2.readLine();
if(name.equals(null))
break;
distance = Double.parseDouble(obj2.readLine());
if(distance <= 100)
{
parcelCost = 100;
}

335
ISC COMPUTER SCIENCE – XI

else if(distance <= 300)


{
parcelCost = 200;
}
else if(distance <= 500)
{
parcelCost = 300;
}
else
{
parcelCost = 400;
}
pw.println(name + “\n” + parcelCost);
} while(! name.equals(null));
}
catch(Exception e)
{}
}
void PrintParcelFile()
{
String name;
int n = 1;
double cp, sp;
System.out.println(“\n Printing Parcel File, Parcel Rate from ” +
capital + “ :: ”);
System.out.println(“City & Rate ” + capital + “ : ”);
try
{
FileReader obj1 = new FileReader(“Parcel.txt”);
BufferedReader obj2 = new BufferedReader(obj1);
do
{
name = obj2.readLine();

336
DATA FILE HANDLING

if(name.equals(null))
break;
System.out.print(name + “\t\t”);
if(n++ % 2 == 0)
System.out.println();
} while(! name.equals(null));
}
catch(Exception e)
{}
}
}

OUTPUT :
Enter Country Name : italy
Enter the capital of Italy : rome
Capital File :
City Name & its distance from rome :
Milan 575.5
Florence 271.3
Venice 528.3
Turin 692.4
Naples 226.1
Latina 58.0
Formia 72.82
Udine 467.8
Making Parcel File ::
Printing Parcel File, Parcel Rate from rome ::
City & Rate rome :
Milan 400.0
Florence 200.0
Venice 400.0
Turin 400.0
Naples 200.0
Latina 100.0
Formia 100.0
Udine 300.0

337
ISC COMPUTER SCIENCE – XI

EXERCISE

1. Answer the following :


(a) Name the package that contains Scanner class ?
(b) What is a Java Stream ?
(c) Which is the method of Scanner class that is used to input an integer from
standard input stream ?
(d) Which is the method of Scanner class that is used to input a string from standard
input stream ?

2. State True and False :


(a) A stream can be defined as a sequence of data.
(b) Java Character streams are used to perform input and output for 16-bit unicode.
(c) Buffered input streams read data from a memory area known as a block.
(d) To append data in the existing file, open an existing file using FileReader.
(e) For closing a file, FileObject.close() is used.
qq

338
RECURSIVE FUNCTIONS

13 RECURSIVE
FUNCTIONS

l Recursive function and its base case



 Use of memory stack in a recursive function

 A function calling another function

 A Function calling itself

 Features of a Recursive Function

 Comparison between Recursion and Iteration
l Programs on Recursive Functions
1. Sum of first n natural numbers. S = 1 + 2 + 3 + … + n
2. Product of first n natural numbers.
P = 1 * 2 * 3 * … * n
3. Sum of first n natural numbers (another method)
4. Product of first n natural numbers (another
method).
5. p * q , without using * operator but by using
repetitive addition
6. Print the numbers from p to q
7. Print the factors of a number
8. Print the Multiplication Table of a number
9. Division of a number by another, return the
quotient and print the remainder
10. Print the HCF (or GCD) of two numbers.

RECURSIVE FUNCTION AND ITS BASE CASE


A recursive function is a special kind of function that makes a call to itself.
Every recursive function should have a base case. Upon reaching the base case,
the recursion stops and the calculation begins. Without a base case, a recursive function
repeats infinite number of times.
339
ISC COMPUTER SCIENCE – XI

Use of Memory Stack in a Recursive Function


A recursive function uses the memory stack to store its intermediate values (which
are calculated after the control returns from the base case). If a recursive function enters
infinity (an error situation) then a runtime error occurs, which states “Stack Overflow”.
A Function Calling Another Function
Example Code :
main() EXPLANATION :
{
… main() is the super function and fntest1() is the sub function.
fntest1();
… The control goes to the sub function when it is called and
… when its code is complete, it goes back to its super function.
The super function carries on with the rest of its code after
}
the function call is over.
void fntest1()
{

}
A Function Calling Itself
In case of recursive functions, the function becomes its own super and sub function.
Example Code :
fnrec1(argument list a) EXPLANATION :
{
… In the given example, fnrec1(..) makes a function
fnrec1(argument list b); call to itself.
… It is a recursive function.
… While making a function call to itself, the value
of the arguments identify the super and the sub
} function.
Recursive Methods Illustration :

340
RECURSIVE FUNCTIONS

Features of a Recursive Function


u It makes a call to itself with a change in the arguments.
u It terminates when it reaches its base case.
u It does not use a variable to store the intermediate value instead uses the memory
stack of the computer system.
u In case of memory shortage, it gives an error “Stack Overflow”.
u Each recursion performs a fresh memory allocation for its arguments/variables.
u Memory requirement of a recursive function is high, hence the system cost also
becomes high.
u Certain kind of programs cannot be done without using recursion [like the Tower
of Hanoi and more of the same kind].
Comparison between Recursion and Iteration
u Recursion using a recursive function and iteration using a loop are meant for
doing repetitive tasks.
Example :
// Iteration // Recursion
int fnFactorialLoop(int n) int fnFactorialRecur(int n)
{ {
int f = 1; if(n <= 1)
for(int j = 1; j <= n; {
j++) return 1;
{ }
f = f * j; return(n * fnFactorialRecur(n – 1));
} }
}
u In iteration, first the calculation is done and then the control moves ahead but in
recursion, the calculation is done after the base case is reached.
u In general, the space requirement (in terms of memory stack) is more compared
to iteration. [in iteration, same memory block is used for the calculation].
u Space and time complexity of recursion is generally more than iteration.

PROGRAMS ON RECURSIVE FUNCTIONS

1. Sum of first n natural numbers. S = 1 + 2 + 3+ … + n


import java.io.*;
public class clRecursive
{
public void main()
{
int r1 = 0;

341
ISC COMPUTER SCIENCE – XI

r1 = fnAdd(5);
System.out.print(“\n Result of fnAdd(5) = ” + r1);
}
public int fnAdd(int n)
{
if( n <= 0) // base case
{
return 0;
}
System.out.print(“\n in fnAdd .. n = ” + n);
return(n + fnAdd(n – 1)); // recursive call
}
}
OUTPUT :
in fnAdd .. n = 5
in fnAdd .. n = 4
in fnAdd .. n = 3
in fnAdd .. n = 2
in fnAdd .. n = 1
Result of fnAdd(5) = 15

Working Explanation (shown in 2 ways) :


Assume we call the function with n = 5, then fnAdd(5) will work as follows :
5 + fnAdd(4) When the recursion ends, the calculation takes
| place backwards.
|4 + fnAdd(3) So, here goes the calculation as :
| fnAdd(5)
|3 + fnAdd(2) = 5 + (fnAdd(4))
|
= 5 + ( 4 + fnAdd(3))
|2 + fnAdd(1)
= 5 + ( 4 + ( 3 + fnAdd(2)))
|
= 5 + ( 4 + ( 3 + (2 + fnAdd(1))))
|1 + fnAdd(0)
= 5 + ( 4 + ( 3 + (2 + ( 1 + fnAdd(0)))))
|
= 5 + ( 4 + ( 3 + (2 + ( 1 + (0)))))
|0

342
RECURSIVE FUNCTIONS

We can also say that fnAdd(4) is a sub function of fnAdd(5). Again fnAdd(3) is a sub
function of fnAdd(4). The base case takes place when n = 0. fnAdd(0) does not call the
function but returns 0 directly. After the base case, the calculation gets completed.
2. Product of first n natural numbers. P = 1 * 2 * 3 * … * n
OUTPUT :
import java.io.*; in fnMultiply.. n = 5
public class clRecursive in fnMultiply.. n = 4
{ in fnMultiply.. n = 3
public void main() in fnMultiply.. n = 2
{ in fnMultiply.. n = 1
int r1 = 0; Result of fnMultiply(5) = 120
r1 = fnMultiply(5);
System.out.print(“\n Result of
fnMultiply(5) = ” + r1);
}

public int fnMultiply(int n)


{
if(n <= 1)
{
return 1;
}
System.out.print(“\n … in fnMultiply
… n = ” + n);
return(n * fnMultiply(n – 1));
}
}

WORKING :
Assume we call the function with n = 5. When the recursion ends, the calcula-
fnMultiply(5) tion takes place backwards.
5 * fnMultiply(4) So, here is the calculation :
4 * fnMultiply(3) ( 5 * ( 4 * ( 3 * ( 2 * ( 1 ) ) ) ) )
3 * fnMultiply(2)
2 * fnMultiply(1)
1
3. Sum of first n natural numbers (another method). S2 = 1 + 2 + 3 + … + n
public int fnRec5(int n, int limit)
{

343
ISC COMPUTER SCIENCE – XI

if(n > limit)


{
return 0;
}
System.out.print(“\n in fnRec1 .. n = ” + n);
return(n + fnRec5(n + 1, limit));
}
WORKING :
Assume we call the function with n = 1
and limit = 5. When the recursion ends, the calculation
fnRec1(1, 5) takes place backwards.
1 + fnRec1(2, 5) So, here is the calculation :
2 + fnRec1(3, 5)
3 + fnRec1(4, 5) ( 1 + ( 2 + ( 3 + ( 4 + (5 + ( 0 ) ) ) ) ) )
4 + fnRec1(5, 5)
5 + fnRec1(6, 5) This function makes n start from 1 and
0 increase till the limit.
4. Product of first n natural numbers (another method). P = 1 * 2 * 3 * … * n
public int fnRec7(int n, int limit)
{
if(n > limit)
{
return 1;
}
System.out.print(“\n in fnRec7 .. n = ” + n);
return(n * fnRec7(n + 1, limit));
}
WORKING :
Assume we call the function with n = 1 and
limit = 5. When the recursion ends, the calculation
fnRec7(1, 5) takes place backwards.
1 * fnRec7(2, 5) So, here is the calculation :
2 * fnRec7(3, 5)
3 * fnRec7(4, 5) ( 1 * ( 2 * ( 3 * ( 4 * (5 * ( 1 ) ) ) ) ) )
4 * fnRec7(5, 5)
5 * fnRec7(6, 5) .
1

344
RECURSIVE FUNCTIONS

5. p * q , without using * operator but by using repetitive addition.


If p = 5, q = 4 then, p * q = 5 * 4 = 5 + 5 + 5 + 5
public int fnRec5(int p, int q) OUTPUT :
{ in fnRec5 .. p = 5 q = 4
if(q < 1) in fnRec5 .. p = 5 q = 3
{ in fnRec5 .. p = 5 q = 2
return 0; in fnRec5 .. p = 5 q = 1
}
System.out.print(“\n in fnRec5 .. p = ” + p + [The function finally returns 20.]
“ q = ” + q);
return(p + fnRec5(p, q – 1));
}
WORKING :
Assume we call the function with p = 5
and q = 4. When the recursion ends, the cal-
fnRec5(5, 4) culation takes place backwards.
5 + fnRec7(5, 3) So, here is the calculation :
5 + fnRec5(5, 2)
5 + fnRec5(5, 1) ( 5 + ( 5 + ( 5 + ( 5 + (0) ) ) ) )
5 + fnRec5(5, 0)
0

6. Print the numbers from p to q.


public void fnRec7(int p, int q)
{
if(p > q) OUTPUT (with p = 5 and q = 9) :
{
return;
} .. 5 .. 6 .. 7 .. 8 .. 9
System.out.print(“ \t .. ” + p);
return(fnRec7(p + 1, q));
}
WORKING :
Assume we call the function with p = 5 and q = 9. In this case there is no value to be
Value printed returned. The recursive function
continues calling itself as long as
fnRec7(5, 9) 5
the condition allows.
fnRec7(6, 9) 6
fnRec7(7, 9) 7
fnRec7(8, 9) 8
fnRec7(9, 9)  9
fnRec7(10, 9)
the function terminates

345
ISC COMPUTER SCIENCE – XI

7. Print the factors of a number. [Printing on condition]


public void fnRec13(int num, int f) OUTPUT :
{
if(f > num) fnRec13 result =
{ 1 is a factor of 12
return; 2 is a factor of 12
} 3 is a factor of 12
if(num % f == 0)
4 is a factor of 12
{
6 is a factor of 12
System.out.print(“\n ” + f + “ is a factor of ” +
num); 12 is a factor of 12
}
fnRec13(num, f + 1);
}
WORKING :
Assume we call the function with num = 12 and f = 1.
The second argument f is tested as factor of num. Range of f is from 1 to num. Printing
of f takes place on condition. [In this case at the starting level, f should begin with 1.]
8. Print the Multiplication Table of a number.
public void fnRec17(int val, int t, int limit)
{
if(t > limit)
{
return;
}
int p = val * t;
System.out.print(“\n ” + val + “ x ” + t + “ = ” + p);
fnRec17(val, t + 1, limit);
}
// Verify the output with fnRec17(12, 1, 15)
9. Division of a number by another. Method fnDivide(int n, int f) returns the quotient
of n/f and prints the remainder.
//code to return the quotient and to print the What will happen if the given code
remainder is executed with :
public int fnDivide(int n, int f) (i) n = 38 and f = 7
{ (ii) n = 100 and f = 35
if(n == 0 || (n – f) < 0)
(iii) n = 25 and f = 49
{
(iv) n = 0 and f = 5
System.out.print(“\n Remainder is ” + n);
return 0; (v) n = 150 and f = 50
}
return(1 + fnDivide(n – f, f));
}

346
RECURSIVE FUNCTIONS

10. Print the HCF (or GCD) of two numbers. [Another method]
public int fnHCF2(int m, int n)
{ OUTPUT (with m = 9, n = 6) :
if(m == n)
{ fnHCF result = 3
return n;
} WORKING :
else if(m > n) m = 9, n = 6; m == n  false
{ m > n  true so,
fnHCF2(m – n, n);
m = 3, n = 6; m == n  false
}
else m > n  false
{ else  true so,
fnHCF2(m, n – m);
m = 3, n = 3; m == n  true so
}
}
public void main() return n  3 which is the HCF
{
System.out.print(“\n fnHCF result = ” + fnHCF(9, 6));
}

EXERCISE

1. Write the outputs of the following codes :

(a) What will be the output if :


void fnRDf(int n) n = 2436
{
if(n <= 0) n = 95623
return;
fnRDf(n/10);
System.out.print(“..” + n % 10);
}

(b) What will be the output if :


boolean fnRP(int n, int f) n = 23 f = 22
{
n = 31 f = 31
if(f <= 1)
n = 1 f = 1
return true;
if(n % f == 0)
return false;
return fnRP(n, f – 1);
}

347
ISC COMPUTER SCIENCE – XI

(c)
void fnRS(int n, int t) What will be the output if :
{ n = 5 f = 20
if(n > t) n = 53 f = 50
return; n = 100 f = 125
System.out.print(“ .. ” + n);
fnRS(n + 2, t);
}

(d)
void fnRT(String s, int p) What will be the output if :
{ s = “PRIZE” , p = 4
if(p < 0) s = “wonder” , p = 2
return;
System.out.print(“ ” + s.charAt(p));
fnRT(s, p – 1);
}
(e)
void fnRU(String s, int p) What will be the output if :
{ s = “bingo” , p = 0
if(p >= s.length()) s = “never” , p = 10
{ s = “candle” , p = 1
System.out.print(“\n Over. ”);
return;
}
if(s.charAt(p) >= ‘a’ && s.charAt(p) <= ‘j’)
System.out.print(“ ” + s.charAt(p));
fnRU(s, p + 1);
}
(f)
void fnRV(char h, int t) What will be the output if :
{ h = ‘0’ , t = 4
if(t <= 0) h = ‘1’ , t = – 2
{ h = ‘p’ , t = 6
System.out.print(“\n Uscita.”);
return;
}
if(h == ‘0’)
h = ‘1’;
else
h = ‘0’;
System.out.print(h);
fnRV(h, t – 1);
}
qq
348
14 PACKAGES IN JAVA

l Packages

l Creation of a Package
 General form of Declaring a package
l Access Specifiers in Java
 Interaction of Objects across Packages
 Java Application Programming Interface (API)

Whenever we develop a software, we try to put all related files into one single
directory. It is a quick and easy way as long as the software is small but when the
software gets bigger, and the number of files increases, then putting all the files into the
same directory becomes difficult. To solve this problem the concept of Packages can be
used.

PACKAGES
A  package  is a namespace that organizes a set of related classes and interfaces.
Conceptually we can think of  packages  as being similar to different folders on our
computer. Logically, a package in Java is a group of related classes, interfaces, and sub-
packages. For example, a java.io package contains classes and interfaces for managing
various kinds of input and output. The default package is java.lang, which includes
primary classes and interfaces essential for Java language.
We have two types of packages in Java : built-in packages and the packages we can
create (also known as user defined packages).
Following are the built – in Java packages :
java.lang – Contains classes that support the Java language (for example–
classes which define primitive data types, math operations,
etc.). This package is automatically imported.
java.io – Contains classes for supporting input/output operations.
java.util – Contains utility classes which implement data structures like
Linked List, Hash Table, Dictionary, etc., and support for
Date/Time operations.
ISC COMPUTER SCIENCE – XI

java.applet – Contains classes for creating Applets.


java.awt – Contains classes for implementing the components of
graphical user interface (like buttons, menus etc.).
java.net – Contains classes for supporting networking operations.
Advantages of using Packages are Listed Below :
• Java package helps in organizing classes and interfaces into units so that they can
be easily maintained.
• Java package helps in reducing problems with conflicts in names.
• Java package helps in providing access protection.
• Packages provide protection to variables, methods and classes in finer ways that
can be done on class-by-class basis.

CREATION OF A PACKAGE
While creating a package, we should choose a name for the package and include
a  package  statement along with that name at the top of every source file that contains
the classes, interfaces, enumerations and annotation types that we want to include in the
package.
The package statement should be the first line in the source file. There can be only
one package statement in each source file, and it applies to all types of files.
General form of Declaring a Package
package package_name;
or
package package_name.subpackage_name;
The program code given below will illustrate how to declare our own user defined
package :
In this code segment, there are three different classes created under one package
named “myPack”. All the three classes will be saved and compiled separately under their
own class name.
//classA.java
package myPack;
public class classA
{
int add(int a, int b)
{
return a + b;
}
}

350
PACKAGES IN JAVA

//classB.java
package myPack;
public class classB
{
int sub(int a, int b)
{
return a – b;
}
}
//class C.java
package myPack.subpack1;
public class classC
{
void printResult()
{
System.out.println(“Your result : ”);
}
}
Importing User defined Packages
‘import’  keyword is used to  import  built-in and  user-defined packages into
our  java  source file so that our class can refer to a class that is in another  package  by
directly using its name.
//myClass.java
import myPack.*;
import myPack.subpack1.*;
class myClass
{
void main()
{
classA a = new classA();
classB b = new classB();
classC c = new classC();
int x = a.add(5, 6);
int y = b.sub(10, 5);
c.print();

351
ISC COMPUTER SCIENCE – XI

System.out.println(x);
System.out.println(y);
}
}
Modifiers in Java
Modifiers are keywords use to define the scope and behaviour of classes, methods
and variables in Java. Java has a wide range of modifiers that can be categorized in the
following categories :
l Access modifiers (also known as Access specifier).
l The static modifier for creating the class members (methods and variables).
l The abstract modifiers for creating abstract classes and methods.
l The final modifier for finalizing the implementation of class members.
l Synchronized, volatile and native modifiers for other purposes.

ACCESS SPECIFIERS IN JAVA


The  access  to classes, constructors, methods and fields are regulated
using access modifiers i.e., a class can control what information or data can be accessible
by other classes. A member has package or default accessibility when no accessibility
modifier is specified.
Java Access Specifiers (also known as Visibility Specifiers) regulate access to classes,
fields and methods in  Java. These  Specifiers  determine whether a field or method in a
class, can be used or invoked by another method in another class or sub-class.
Following are the different types of access specifiers in Java :
Public Access Specifier
Members (Fields, methods and constructors) declared public (least restrictive) within
a public class are visible to any class in the Java program, whether these classes are in the
same package or in another package.
Private Access Specifier
The fields or methods that are declared as private are the most restrictive and cannot
be used for other classes and interfaces. Fields, methods or constructors declared as
private are strictly controlled, which means they cannot be accessed anywhere outside
the enclosing class. A standard design strategy is to make all fields private and provide
public getter methods for them.
Protected Access Specifier
The protected access modifier cannot be applied to class and interfaces. Methods,
fields can be declared protected, however methods and fields in an interface cannot
be declared protected. The protected access modifier can be applied on data members,

352
PACKAGES IN JAVA

methods and constructors. It cannot be applied to the class. The protected access modifier
is accessible within a package and outside the package but through inheritance only.
Default Access Specifier
In Java, when no access modifier is used then it is called a default specifier. Any
class, field, method or constructor that has not declared an access modifier is accessible
only by the classes in the same package. The default modifier is not used for fields and
methods within an interface. The default access specifier is also called “package-private.”
Access within same package Access in different package
Access
specifier In same In sub In other In sub
In other classes
class class classes class
Private Yes No No No No
Protected Yes Yes No Yes No
Public Yes Yes Yes Yes Yes
Default Yes Yes Yes No No

Interaction of objects across packages


Every object which is public can be accessed from other packages, we can return
value from one package to other.
Java Application Programming Interface (API)

An application programming interface (API), in the context of Java, is a collection


of prewritten packages, classes, and interfaces with their respective methods, fields and
constructors.
Java application programming interface (API) is a list of all classes that are a part
of the Java Development Kit (JDK). It includes all Java packages, classes, and interfaces,
along with their methods, fields, and constructors.
Similar to a user interface, which facilitates interaction between humans and
computers, an API serves as a software program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API’s classes and
packages, which are helpful in minimizing the number of lines written within pieces of
code.
Java Development Kit (JDK) is comprised of three basic components, as follows :
• Java compiler.
• Java Virtual Machine (JVM).
• Java Application Programming Interface (API).
What is the use of a Java API ?
Java API is a set of methods and classes which are predefined in the Java Developmental
Kit (JDK). Thus, a programmer is able to apply prewritten code via the Java API.

353
ISC COMPUTER SCIENCE – XI

Development of Applications Using User Defined Packages : Java provides its


users with some default packages. When we start writing any code in java, the package
which is imported by default is “java.lang” package. This is often called the by default
package.
The list of classes that are included in the java.lang packages are :

There are also a lot of packages which are needed to be included in our programs to
write better or efficient codes.
Java is a friendly language that permits to create our own packages that are known
as user-defined packages and use them in programming.
User defined packages are those which are developed by a java programmer and
supplied as a part of their project to deal with common requirements.
Steps for creating User-Defined Packages in Java and using them :
1. Create a package with a class file.
2. Set the class path from the directory from which you would like to access it. It
may be in a different drive and directory. Let us call it as a target directory.

354
PACKAGES IN JAVA

3. Write a program and use the file from the package.


Example 1. : Write a program to find the value of the given expression :
C= , where n and r will be given by the user. Make a separate class that

will have a function to compute the factorial of a number n and return the same. Use
the concept of package in the above program.
package myPack;
classA
{
int factorial(int a)
{
int f = 1;
while(a > 0)
{
f *= a– –;
}
return f;
}
}
import myPack.A;
class B
{
A obj = new A();
void compute(int n, int r)
{
int f1 = A.factorial(n);
int f2 = A.factorial(r);
int f3 = A.factorial(n – r);
int res = f1/(f2 * f3);
System.out.println(res);
}
}

Example 2. : Write a program to find the sum of the given series : expression : Sum

= +...f or n terms, where the value of n and x will be given by the user. Make

separate classes that will have a function to compute the factorial and power. Use the
concept of package in the above program.

355
ISC COMPUTER SCIENCE – XI

package myPack.sub1;
class A
{
int factorial(int a)
{
int f = 1;
while(a > 0)
{
f *= a – –;
}
return f;
}
}
package myPack.sub2;
class B
{
int power(int a, int b)
{
int p = 1;
while(b > 0)
{
p *= a;
b – –;
}
return p;
}
}
import myPack.*;
class C
{
double sum = 0.0;
A obj1 = new A();
B obj2 = new B();
void compute(int n, int x)
{

356
PACKAGES IN JAVA

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


{
int p = obj2.power(x, i);
int f = obj1.factorial(i);
sum += (double)p/f;
}
System.out.println(res);
}
}
The most commonly used packages are :
Package Name Description
java.applet Provides classes necessary to create an applet and the classes
an applet uses to communicate with its applet context.
java.awt Contains all of the classes for creating user interfaces and for
painting graphics and images.
java.io Provides classes for system input and output through data
streams, serialization and file system.
java.lang Provides classes that are fundamental to the design of the
Java programming language.
java.math Provides classes for performing arbitrary-precision integer
arithmetic and arbitrary-precision decimal arithmetic.
java.net Provides classes for implementing network applications.
java.util Contains the collection of framework, legacy collection classes,
event model, date and time facilities, internationalization, and
miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).

EXERCISE

1. State True or False :


(a) Any class may be inherited by another class in the same package.
(b) Protected members of a class are accessible only to the methods of the class.
(c) A package declaration precedes all non-comment codes in a class.
(d) To access members of a class in another package, we need default as a specifier.
(e) A package can contain methods outside any class or interface.

357
ISC COMPUTER SCIENCE – XI

2. Answer the following :


(a) What is the importance of using packages in Java ?
(b) What is Java API ? How is it useful ?
(c) Differentiate between the four access specifiers of class members.
(d) What is the use of import statement in a Java program ? Illustrate with an
example.
(e) C
 reate a user defined package that will contain two classes named Rectangle and
Cuboid that will contain methods to compute area and volume of the respective
figures. Now use both of them in a menu driven program to compute the area
of a rectangle and volume of a cuboid as per the user’s choice.
(f) C
 reate a user defined package that will contain a class named Taxation with
methods to compute the tax on the annual income passed as a parameter as per
the given rules :
Annual income Tax
upto 200000 Nil
200001 to 500000 2% of amount above 200000
Above 500000 60000 + 4% of amount above 500000
Now using the above class’s method in a separate class compute the tax for n
employees where n will be entered by the user.

3. Identify the errors in the given code segments :


(a) package p1;
public class student
{ }
class test
{ }
import p1.*;
class result
{
student s1;
test t1;
}
Assume all the three classes are in different packages.
(b) package e1;
public class employee
{ }
package e1;

358
PACKAGES IN JAVA

class department
{ }
import e1.employee;
class salary
{
employee a;
department b;
}
Assume all the three classes are in different packages.
(c) package t1;
public class text1
{ }
package t2;
public class test2
{ }
import t1.*;
class result
{
test1 a;
test2 b;
}
Assume all the three classes are in different packages.
qq

359
ISC COMPUTER SCIENCE – XI

TRENDS IN
15 COMPUTING AND
ETHICAL ISSUES

l Artificial Intelligence
l Internet of things (IoT)
l Virtual Reality
l Augmented Reality
l Ethical issues in the field of Computing
l Intellectual Property
 Intellectual Property Laws and Rights
 How are Intellectual Property Rights Helpful ?
 Software Copyright and Software Patent
 Sofware Licensing
 Software Piracy
 Harms caused by Software Piracy
 The Free Software Foundation
 Open Source Software
l Netiquette
 What we should not do over the Internet
 What we should do over the Internet
 Email Etiquettes
 Various Security Threats
 Some of the Harmful Viruses on Record

ARTIFICIAL INTELLIGENCE

Artificial intelligence, commonly known as AI, is the file of computer science which
focuses on the creation of intelligent technologies that can think, work and respond like
human beings. Intelligence comprises of many non-tangible factors, such as learning,
reasoning, perception, problem-solving etc.

360
TRENDS IN COMPUTING AND ETHICAL ISSUES

Intelligent systems are embedded with artificial intelligence which extend many
helpful features. The purpose of the development of AI is to help human beings to
have an easier and comfortable life. It focuses on overcoming the common flaws that
human beings make in general such as forgetting dates and events, slow calculations and
response, confusion and miscalculation, etc. The most implying application of Artificial
intelligence is Robotics. There are many other application areas of AI, some of them are
given below :
l Image and Sound Identification.
l Temperature and Location sensors.
l Decision Making.
l Learning and Planning.
l Problem Solving.
l Calculated Predictions.
John McCarthy is known as the Father of Artificial Intelligence.
Development of technology is continuously creating wonders in the field of AI as
more and more developed systems are being invented. Driverless vehicles, home security
systems, 360-degree video cameras are to name a few and the list of AI supported systems
may seem endless today.

INTERNET OF THINGS (IoT)

It is the network of different devices that can interact with each other and can
exchange data and information. These devices can be vehicles, home appliances,
electronic gadgets, sensors and other items. Each thing is uniquely identifiable through
their embedded computing system. These systems are capable of communicating with
other systems on their own and hence, require less human intervention.

361
ISC COMPUTER SCIENCE – XI

“Internet of Things” provides a way to connect objects to one another through the
internet. This network can be controlled remotely which can effectively make modern
life more efficient and economical. Few of the many application areas are smart homes,
automated factories, intelligent transportation and so on.
Advantages of IoT

IoT allows devices to be controlled remotely across the internet, thus creating
opportunities to directly connect and intergrate the physical world to the computer-
based systems using sensors and internet. There are many advantages of IoT, few are
given below :
(i) IoT network benefits are not limited, it has a wide range i.e., individuals, society,
stakeholders of businesses etc., due to the fact that IoT network saves time and
money.
(ii) It is used for patient health monitoring i.e., various types of wireless sensors are
installed on the patient’s body which communicate with the IoT network and
provides all the required information of the patient under treatment.
(iii) IoT concept is also used in home security devices which are monitored and
controlled either locally or remotely using easy to use applications available on
mobile phones or smartphones.
Typical IoT devices like security alarm, camera, sensors, door locks, etc., are
used in automation environment.
(iv) IoT is used in asset and individual tracking, inventory control, energy
conservation etc.

362
TRENDS IN COMPUTING AND ETHICAL ISSUES

VIRTUAL REALITY
Virtual Reality (VR) means experiencing things
through computers that don’t exist in the real world. It is a
computer-simulated reality in which a user can interact with
replicated real or imaginary environments. The experience
is totally immersive by the means of visual, auditory and
haptic (touch) stimulation so, the constructed reality is
almost indistinguishable from the real deal.

AUGMENTED REALITY
Augmented reality (AR) is a technology that
superimposes a computer generated image on the user’s
view of the real world, thus providing a merged view. Unlike
virtual reality, which creates a totally artificial environment,
augmented reality uses the existing environment and
overlays new information on top of it.

Areas in which Virtual/Augmented reality application are commonly used are :


l Design Evaluation (Virtual Prototyping).
l Architectural walk-through.
l Planning and maintenance.
l Concept and data visualizations.
l Operations in hazardous environments.
l Training and simulation.
l Sales and marketing.
l Entertainment and leisure.

ETHICAL ISSUES IN THE FIELD OF COMPUTING


“Ethical Issues in the Field of Computing” provide a guideline to proper and
correct usage of computers and its applications. Many social responsibilities should be
shouldered by the citizens to ensure that the people who invent and develop useful
software and other applications are not deprived of their basic rights.
In the coming sections, let us discuss some important social and ethical issues in the
field of computing.

INTELLECTUAL PROPERTY
Intellectual Property is the result of creativity of the human intellect which is
intangible in nature. Some examples are musical notes, literary work or artistic creation

363
ISC COMPUTER SCIENCE – XI

and so on. Some theories and methods can also be included in Intellectual property.
Computer Software is considered as an Intellectual property because of its intangible
nature.
Intellectual Property Laws And Rights
There are certain Laws and Rights that guard Intellectual properties. Listed below
are some of the major Intellectual property rights (IPR).
(i) Copyright : A copyright is a legal right permitting a creator exclusive rights
for the use of his creation. It gives the right to the creator so that no one can
copy his work. However, someone can do the whole thing from the beginning
keeping the basic idea same. Copyrighted items have a symbol of ©.
(ii) Patent : It protects an “idea”. No one can work on a patented idea even if the
whole plan is new.
(iii) Trademark : It is a distinct name that is used for some kind of goods or services.
Symbol of trademark is ®.
(iv) Trade Secrets : These are certain formulas or plans that are kept confidential for
keeping the uniqueness of an item/property.
How Are Intellectual Property Rights Helpful ?
“Intellectual Property Rights” provide legal protection and security to the creators
of Intellectual Property. Intellectual properties are of immense help to the society for its
overall improvement.

Software Copyright And Software Patent


(i) A software copyright is a legal right permitting a creator of literary and artistic
works exclusive rights for its use, while a software patent is an exclusive right
granted to an inventor for new and useful inventions.
(ii) A software copyrighted work is protected right after its creation, while an
invention will be protected only after the software patent is issued.
(iii) Parts of a software copyrighted work can be used by another person, provided
it is acknowledged, while a patented work cannot be made, used or sold by
another, without permission from the software patent holder.
(iv) A software copyright costs less than software patent and are easier to acquire.
(v) A software copyright lasts generally for 60 years, while a software patent will
expire 10-20 years after it is issued.
(vi) Both software copyright and software patent owner can take legal action against
any person who infringes the copyright/patent.
Software Licensing
Software licensing is the permission given to an individual or a group to use the
Software. Before using any software, the user must ensure that the software is a licensed
software.

364
TRENDS IN COMPUTING AND ETHICAL ISSUES

Software license are of various types, some are listed below :


(i) A Software license may allow a software to be used in only one machine.
(ii) A Software license may allow a software to be used in a specific number of
machines.
(iii) A Software license may allow a software to be used in a given number of
machines but at the same time only a single machine can work on it.
Software Piracy
Piracy is the illegal copying of a software. By buying any software, a buyer does not
become the owner of that software. He only becomes a licensed user of that software and
does not get the right to sell/give his copy to others. Each and every user must buy the
software from its owner and not from its user.
Harms Caused By Software Piracy
Software piracy is unethical. Some of the harms caused are :
• Financial loss to the creative programmers, who make them.
• Causes hike in the general cost of the Software.
• Programmers lose interest in making new creative Software fearing the loss
caused by Piracy.
• Software companies loose their profits as people purchase pirated software in
place of the original software.
The Free Software Foundation
The Free Software Foundation (FSF) is a non-profit organization that supports the
free software movement. It was founded by Richard Stallman on 4th October, 1985.
The Free Software Movement promotes the freedom to create, distribute and modify
software with the creator’s permission. It is non-commercial in nature.
Open Source Software
Open Source Software is a computer software whose source code is open to all. Any
person can read, debug, modify and can sometimes even distribute the Open Source
Software.
Various Types of Licensing (E.g. GPL, BSD)
A Software license is a legal document that manages the proper usage of the software
by its creator and its users.
l General Public Licence (GPL) is a free license that allows the software to be
sold/used as a commercial object.
l Berkeley Source Distribution (BSD) is another class of license that provides
some protection to commercial use of a software, such as giving due credit to the
creator of a software, protect the creator from certain non-functioning part of a
software etc.

365
ISC COMPUTER SCIENCE – XI

NETIQUETTE
Etiquette to be followed while using the Internet, is called Netiquette.
With the Internet proving to be so very useful to us, we should also be careful and
sincere from our side. Ignorant or careless attitude may prove to be harmful to the society
and can cause unnecessary trouble to millions of users who use the Internet.
What We Should Not Do over the Internet :
(i) We should not use the computer to harm other people in any way.
(ii) We should not interfere with other people’s work.
(iii) We should not disturb someone who is working on something important on the
computer.
(iv) We should not spread wrong or harmful messages through the Internet.
(v) We should not go to those Web Sites for which we do not have permission.
What We Should Do over the Internet :
(i) We should be helpful to people who are learning.
(ii) We should always use proper language and correct information in our messages.
(iii) We should always write messages with proper subject so that if the receiver is
busy, he can decide whether he should give immediate attention to our message
or can he read it later.
(iv) We should be proud of our own culture and should respect the cultures from all
over the world as well. It will help in developing a beautiful relationship with
people from all over the world through the Internet.
(v) We should stop our friends from doing wrong things on the computer.
Email Etiquettes
Etiquette means good manners. As a responsible citizen, one should maintain certain
email etiquettes.
A person Should Not Do the following Over the Email :
(i) Ask or acquire other’s email password.
(ii) Open/use other’s email account.
(iii) Forward gossips/false news via email.
(iv) Forward meaningless mails to others.
(v) Send mails without subject as subject helps the receiver to know its importance.
A person Should Do the following Over the Email :
(i) Help new users.
(ii) Use bcc in case a mail has to be sent/forwarded to various people.

366
TRENDS IN COMPUTING AND ETHICAL ISSUES

(iii) Remove the chain of addresses in case of multiple forwarding.


(iv) Send/reply formal mails by maintaining the standards.
(v) Remember that alphabets in Upper Case indicate loudly spoken words. Avoid
uppercase if not necessary.
Various Security Threats
Computers these days are subject to various security threats, which can cause many
different types of damages. Some security threats are given below :
VIRUS
Most people have heard of computer viruses, but not many know exactly what they
are or what they do.
What they are :
• Malicious computer programs that are often sent as an email attachment or a
download with the intent of infecting your computer, as well as the computers
of everyone in your contact list. Just visiting the site can start an automatic
download of the virus.
What they can do :
• Send spam.
• Provide criminals with access to your computer and contact lists.
• Scan and find personal information like passwords on your computer.
• Hijack your web browser.
• Disable your security settings.
• Display unwanted ads.
When a program is running, the virus attached to it could infiltrate your hard drive
and also spread to USB keys and external hard drives. Any attachment you create using
this program and send to someone else could also infect them with the virus.
HACKING
Hacking is a term used to describe actions taken by someone to gain unauthorized
access to a computer. The availability of information online about the tools, techniques,
and malware makes it easier for even non-technical people to undertake malicious
activities.
What it is :
The process by which cyber criminals gain access to your computer.
What it can do :
Find weaknesses (or pre-existing bugs) in your security settings and exploit them in
order to access your information.
• Install a Trojan horse, providing a back door for hackers to enter and search for
your information.

367
ISC COMPUTER SCIENCE – XI

MALWARE
Malware is one of the most common ways to infiltrate or damage your computer.
What it is :
Malicious software that infects your computer, such as computer viruses, worms,
Trojan horses, spyware, and adware.
What it can do :
• Intimidate you with scare ware, which is usually a pop-up message that tells you
your computer has a security problem or other false information.
• Reformat the hard drive of your computer causing you to lose all your information.
• Alter or delete files.
• Steal sensitive information.
• Send emails on your behalf.
• Take control of your computer and all the software running on it.
PHISHING
Phishing is used most often by cyber criminals because it’s easy to execute and can
produce the results they’re looking for with very little effort.
What it is :
Fake emails, text messages and websites created to look like they’re from authentic
companies. They’re sent by criminals to steal personal and financial information from
you. This is also known as “spoofing”.
What it does :
• Trick you into giving them information by asking you to update, validate or
confirm your account. It is often presented in a manner than seems official and
intimidating, to encourage you to take action.
• Provides cyber criminals with your username and passwords so that they can
access your accounts (your online bank account, shopping accounts, etc.) and
steal your credit card numbers.
SPAM
Spam is one of the most common methods of both sending information out and
collecting it from unsuspecting people.
What it is :
• The mass distribution of unsolicited messages, advertising or pornography to
addresses which can be easily found on the Internet through things like social
networking sites, company websites and personal blogs.
• Canada’s anti-spam legislation applies to all commercial electronic messages.
A commercial electronic message is any electronic message that encourages
participation in a commercial activity, regardless of whether there is an
expectation of profit.

368
TRENDS IN COMPUTING AND ETHICAL ISSUES

What it can do :
• Annoy you with unwanted junk mail.
• Create a burden for communications service providers and businesses to filter
electronic messages.
• Phish for your information by tricking you into following links or entering details
with too-good-to-be-true offers and promotions.
• Provide a vehicle for malware, scams, fraud and threats to your privacy.
TROJAN HORSES
Trojan Horse is a malicious program that is disguised as, or embedded within,
legitimate software. It is an executable file that will install itself and run automatically
once it’s downloaded.
What it can do :
• Delete your files.
• Use your computer to hack other computers.
• Watch you through your web cam.
• Log your keystrokes (such as a credit card number you entered in an online
purchase).
• Record usernames, passwords and other personal information.
WORMS
Worms are a common threat to computers and the Internet as a whole.
What they are :
A worm, unlike a virus, works on its own without attaching itself to files or programs.
It lives in your computer memory, doesn’t damage or alter the hard drive and propagates
by sending itself to other computers in a network – whether within a company or the
Internet itself.
What they can do :
• Spreads itself to everyone in your contact list.
• Cause a tremendous amount of damage by shutting down parts of the Internet,
wreaking havoc on an internal network and costing companies enormous
amounts of lost revenue.

Some of The Harmful Viruses On Record


Flame : It is said to be the first of its kind that uses Bluetooth as its spread medium.
It was first detected in a Russian lab.
Crime Virus : This virus spread globally and asked the users for some vital
information and a processing fee, claiming that it was for police records.
Shamoon : This virus is dangerous as it creates files of the data on your hard disk,
and then this compiled data is sent to the attacker.

369
ISC COMPUTER SCIENCE – XI

Beside these, there are many other computer viruses that have the potential to infect
your digital data. Hence, it is must that you should protect your data by installing a
genuine quality antivirus software.

EXERCISE

1. Fill in the blanks :


(a) The full form of AI is ______________ .
(b) Smart home security system applies ______________ .
(c) The two types of reality are _____________ and ______________ .
(d) ________________ means experiencing things through our computers.
(e) Trade secrets help to keep __________ of an item.
(f) Piracy is the __________ copying of software.
(g) A software _________ ( can/cannot ) be resold.
(h) Intellectual property is ________ in nature.
(i) _____ gives the right to the creator that no one can copy the same.
2. Write a brief note on :
(a) Virtual reality (b) Agent and Environment
(c) Augmented reality (d) Artificial Intelligence
(e) Speech Recognition (f) Copyright
(g) Trademark (h) Piracy
(i) Netiquette (j) Phishing
(k) Spam (l) Patent
(m) Hacking
3. Identify the following :
(a) It protects an “idea”. No one can work on this idea even if the whole plan is new.
(b) These issues in the field of computing provide a guideline to proper and correct
usage of computers and its applications.
(c) It is a distinct name that is used for some kind of goods or services. Its symbol
is ®.
(d) Financial loss to the creative programmers, who make them.
(e) These are harmful computer programs that cause damage to the information
stored in the computer memory.

370
TRENDS IN COMPUTING AND ETHICAL ISSUES

4. Answer the following :


(a) What do you mean by Artificial Intelligence ?
(b) Write the benefits of Artificial Intelligence.
(c) What are the areas, where we use Artificial Intelligence ?
(d) Write the difference between Virtual reality and Augmented reality.
(e) What do you mean by IoT ?
(f) Write any five advantages of IoT.
(g) What are the harms caused by Software Piracy ?
(h) What is Software Licensing ?
(i) What are the differences between Software Copyright and Software Patent ?
(j) What is Intellectual Property ?
(k) What should a person not do over email ?
(l) Write briefly about any two types of licensing.

qq

371
16 ALGORITHM

l Algorithm
 Need of an Algorithm
 Various forms of Algorithm
l Pseudocode
l Flowchart

ALGORITHM
An algorithm is a stepwise detail of a process. Every process is made up of smaller
steps and explaining the process with the help of these smaller steps forms its Algorithm.
The most simple and common algorithm that is used by almost everyone is the
cookbook. A cookbook contains stepwise details of how to cook, which recipe.
For example, consider the steps of making “Tea”
Step 1 : Boil water.
Step 2 : Put fire off, and add tea leaves to the water.
Step 3 : When the color of water changes and nice
aroma comes out, stain the leaves, and pour
the tea in cups.
Step 4 : Serve the tea along with sugar and snacks.

Need of An Algorithm
Every process needs an explanation in simple language. If the algorithm of a process
is not written in a clear and proper manner it will become very difficult to put that task
into action. Every beginner needs an algorithm to start a task.
Every program has an algorithm. The algorithm written for a program is preferred
to be independent of the programing language. It should be written in simple language.
Algorithms are also very helpful to do the initial analysis of a problem. Programmers
working on big projects first do the problem analysis, then they make the algorithm of
the solution and after a satisfactory algorithm is approved, they start working on the
program.
ALGORITHM

Algorithm for the verification of a Prime number :


Step 1 : Input a number say, n.
Step 2 : Count its total factors and store in say
cf.
Step 3 : If cf = 2 then print n is prime.
Step 4 : If cf > 2 then print n is not prime.
Step 5 : End.

Various Forms of Algorithm


Among the other equivalents of algorithms are Pseudocodes and Flowcharts.

PSEUDOCODE
A Pseudocode is an algorithm that is very close to a program. It allows many
program syntax-like statements. However, a Pseudocode is not a program and so, it is
not executable.
Example : A Pseudocode that repeatedly asks for entry of a number in the range 1
to 100 until a valid number is entered.
REPEAT
DISPLAY “Enter a number between 1 and 100”
ACCEPT number
UNTIL number > 50 OR number < 60
END
The above Pseudocode can also be written as :
DO
PRINT “Enter a number between 1 and 100”
INPUT num
WHILE(n > 50 OR n < 60)
END
Some keywords that are allowed in pseudocodes are :
1. Since a Pseudocode is very close to a program, many meaningful programming
terms can be used in it. However a Pseudocode should not entirely be a program
code.
2. For simple input output, general terms such as INPUT, ACCEPT, PRINT,
DISPLAY, etc., are allowed.
3. For conditional statements, IF .. ELSE IF .. ELSE can be used.
4. For looping, quite a few forms are allowed, few of which are DO..WHILE,
REPEAT UNTIL, etc.
5. For loop counters, INCREMENT, DECREMENT are accepted. More similar terms
are also allowed in a Pseudocode.
6. Unlike Algorithm, Pseudocodes are written to explain a program by giving the
least language explanation.

373
ISC COMPUTER SCIENCE – XI

Example : A Pseudocode to print the factors of a number—


INPUT num
ASSIGN 1 to f
REPEAT
IF f is a factor of num THEN PRINT f
INCREMENT f
UNTIL (f > num)
END

FLOWCHART
A flowchart is a diagrammatic or pictorial representation of the steps of doing some
work.
A flowchart uses different symbols for different steps of work.
Given below are the general flowchart symbols :
1. Start / Stop box 2. Process box 3. Input / Output box


4. Decision box 5. Flowlines 6. Connectors

A

Example 1 : Enter a number in a variable m. Calculate the square of m and store in
variable s. Print the value of variable s. [Input Process Output]
Check the output of the
flowchart if the value entered
is :
(i) 4 (ii) 6 (iii) 8

374
ALGORITHM

Example 2 : Input the age of a person in variable a. If his age is more than or equal
to 60, print “Senior Citizen” otherwise print “Non Senior Citizen”. [Input Condition
Output]

Check the path


and output of
the flowchart if
the variable a
is—
(i) 45 (ii) 75
(iii) 60 (iv) 59
(v) 61

Exercise 3 : Print numbers from 1 to 500. [Simple Loop]

Variable n starts with 1.


It is printed and the
value of n is increased by 1 as
long as n <= 500.

YES
<=

NO

375
ISC COMPUTER SCIENCE – XI

Exercise 4 : Count how many students got distinction out of 50 students.


[Condition in a Loop]
• Variable rn(roll number) starts with 1.
• For each rn, marks M is entered and if it is >= 80 , counter c increases by 1.
• rn increases by 1 and the process repeats as long as it is not more than 50.
• Finally the counter c is printed.

EXERCISE

1. Write an Algorithm for the following (5 - 7 steps) :


(a) Planting a sapling.
(b) Conducting an exam.
(c) Organizing a picnic.
(d) Booking an online Railway ticket.

376
ALGORITHM

2. Write a Pseudocode for the following :


(a) Print the digits of a number in separate lines.
(b) Print the total number of prime elements present in an array.
(c) Print the multiplication table of a number.
(d) Print the largest element present in a list of 10 elements.

3. Draw a Flowchart for the following :


(a) Print “Profit” or “Loss” incurred on an item by asking for Cost and Sell Price.
(b) Count and print the number of failures in an exam. Input the total marks of each
candidate and let there be 50 candidates. Assume the passing marks to be 40.
(c) Operation of a bank ATM counter.
(d) Print the roots of a Quadratic Equation using Sri Dharacharya’s formula.

4. Complete the given flowcharts with suitable tasks :

(a)

(b)

377
ISC COMPUTER SCIENCE – XI

5. The given flowcharts have some Logical Errors. Identify and correct them. Also
write the output of the flowcharts :
(a)
Start

Input N

Let S = 0, j = 1

S=S+j

j=j+1

YES
Is j  N ?

NO
Print S

Stop

(b)

378
ALGORITHM

(c)
Start

Input M, N

Let P = M

Print M

P=P+1

NO
Is P  N ?

YES
Stop

(d)

qq

379
ISC COMPUTER SCIENCE – XI

PROGRAMS AND
17 ALGORITHMS


l Programs
l Algorithms
l Programs Solutions

PROGRAMS

Topic 1 Loops and Conditions


1. Print and count the factors of a number.
2. Summation of a number n = 1 + 2 + 3 + … + n; For e.g., n = 5, summation n = 15.
3. Factorial of a number n = 1 * 2 * 3 * …. * n; For e.g., n = 5, factorial n = 120.
4. Digits of a number (Print, Count, Add, Multiply, Reverse, Largest Digit).
5. All Common factors of two numbers.
6. All Common Multiples of two numbers.
7. Print n (int) numbers lying between two variables w and z.
8. Calculate and print S7 = 1 + 2 + 4 + 8 + 16 + 32 + ………. upto n terms.
9. Roots of a quadratic equation using Sri Dharacharya’s formula.
For e.g., ax2 + bx + c = 0 Roots = (– b + (b2 – 4.ac)1/2) / 2.a
Topic 2 Application of Flags (optimized operation)

1. Verify whether at least one of the array elements is even or not.


2. Verify whether all the array elements are even or not.
3. Verify whether all 25 students passed the subject examination or not.
4. Verify whether at least one student scored full marks out of 25 students or not.
5. Verify whether a number n, has at least one factor between 2 and its half (n/2) or
not.
6. Verify whether all the elements in an array are 0 or not.

380
PROGRAM AND ALGORITHMS

7. Verify whether at least one element in the array is a multiple of 5 or not.


8. Verify whether all the other elements are larger than the first element in an array
or not.
9. Verify whether a string contains at least one occurrence of ‘q’.
10. Verify whether every word in a string begins with ‘s’ or not.
11. Verify whether 2 One Dimensional arrays contain the same set of numbers at the
same positions.
12. Verify whether 2 One Dimensional arrays contain at least one common element .
13. Verify whether 2 One Dimensional arrays contain the same set of numbers at any
position.
14. Verify whether 2 One Dimensional arrays contain no common elements.
15. Verify whether an array is pre-sorted or not [do not sort the array].
Topic 3 Patterns using Nested Loops

In the following patterns, n = 5. Instead of numbers, characters of a string can also


be taken.
(i) (ii) (iii) (vii)
54321 12345 1 123454321
4321 2345 101 1234321
321 345 10101 12321
21 45 1010101 121
1 5 101010101 1
121
12321
(iv) (v) (vi) 1234321
5 5 123454321 123454321
54 45 1234321
543 345 12321
5432 2345 121
54321 12345 1
Topic 4 Methods or Functions
1. Input a year and verify if it is Leap or not.
A year is Leap if it is — (i) Divisible by 4 and not by 100.
OR
(ii) Divisible by 400.

381
ISC COMPUTER SCIENCE – XI

2. Input a number and verify if it is Prime or not.


A prime number has a total of only 2 factors i.e., 1 and the number itself.
3. Input a number N and input two limits (L1, L2). Print the Multiplication Table of
N from Limit L1 to Limit L2.
4. Input a number N. Print its Prime Factors.
5. Calculate and print S1 = 1!+ 2! + 3! + 4! + 5! + …….. upto n terms, where n is user
input and K! = 1 * 2 * 3 * … * K.
6. Calculate and print S2 = 1$ + 2$ + 3$ + 4$ + ………. upto n terms, where n is user
input and K$ = 1 + 2 + 3 + … + K.
7. Calculate and print S3 = ( 1! / 1$ ) + ( 2! / 2$ ) + ( 3! / 3$ ) + ( 4! / 4$ ) + ……..
upto n terms.
8. Input a number N and verify if it is Palindrome or not. [N = its Reverse].
9. Input a number and verify if it is a Krishnamurthy number or not. To be a
Krishnamurthy number – Sum of the factorial of the digits = the number itself.
E.g., 145  1 + 4! + 5!  1 + 24 + 120  145
10. Armstrong number – Sum of cube of digits = number itself
E.g., 153  1^3 + 5^3 + 3^3  1 + 125 + 27  153
11. D-Factors are a pair of factors of a number where one is the double of the other.
For example N
= 24, factors - 1 2 3 4 6 8 12 24
D-Factors will be (1, 2), (3, 6), (4, 8), (6,12), (12, 24).
12. Perfect Square –
Square of the Square root of a number = number itself.
E.g., : (√25)2 = (5)2 = 25… 25 is a perfect square.
(√10)2 = (3.33)2≠10 10 is not a perfect square.
13. Perfect Number — Sum of the factors excluding itself is equal to the number
e.g., : 28
Sum of factors of 28 except itself : (1 + 2 + 4 + 7 + 14) = 28
Hence, 28 is a perfect number.
l Input n, assume Sum of factors (sf) = 0.
l Run a loop of f from 1 to n/2, and for each factor in this range, add it to sf.
l Verify whether sf is equal to n, if so, then n is a perfect number else not so.
14. Magic Number — Subsequent sum of digits is 1
e.g., : 991, sum of digits (9 + 9 + 1) = 19 → sum of digits (9 + 1) = 10 → sum of

digits (1 + 0) = 1.
Hence, 991 is a Magic Number.
l Input n, copy it in cn, assume s = 0.
l Find the sum of digits of cn and store in s and copy it back in cn as long as
cn > 9.
l Refresh s each time.

382
PROGRAM AND ALGORITHMS

15. A number is called a Smith Number if the sum of the digits of the number is
equal to the sum of the digits of the prime factors of the number.
e.g., : 666
Prime factors are 2, 3, 3, and 37.
Sum of the digits are (6 + 6 + 6) = 18
Sum of the digits of the prime factors (2 + 3 + 3 + (3 + 7)) = 18
Hence, 666 is a Smith Number.
l Input n.
l Generate its prime factors and add the digits of the prime factors to s.
l Hint : Use a method that adds the digits of a number.
l Compare the sum of the digits of the number with the sum of the digits of
the prime factors.
Topic 5 Arrays – One Dimensional
1. Find the sum of the prime elements of the array.
2. Input a number N. Fill an array with its factors.
3. Fill an array with variables. Verify if it is symmetric or not.
4. Fill an array and print its Max and Min elements along with their positions.
5. Perform left/right shift (linear and circular) on the elements of an array.
6. Calculate Mean, Median, Mode for a given set of data.
Topic 6 Arrays – Two Dimensional
1. Fill a 2D array with variables. Print the left diagonal and its sum.
Also print the right diagonal and its sum.
2. Compare 2 2-D arrays and verify whether all the elements are same cell to cell
3. Compare 2 2-D arrays and verify whether they have any common elements or
not.
4. Print Row-wise and Column-wise Sum and, Maximum and Minimum elements.
5. Create a vertical and horizontal Mirror Matrix.
6. Print the Upper and Lower matrix of a square matrix.
Topic 7 APPLICATION I
1. For a number, if the sum of the digits is 9 then it is a multiple of 9. Even for large
numbers, if the recurring sum of the digits becomes 9, then it is a factor of 9. E.g.,
72, 8415.
Input a number N and verify if it is a multiple of 9 or not by applying the above
process.
2. Input a number N and divide it into two parts digit wise.
If the number has n number of digits and if n is even, then both parts will have
same number of digits (n/2).

383
ISC COMPUTER SCIENCE – XI

If n is odd then the first part will contain (int) n/2 number of digits and the
second part will contain (int) n/2 – 1 number of digits.
For example – n = 2453  Part 1 = 24 Part 2 = 53
For example – n = 2714369  Part 1 = 271 Part 2 = 4369
3. Input a number and verify if it is Palindrome or not. (N = Reverse(N)).
4. 
Assume two integers represent them as numerator and denominator of a
Fraction. Present it in its reduced form.
For example, n = 40; d = 12
After reduction, n = 10; d = 3
5. Automorphic Number - Its square ends by the number itself.
For example — 52 = 25 762 = 5776 8906252 = 793212890625
Some other examples – 6, 25, 376, 625, 9376, etc.
6. c/5 = (f – 32)/9 c = k – 273
Convert temperature from one unit to another. Input the value and unit and
calculate the value in other units. (Celsius, Kelvin or Fahrenheit)
Topic 8 APPLICATION II
Input a string (for question numbers 1 to 5) and :
1. convert it to Uppercase / Lowercase.
2. verify whether it is in Uppercase / Lowercase.
3. verify whether it represents a valid binary number or not.
4. perform toggle case (upper case to lower and vice versa).
5. move the characters by n on the alphabet line (assume circular list of alphabets).
For reference ASCII [‘A’ = 65 ‘a’ = 97 ‘0’ = 48]
Input a sentence (string) (for question numbers 6 to 12) :
6. Print those words that begin with a vowel.
7. Print each word and the number of vowels present in it in new line each.
8. Print the sentence with the letters of each word reversed.
9. P
 rint the sentence with the words in reverse order (last word first, letters of each
word unchanged).
10. Input the full name of a person and print the initials.
11. Count how many words in the string are Palindrome.
12. Verify if the sentence is word wise Palindrome.
E.g., Did I say I Did
13. Input two strings and print the common characters.
14. Input two string sentences and verify whether both of them have the last word
common.
15. Input a string and print the words in ascending order of length.

384
PROGRAM AND ALGORITHMS

Topic 9 Application III


1. Input a number and verify whether it is a Perfect Square or not. (square of the
squar root of a number is the number itself) (avoid using Math built in methods,
if possible).
2. Input a number and find it’s Square Root (do not use built in methods). In case
the result is not a proper integer, find upto 2 places.
3. S1 = 1@ + 2@ + 3@ + 4@ + …. w
here k@ is the sum of the factors of k.
4. S2 = 5 + 102 + 15 + 202 + 25 + … (n terms).
5. S3 = 2 + 42 + 63 + 84 + 105 + …
6. S4 = an y1 + an-1 y2 + an-2 y3 + an-3 y4 + …
7. S5 = = – 1 * 2 + 3 * 4 – 5 * 6 + 7 * 8 – …
8. S6 = 0 + 7 + 26 + 63 + 124 + ….
9. S7 = 1 + 4 + 3 + 16 + 5 + 36 + …
10. S8 = (12 * 23) + (22 * 33) + (32 * 43) + …
11. S9 = n.C.k + (n – 1).C.(k + 1) + (n – 2).C.(k + 2) + (n – 3).C.(k + 3) + (n – 4).C.
(k + 4) + ….. till n > 0;  where p.C.q = (p!) / (q! × (p – q)!)
12. S10 = (1 * 2 * 3) + (3 * 4 * 5) + (5 * 6 * 7) + …
Topic 10 Project Programs
1. Digit Handling in a Number
Various digit handling operations on a number using methods, controlled by a
menu in the main() method.
Few operations are suggested : sum / product of digits; largest / smallest
digit; prime digits; sum of even / odd digits; count digits; average of digits;
rearrangement of digits so as to form another number.
2. Calculator
A simple calculator, that performs arithmetic calculations on two variables and
gives the choice of continue or refresh to carry on.
3. Set Application
A set is a collection of unique elements. Perform Union, Intersection, Difference
on Sets.
4. Sort – Bubble , Selection , Insertion, Search – Linear , Binary
Perform all the above operations using various methods and connect them using
a menu in the main() method.
5. Count the Frequency of each element in an array
Print the frequency of each element without repetition.
6. Shrink / Pack an array
Remove the duplicate elements present in an array, without using another array.
385
ISC COMPUTER SCIENCE – XI

7. Binomial Series
Input a, x, n, and calculate the result of the Binomial Series, given that (a + x) ^ n
= nC0 * a^n * x^0 + nC1 * a^(n – 1) * x^1 + … + nCr * a^(n – r) * x^r + .. + nCn *
a^(n – n) * x^n
where – nCr = n! / ( r! x (n – r) ! )
Suggested methods :
fnFactorial(n) : to calculate the factorial of n which is 1 * 2 * 3 * … * n.
fnPower(a, b) : to calculate a ^ b.
fnNCR(n, r) : to calculate the combination of n, r.
fnSeries(a, x, n) : to calculate the sum of the binomial series using the above
methods.
8. Conversion of a number from one base to another.
A decimal number can be converted to binary by continuous division.
A binary number can be converted to decimal by multiplying the digit with its
base raised to its place value.
Similar is the rule to convert to / from decimal to any other base.
9. Operations in an ATM
In a bank an ATM counter was set up. It was given revenue notes of denomination
1000, 500, 100 and 50. For each denomination, x number of notes were entered
in the beginning. With each customer coming and withdrawing money, write a
code to handle the balance left in the ATM Machine and print comments such as
“Machine out of order” when insufficient amount is left in the machine. [Prepare
a solution of the problem situation].
10. Date Handling
Dates are such that a plenty of codes can be coded out of them. Here are a few
samples…
Year 2006 started with Sunday. The previous year started one day back and the
next year started one day next provided there was no leap year in between.
(i) For a given year, use the above reference to find the first day of that year.
(ii) Verify whether a date is valid or not.
E.g., 31-02-1950 is INVALID 1-01-2009 is VALID
31-08-2002 is VALID 31-11-2010 is INVALID
Hint : Use an array to store the month ends.
Use a method to test whether the given year is leap or not.
(iii) Julian day is the day number, where 1st Jan is considered day number 1 and the
count begins. Julian day value of 1st Feb is 32. For a non-leap year, Julian day
value of 31st Dec. is 365.
Input a date and print its Julian day value with respect to that year.

386
PROGRAM AND ALGORITHMS

(iv) Input a Julian day and its corresponding year and find the respective date.
(v) For two given dates, find the number of days in between.
(vi) Count the number of Sundays between two dates.
(vii) Given a date, add a given number of days to it and find the new date.
(viii) If a month starts with a given weekday (1 – Sunday … 7 – Saturday), find the
starting day of the next month.
(ix) For a given date, find its day.
(x) Print a month in a 5 × 7 two dimensional format, given its starting weekday
number.
(xi) Print the Calendar of any given year.

ALGORITHMS
In this section, some of the procedures are explained.
Topic 1 Loops and Conditions
1. Print and count the Factors of a number (n).
• The factors of n range between 1 and n.
• Not all the numbers in the range are factors of n.
• Use a loop of f to generate all the numbers in the range.
• Verify whether each value of f is a factor of n or not.
• If it is a factor, then print it and also increase the counter.
• Print the counter outside the loop of f.
• Multiple factors to be printed on condition, total factors to be printed once.
2. Summation of a number n = 1 + 2 + 3 + … + n; For ex n = 5, summation n = 15.
• In this series the term numbers co-inside with the term values.
• The sum of the series is calculated by using another variable, (tsum), which
starts with 0 and adds the next term to it each time.
• For each term, new sum = previous sum + next term

Term Val
1 2 3 4 5 …
1 2 3 4 5 upto n
Term Num
TSum 0 + 1 = 1 1 + 2 = 3 3 + 3 = 6 6 + 4 = 10 10 + 5 = 15 terms
• The program has only one output, the sum of the series, to be printed. The
output statement, therefore, should occur out of the loop bounds.
3. Factorial of a number n = 1 * 2 * 3 * …. * n; For ex n = 5, factorial n = 120.
• Same as above, except that that the numbers are getting multiplied, and the
result begins with 1.
4. Digits of a number (Print, Count, Add, Multiply, Reverse, Largest Digit)
Digit Extraction–
387
ISC COMPUTER SCIENCE – XI

• When a number (n) is divided by 10, the remainder is the last digit and the
quotient is the first part without the last digit
For example, n = 3496, divide by 10, remainder = 6, quotient = 349.
• To print the digits of a number, a number is divided by 10, remainder gives
the last digit, quotient gives the reduced number. The division is repeated till
the number does not become 0.
Example : n = 5842;
working steps–
5842 >= 0 true r=2 print r n = 584
584 >= 0 true r=4 print r n = 58
58 >= 0 true r=8 print r n=5
5 >= 0 true r = 5 print r n=0
0>0 false
[application of integer division]
Creating Reverse of a Number –
• To create a number, we can use the place value of its digits.
Such as 7259 = 7 × 1000 + 2 × 100 + 5 × 10 + 9
• To create a the reverse of a number, we can use the digits from the end,
one by one, as shown n  — the number; cn — copy of the number n, which
changes each time.
r – the last digit each time rev – the new num each time (prev value × 10 + r)
n = 5842
cn = n;
5842 >= 0 true r = 2 rev = 0 * 10 + r = 2 cn = 584
584 >= 0 true r = 4 rev = 2 * 10 + r = 24 cn = 58
58 >= 0 true r = 8 rev = 24 * 10 + r = 248 cn = 5
5 >= 0 true r = 5 rev = 248 * 10 + r = 2485 cn = 0
0>0 false
Counting Digits–
• Initiate a counter to 0.
• Increase the counter by 1 each time the number is divided by 10 till it becomes
0.
5. All Common Factors of two numbers
• Factors range between 1 and the number itself.
• For two numbers, the common factors range between 1 and the smaller
number (since the larger number cannot be a common factor, but the smaller
number may).
• Verify whether each value in the range is a factor of both the numbers or not.

388
PROGRAM AND ALGORITHMS

6. All Common Multiples of two numbers


• Multiples are larger numbers (given by multiplication table).
• For two numbers, the common multiples range between the larger number
and the product of the two numbers.
• Verify whether each value in the range is a multiple of both the numbers or
not (if f is a factor of n then n is a multiple of f).
7. Print n (int) numbers lying between two variables w and z.
8. S7 = 1 + 2 + 4 + 8 + 16 + 32 + ………. upto n terms.
• In this series, each term is the double of the previous term.
• The terms are to be generated inside the loop.
• Add the terms inside the loop.
• Print the result outside the loop.
9. Roots of a quadratic equation using Sri Dhar acharya’s formula.
For e.g., ax2 + bx + c = 0 Roots = (–b + (d)1/2) / 2.a where d = (b2 – 4.a.c)
• Input a, b, c.
• If a = 0, then the equation is invalid (div by 0).
• If d = 0, the roots are equal.
• If d > 0, the roots are unequal and real
• If d < 0, the roots are unequal and imaginary.
u T
o print imaginary roots, the absolute value of d is used, its square root is
found, and it is printed along-with i to indicate it as imaginary.
Topic 2 : Application of Flags (optimized operation)

1. Verify whether at least one of the array elements is even or not.


• Assume the array contains no even elements (pe = false).
• Run a loop of j from 1 to array.length[ ].
• Check each element for being even.
• If any element is even, set pe to true and terminate the loop.
• If no element is even, pe remains false.
• Return pe.
[Here the hunt is for an even element].
2. Verify whether all the array elements are even or not.
• Assume the array contains all even elements (pe = true).
• Run a loop of j from 1 to array.length[ ].

389
ISC COMPUTER SCIENCE – XI

• Check each element for being even.


• If any element is odd, set pe to false and terminate the loop.
• If no element is odd, pe remains true.
• Return pe.
[Here the hunt is for an odd element]
3. Verify whether all 25 students passed the subject examination or not.
• Assume that all students passed the subject examination (pe = true).
• Run a loop of j from 1 to 25.
• Enter the marks of one student at a time in m.
• If any student fails, pe becomes false (i.e, all students did not pass) and
terminate the loop.
• If no student fails, then pe remains true.
• Return pe.
[Here the hunt is for a failing mark]
4. Verify whether at least one student scored full marks out of 25 students or not.
• Assume that no one scored full marks (fm = false).
• Out of 25 students, if any student scores full marks, fm becomes true.
• If no student scores full marks, then fm remains false.
• Return fm.
[Here the hunt is for one student getting full marks]
5. Verify whether a number n, has at least one factor between 2 and its half n/2.
• Assume that there is no factor between 2 and n/2 (fe = false).
• In the range, if one factor is found, fe becomes true and the loop terminates.
• If no factor is found, fe remains false.
• Return fe.
[Here the search is for one factor in the given range]
6. Verify whether all the elements in an array are 0 or not.
7. Verify whether at least one element in the array is a multiple of 5 or not.
8. Verify whether all the other elements are larger than the first element in an
array or not.
• Assume that the other elements are larger (le = true).
• Search for at least one smaller element, which if found then le = false.
[Here the search is for one element smaller than the first element].
9. Verify whether a string contains at least one occurrence of ‘q’.
• Assume that the result is false.
• Search for at least one occurrence of ‘q’ , which if found, result becomes true.
390
PROGRAM AND ALGORITHMS

10. Verify whether every word in a string begins with ‘s’ or not.
• Assume that the result is true.
• Search for at least one word that does not begin with ‘s’ , which if found,
result becomes false.
11. Verify whether 2 one-d arrays contain the same set of numbers at the same
positions.
• Assume that the result is true.
• Search for at least one non equal element in the corresponding cells and the
result becomes false.
12. Verify whether 2 one-d arrays contain at least one common element.
• Assume that the result is false.
• For each element of the 1st array, search it in the 2nd array. (a nested loop)
• If any element is found common, result is true, the loop terminates.
[Program code applies label in Java to break nested loop]
13. Verify whether 2 one-d arrays contain the same set of numbers at any position.
• Assume that the result is true.
• For each element of the 1st array, search it in the 2nd array. (a nested loop)
• If any element (of 1st array) is not found in the 2nd array, result is false, and
the loop terminates.
14. Verify whether 2 one-d arrays contain no common elements.
• Assume that the result is true.
• For each element of the 1st array, search it in the 2nd array. (a nested loop)
• If any element (of 1st array) is found in the 2nd array, result is false, and the
loop terminates.
15. Verify whether an array is pre-sorted in ascending order or not [do not sort the
array].
• Assume that the result is true.
• Compare each element with its next.
• If for any pair, the next element is smaller than the element itself then, the
result becomes false and the process terminates.
Topic 3 Patterns using Nested Loops

(i) 5 4321 for (r = n; r >= 1; r – –) // outer loop is


4 321 { decreasing.
3 21 for(c = r; c >= 1; c– –) // inner loop is
2 1 { decreasing.
1 System.out.print(“ ” + c); // inner loop, lower
} limit is variable,
upper limit is
System.out.println();
fixed.
}

391
ISC COMPUTER SCIENCE – XI

(ii) 1 2 3 4 5 int r = 0, c = 0, n = 5;
2 3 4 5 for(r = 1; r <= n; r++)
3 4 5 {
4 5 for(c = 1; c < r; c++)
5 {
System.out.print(“ ”);
// to print leading spaces in each row
}
for(c = r; c <= n; c++)
{
System.out.print(“ ” + c);
}
System.out.println();
}
(iv) 5 for(r = n; r >= 1; r– –) // outer loop is
5 4 { decreasing.
5 43 for(c = n; c <= r; c++) // inner loop is
decreasing.
5 432 {
// inner loop, lower
5 4321 System.out.print(“ ” + c); limit is fixed,
} upper limit is
System.out.println ( ); variable.
}
(viii) 1 2 3 4 5 4 3 2 1 void main()
1234321 {
1232 1 int r = 0, c = 0, n = 5;
121 // upper part
1 for(r = 5; r >= 1; r– –)
{
121
for(c = n; c > r; c– –)
1232 1
{
12343 21
System.out.print(“ ”);
123454 3 2 1 // to print leading spaces in each row
}
for(c = 1; c <= r; c++)
{
System.out.print(“ ” + c);
}
for(c = r – 1; c >= 1; c – –)

392
PROGRAM AND ALGORITHMS

{
System.out.print(“ ” + c);
}
System.out.println();
}
//lower part
for(r = 2; r <= n; r++)
{
for(c = r; c <= n – 1; c++)
{
System.out.print(“ ”);
// to print leading spaces in each row
}
for(c = 1; c <= r; c++)
{
System.out.print(“ ” + c);
}
for(c = r–1; c >= 1; c– –)
{
System.out.print(“ ” + c);
}
}
}
Topic 4 Methods or Functions
1. Input a year and verify if it is Leap or not. A year is Leap if it is —
(i) Divisible by 4 and not by 100.
OR
(ii) Divisible by 400.
• An year will be Leap on the two conditions given.
• The 1st condition has two sub conditions, both of which will have to be true.
• The 2nd condition is single.
• If none are true then the year is a non-Leap year.
boolean fnIsLeap(int y)
2. Input a number and verify if it is Prime or not.

393
ISC COMPUTER SCIENCE – XI

A prime number has a total of only 2 factors i.e., 1 and the number itself.
• A number will be prime if its total number of factors = 2.
• Use a function fnTotalFactors() that will count and return the total number of
factors a number has. i nt fnTotalFactors(int n)
• Use a function fnIsPrime() that uses the return of fnTotalFactors() to verify if a
number is prime or not. b oolean fnIsPrime(int v)
3. Input a number N and input two limits (L1, L2). Print the Multiplication Table
of N from Limit L1 to Limit L2.
• Multiplication table of a number N gives many outputs.
• Input the limits (L1, L2).
• Run a loop of j from L1 to L2. For each j, P = N × j and print P.
• Extension – If L1 < L2, the loop is ascending ; If L1 > L2, the loop is descending.
void fnMulTab(int N, int L1, int L2)
4. Input a number N. Print its Prime Factors.
• Find the factors and for each factor verify whether it is prime or not.
• Run a loop of j from 2 to N. (since 2 is the 1st prime number)
• For each value of j, if it is a factor, then send it for prime test to fnIsPrime().
• If a factor is Prime only then it gets printed.
5. Calculate and print S1 = 1! + 2! + 3! + 4! + 5! + …….. upto n terms, where n is
user input and K! = 1 * 2 * 3 * … * K.
• Input n, the number of terms and assume Sum = 0.
• Run a loop of j from 1 to n to generate the terms of the series.
• For each value of j, calculate its factorial using function fnFactorial() and add
the return to the sum. int fnFactorial(int k).
• Print Sum outside the loop.
• The next two series are similar(S2, S3).
6. Calculate and print S2 = 1$ + 2$ + 3$ + 4$ + ………. upto n terms , where n is
user input and K$ = 1 + 2 + 3 + … + K.
7. Calculate and print S3 = ( 1! / 1$ ) + ( 2! / 2$ ) + ( 3! / 3$ ) + ( 4! / 4$ ) + ……..
upto n terms.
8. Input a number N and verify if it is Palindrome or not. [N = its Reverse]
• A number will be Palindrome if it is same as its reverse.
• Use a function fnReverseNum() that will return the reverse of a number.
int fnReverseNum(int n)
• Use a function fnIsPalindrome() that uses the return of fnReverseNum() to
394
PROGRAM AND ALGORITHMS

verify if a number is Palindrome or not. boolean fnIsPalindrome(int v)


9. Input a number and verify if it is a Krishnamurthy number or not.
To be a Krishnamurthy number—
Sum of the factorial of the digits = the number itself
E.g., 145  1 + 4! + 5!  1 + 24 + 120  145
• Input a number N. Assume Sum = 0.
• Extract the digits of N. For each digit (d), find the factorial of d and add it to
Sum.
• Use a function fnFactorial() that will return the factorial of a number.
int fnFactorial(int n)
• Use a function fnIsKrishnamurthy() that uses the return of fnFactorial() to
verify if a number is a Krishnamurthy number or not.
boolean fnIsKrishnamurthy (int v)
10. Armstrong number — Sum of cube of digits = number itself
E.g., 153  1^3 + 5^3 + 3^3  1 + 125 + 27  153
• Similar to above. Instead of factorial, find the cube of the digits, then add
them and verify.
• Function boolean fnIsArmstrong(int n)
11. D-Factors are a pair of factors of a number where one is the double of the other.
For example N = 24 , factors — 1 2 3 4 6 8 12 24
D-Factors will be (1, 2) , (3, 6), (4, 8), (6, 12), (12, 24)
Can be done without using arrays.
12. Perfect Square – square of the square root of a number = number itself.
e.g., :
(√25)2 = (5)2 = 25… 25 is a perfect square.
(√10)2 = (3.33)2≠10 10 is not a perfect square.
Hints :
• Square Root, R, of N will be less than N/2.
• R cannot be fraction if N is an integer.
Topic 5 Arrays – One Dimensional
1. Find the sum of the prime elements of the array.
• Fill an array of size n with variables.
• Run a loop of j from 0 to (n – 1).
• For each j, verify if the array element at position j (ar[j]) is prime or not. Use
function fnIsPrime(). boolean fnIsPrime(int n)

395
ISC COMPUTER SCIENCE – XI

• Print the element if it is Prime.


2. Input a number N. Fill an array with its factors.
• The size of the array should be equal to the number of factors N has.
• Find the total factors of N and store in tf. Use function fnTotalFactors().
int fnTotalFactors(int n)
• Declare an array NFactor[ ] whose size is tf.
• Store 1 in the 1st cell and N in the last cell. NFactor[0] = 1; NFactor[tf – 1] = N
• Let c = 1, where c denotes the cell number getting filled.
• Run a loop of j from 2 to (N/2).
• For each j, if it is a factor of N, then store it in cell number c, and increase c
by 1.
• Note that c increases on condition.
3. Fill an array with variables. Verify if it is symmetric or not.
• A Symmetric array will read the same from forward and backward.
• Let the size of the array be n.
• Assume that the array is symmetric, sm = true.
• Search for one non-symmetric element and sm = false.
• Let b = (n – 1)
• Run a loop of j from 0 to n/2
• For each j, compare ar[j] with ar[b]. If they are not equal, sm = false and
return sm.
• For the array to be symmetric, the result of comparison should never be false.
• Reduce b by 1 each time.
• Finally out of the loop, sm is the result.
4. Fill an array and print its Max and Min elements along with their positions.
• Fill the array.
• To find the largest element, a variable named max is used.
• Variable max begins with the value in the first cell.
• Then one by one all the elements are compared with it. Whenever any
other element of the array becomes larger than max, the value of max is
overwritten by that.
• Thus, finally when the array traversal ends, max contains the largest element.
am[5] 10 8 1 19 7
Cell numbers 0 1 2 3 4
• Similarly find the min elements.
5. Perform left/right shift on the elements of an array.
Left Shift

396
PROGRAM AND ALGORITHMS

• Fill the array.

am[5] 10 8 1 12 7
Cell numbers 0 1 2 3 4
• After left shift

am[5] 8 1 12 7 7
Cell numbers 0 1 2 3 4
• For n (say 5) elements, left shift can take place for n – 1 (i.e., 4) elements.
• Run a loop of j from 1 to (n – 1).
• For each j, put the current element in its previous cell. ar[j – 1] = ar[j]
• In this case, the 1st element gets overwritten.
Left Circular Shift
• Modification on the above process, store the 1st element in tmp.
• Finally, put tmp in the last cell.

am[5] 8 1 12 7 10
Cell numbers 0 1 2 3 4
Right Shift
• Here the shift takes place from right to left. On the source array, right shift
will change it as follows :

am[5] 10 10 8 1 12
Cell numbers 0 1 2 3 4
Right Circular Shift
• Modification on the above process, store the last element in tmp.
• Finally, put tmp in the 1st cell.

am[5] 7 10 8 1 12
Cell numbers 0 1 2 3 4
6. Calculate Mean, Median, Mode for a given set of data.
Example data [12] = [25, 32, 35, 42, 25, 35, 45, 52, 45, 32, 46, 34]
Mean = sum of all elements / total number of elements.
Median = (n + 1)/2 th element if n is odd.
Avg of n/2 th and (n/2 + 1)th element if n is even.
Mode = element with the highest frequency.
[To find Median, the array should be in ascending order]
• For Mean and Mode, apply the known tools.

397
ISC COMPUTER SCIENCE – XI

• Median calculation includes sorting of the array in ascending order.


Topic 6 Arrays : Two Dimensional
1. Fill a 2D array with variables. Print the left diagonal and its sum.
Also print the right diagonal and its sum.
• For a 2D array of order 5 × 5.
u The left diagonal is made of the elements at cell (0, 0), (1, 1), (2, 2), (3, 3), (4, 4).
u The right diagonal elements are at (0, 4), (1, 3), (2, 2), (3, 1), (4, 0).
• The 2D array should have same number of rows and columns, to have diagonals.
For example :
44 66 88 22 33
21 43 65 87 98
45 56 78 89 34
30 50 90 40 70
83 74 51 95 62
For left diagonal, row number coincides with the column number.
From the given example : 44 43 78 40 62
• For right diagonal, row number increases and the column number decreases.
From the given example : 33 87 78 50 83
• The diagonal elements can be printed with a single loop for each.
2. 
Compare two 2-D arrays and verify whether all the elements are same cell to
cell
• For two 2D arrays to be same cell to cell, assume the status to be true.
• For each row and each column, compare one element from both the arrays at
a time. If any mismatch is found, set status to be false and terminate the loop.
• If no mismatch occurs, status remains true.
• Print the status.
For Array A and Array B, status is false.
For Array A and Array C, status is true.
Array A Array B Array C
44 66 88 22 33 43 65 87 21 32 44 66 88 22 33
21 43 65 87 98 20 42 64 86 97 21 43 65 87 98
45 56 78 89 34 44 55 78 88 33 45 56 78 89 34
30 50 90 40 70 29 49 89 39 69 30 50 90 40 70
83 74 51 95 62 82 73 50 94 61 83 74 51 95 62

398
PROGRAM AND ALGORITHMS

3. 
Compare two 2-D arrays and verify whether they have any common elements
or not.
• For two 2D arrays to be same cell to cell, assume the status to be false.
• For each element of the 1st array, compare all the elements of the 2nd array.
If any match is found, set status to be true and terminate the loop.
• If no match occurs, status remains false.
• Print the status.
In the above array examples, Array A and Array B have one common element.
4. Print Row-wise and Column-wise Sum and Maximum and Minimum elements.
Row-wise Sum in a 2D array of order m × n.
• For each row, add all the column elements and print the sum each time.
Row-wise Maximum in a 2D array of order m × n
• For each row, find the maximum of column elements, and print each time.
Row-wise Minimum in a 2D array of order m × n
• For each row, find the minimum of column elements, and print each time.
Column-wise Sum in a 2D array of order m × n
• For each Column, add all the row elements and print the sum each time.
Column-wise Maximum in a 2D array of order m × n
• For each column, find the maximum of row elements, and print each time.
Column-wise Minimum in a 2D array of order m × n
• For each column, find the minimum of row elements, and print each time.
[A nested loop is required to traverse a 2D array.]
Example :
11 20 10 49
22 11 33 19
66 33 20 30
88 15 25 22
st st
Sum 1 Row : 90 1 Column : 187
nd nd
2 Row : 85 2 Column : 79
rd rd
3 Row : 149 3 Column : 88
th th
4 Row : 150 4 Column : 120
st st
Maximum 1 Row : 49 1 Column : 88
nd nd
2 Row : 33 2 Column : 33
rd rd
3 Row : 66 3 Column : 33
4th Row : 88 4th Column : 49

399
ISC COMPUTER SCIENCE – XI

Minimum 1st Row : 10 1st Column : 11


nd nd
2 Row : 11 2 Column : 11
rd rd
3 Row : 20 3 Column : 10
4th Row : 15 4th Column : 19
5. Create a vertical and horizontal Mirror Matrix.
Horizontal Mirror Matrix of A[ ][ ]
• The last column of A[ ][ ] becomes the first column of its mirror, 2nd last
column becomes 2nd column and so on.
• For each row, the mirror matrix contains the column elements in reverse
order.
• The matrix need not be a square matrix.
Matrix A[ ][ ] Horizontal Mirror Matrix of A[ ][ ]
11 20 10 49 69 69 49 10 20 11
22 11 33 19 18 18 19 33 11 22
66 33 20 30 27 27 30 20 33 66
88 15 25 22 32 32 22 25 15 88

Vertical Mirror Matrix of A[ ][ ]


• The last row of A[ ][ ] becomes the first row of its mirror, 2nd last row becomes
2nd row and so on.
• For each column, the mirror matrix contains the row elements in reverse
order.
• The matrix need not be a square matrix.
Matrix A[ ][ ] Vertical Mirror Matrix of A[ ][ ]

11 20 10 49 69 18 27 32

22 11 33 19 88 15 25 22
66 33 20 30 66 33 20 30

88 15 25 22 22 11 33 19
69 18 27 32 11 20 10 49

6. Print the Upper and Lower matrix of a square matrix.


Upper Matrix of A[ ][ ]
• The elements that appear on and above the left diagonal form the Upper
Matrix.

400
PROGRAM AND ALGORITHMS

• The matrix has to be a square matrix.


Array A[ ][ ] Upper Matrix of A[ ][ ]
44 66 88 22 33 44 66 88 22 33
21 43 65 87 98 43 65 87 98
45 56 78 89 34 78 89 34
30 50 90 40 70 40 70
83 74 51 95 62 62
Lower Matrix of A[ ][ ]
• The elements that appear on and below the left diagonal form the Lower
Matrix.
• The matrix has to be a square matrix.
Array A[ ][ ] Lower Matrix of A[ ][ ]
44 66 88 22 33 44
21 43 65 87 98 21 43
45 56 78 89 34 45 56 78
30 50 90 40 70 30 50 90 40
83 74 51 95 62 83 74 51 95 62

PROGRAMS SOLUTIONS
In this section, some of the programs are done.
Topic 1 Loops and Conditions
1. Print and count the Factors of a number (n).
import java.util.*;
public class clWork
{
int fnFactors(int n)
{
if(n <= 0)
{
System.out.print(“Invalid number”);
return 0;
}
if(n == 1)
{
System.out.print(“ 1 has only 1 factor, i.e itself “);
return 1;

401
ISC COMPUTER SCIENCE – XI

}
int c = 2;
System.out.print(“Factors of” + n + “are : 1”);
for(int j = 2; j <= n/2; j++)
{
if(n % j == 0)
{
System.out.print(“ ” + j);
c++;
}
}
System.out.print(“ ” + n );
return c;
}

public void main()


{
Scanner sc = new Scanner(System.in);
int k = 0, ck = 0;
System.out.print(“Enter the number :”);
k = sc.nextInt();

ck = fnFactors(k);
System.out.print(“ \n Number of factors” + k + “has =” + ck);
}
}
OUTPUT :
Enter the number : 45
Factors of 45 are : 1 3 5 9 15 45
Number of factors 45 has = 6
2. Summation of a number n = 1 + 2 + 3 + … + n; For e.g., n = 5, summation
n = 15
import java.util.*;
public class clWork
{
int fnSummation(int n)

402
PROGRAM AND ALGORITHMS

{
if(n <= 0)
{
System.out.print(“Invalid number”);
return 0;
}
int sum = 0;
for(int j = 1; j <= n; j++)
sum += j;
return sum;
}
public void main()
{
Scanner sc = new Scanner(System.in);
int k = 0, sum = 0;
System.out.print(“Enter the number :”);
k = sc.nextInt();
sum = fnSummation(k);
System.out.print(“ \n Summation of ” + k +“ = ” + sum);
}
}
OUTPUT :
Enter the number : 6
Summation of 6 = 21
3. Factorial of a number n = 1 * 2 * 3 * …. * n; For e.g., n = 5, factorial n = 120
• Similar to the above, except that, the numbers are multiplied, and the result
begins with 1.
4. Digits of a number (Print, Count, Add, Multiply, Reverse, Largest Digit).
import java.util.*;
public class clWork
{
void fnPrintDigits(int n)
{
int d = 0;
System.out.print(“The digits of ” + n +“ are :”);
while(n > 0)

403
ISC COMPUTER SCIENCE – XI

{
d = n % 10;
System.out.print(“ ” + d);
n = n/10;
}
}
int fnDigitSum(int n)
{
int d = 0, sum = 0;
while(n > 0)
{
d = n % 10;
sum = sum + d;
n = n/10;
}
return sum;
}
int fnMaxDigit(int n)
{
int d = 0, mxd = 0;
while(n > 0)
{
d = n % 10;
if(d > mxd)
{
mxd = d;
}
n = n/10;
}
return mxd;
}
int fnReverseNum(int n)
{
int d = 0, rev = 0;
while(n > 0)

404
PROGRAM AND ALGORITHMS

{
d = n % 10;
rev = rev * 10 + d;
n = n/10;
}
return rev;
}
boolean fnIsPalindrome(int n)
{
int revnum = fnReverseNum(n);
if(n == revnum)
{
return true;
}
return false;
}
int fnTotalDigits(int n)
{
int td = 0;
while(n > 0)
{
td++;
n = n/10;
}
return td;
}
}
5. All Common Factors of two numbers.
import java.util.*;
public class clWork
{
void fnCommonFactors(int p, int q)
{
System.out.println(“Common Factors of ” + p + “ and ” + q + “ are : ”);
for(int c = 1; c <= Math.min(p, q); c++)

405
ISC COMPUTER SCIENCE – XI

{
if(p % c == 0 && q % c == 0)
{
System.out.print(“ ” + c);
}
}
}
}
OUTPUT :
Common Factors of 24 and 18 are :
1 2 3 6
6. All Common Multiples of two numbers.
import java.util.*;
public class clWork
{
void fnCommonFactors(int p, int q)
{
System.out.println(“Common Multiples of ” + p + “ and ” + q + “ are : ”);
for(int m = Math.max(p, q); m <= p * q; m++)
{
if(m % p == 0 && m % q == 0)
{
System.out.print(“ ” + m);
}
}
}
}
OUTPUT :
Common Multiples of 20 and 12 are :
60 120 180 240
7. Print n (int) numbers lying between two variables w and z.
• Run a loop from w to z with a limit of less than or equal to n, rest same as abore.
8. S7 = 1 + 2 + 4 + 8 + 16 + 32 + ………. upto n terms.
import java.util.*;
public class clWork

406
PROGRAM AND ALGORITHMS

{
void fnSeries7(int n)
{
System.out.print(“ Series7 :: ”);

int sum = 0, termVal = 1;


for(int j = 1; j <= n; j++)
{
System.out.print(termVal);
if(j < n)
System.out.print(“ + ”);
else
System.out.print(“ = ”);
sum = sum + termVal;
termVal = termVal * 2;
}
System.out.print(+Sum);
}
}
OUTPUT :
n=7
Series7 :: 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127

n=5
Series7 :: 1 + 2 + 4 + 8 + 16 = 31
9. Roots of a quadratic equation using Sri Dharacharya’s formula.
For ax2 + bx + c = 0 Roots = (–b + (d)1/2) / 2.a where d = (b2 – 4.a.c)
import java.util.*;
public class clWork
{
void fnRoots(int a, int b, int c)
{
System.out.println(“ The Quadratic Equation is ...” + a + “x^2 +
(“ + b + ” )x + ” + c);

double r1 = 0, r2 = 0, d = 0;
if(a == 0)

407
ISC COMPUTER SCIENCE – XI

{
System.out.print(“Not a Quadratic Equation.”);
}
else
{
d = b * b – 4 * a * c;
if(d > 0)
{
r1 = ( –b + Math.sqrt(d) )/ (2 * a);
r2 = ( –b – Math.sqrt(d) )/ (2 * a);
System.out.print(“Roots are real and unequal, R1 = ”+ r1 + “ R2 = ” + r2);
}
else if(d == 0.0)
{
r1 = –b / (2.0 * a);
System.out.print(“ Roots are real and equal, Root = ” + r1);
}
else
{
double tmp = Math.sqrt(d * (–1));
System.out.println(“ Roots are Imaginary and unequal.”);
System.out.println(“ R1 = (“ + (– b) + “ + ” + tmp + “ i ” + ”)/ (“+ 2 * a + ”) ”);
System.out.println(“ R2 = (“ + (– b) + “ – ” + tmp + “ i ” + ”)/(“+ 2 * a + ”) ”);
}
}
}
}
OUTPUT :
a = 5, b = –25, c = 30
The Quadratic Equation is ... 5 x ^2 + (– 25) x + 30
Roots are real and unequal, R1 = 3.0, R2 = 2.0
a = 1, b = – 8, c = 16
The Quadratic Equation is ... 1 x ^2 + ( – 8 ) x + 16
Roots are real and equal, Root = 4.0
a=4,b=8,c=5

408
PROGRAM AND ALGORITHMS

The Quadratic Equation is ... 4 x ^2 + (8) x + 5


Roots are Imaginary and unequal.
R1 = (– 8 + 4.0 i) / 8
R2 = (– 8 – 4.0 i) / 8
Topic 2 Application of Flags (optimized operation)
1. Verify whether at least one of the array elements is even or not.
import java.util.*;
public class clJob
{
int ag[ ] = {25, 37, 11, 20, 69, 83}; // code to fill the array to be here
boolean fnOneEven()
{
for(int j = 0; j <= ag.length – 1; j++)
{
if(ag[j] % 2== 0)
{
return true; // one even element found
}
}
// After testing all elements, and condition never happening
return false;
}
}
2. Verify whether all the array elements are even or not.
import java.util.*;
public class clJob
{
int ag[ ] = {24, 36, 12, 20, 68, 88};
boolean fnAllEven()
{
for(int j = 0; j <= ag.length – 1; j++)
{
if(ag[j] % 2 != 0)
{
return false; // not all elements are even
}

409
ISC COMPUTER SCIENCE – XI

}
// After testing all elements, and never getting an odd
return true;
}
}
3. Verify whether all 25 students passed the subject examination or not.
Program Idea
• Assume that the result is true.
• Search for at least one occurrence of ‘failing marks’, which if found, result
becomes false.
import java.util.*;
public class clJob
{
void fnAllPassed()
{
Scanner sc = new Scanner(System.in);
int mark = 0;
int j = 0;
boolean alp = true;
for(j = 1; j <= 25; j++)
{
System.out.print(“Enter marks for Roll num” + j + “ : ”);
mark = sc.nextInt();
if(mark < 40)
{
System.out.print(“Sorry. Not all students passed.”);
break;
}
}
if(j == 26)
{
System.out.print(“Congrats. All students passed.”);
}
}
}
OUTPUT :
Enter marks for Roll num 1 : 66
Enter marks for Roll num 2 : 55
Enter marks for Roll num 3 : 22

410
PROGRAM AND ALGORITHMS

Sorry. Not all students passed.


10. Verify whether every word in a string sentence begins with ‘s’ or not.
import java.util.*;
public class clJob
{
void fnWordS( )
{
Scanner sc = new Scanner(System.in);
int j = 0;
System.out.print(“Enter the string sentence : ”);
String sa = sc.nextLine();
sa = “ ” + sa; // for all words to have a space in front

for(j = 0; j <= sa.length() – 1; j++)


{
char ch = sa.charAt(j);
if(ch == ‘ ’)
{
char ch2 = sa.charAt(j + 1);
System.out.println(“ j = ” + j + “ch2 = ” + ch2);

if(ch2 != ‘s’ && ch2 != ‘S’)


{
System.out.print(“Sorry. All words do not start with s. ”);
break;
}
}
}
if(j == sa.length())
{
System.out.print(“Yes. All words start with s.”);
}
}
}
OUTPUT :
Enter the string sentence : Sunday super song.

411
ISC COMPUTER SCIENCE – XI

Yes. All words start with s.


Enter the string sentence : Simple SUMS of Science
Sorry. All words do not start with s.
14. Verify whether 2 one-d arrays contain no common elements.
Solution A :
import java.util.*;
public class clJob
{
void fnArray()
{
Scanner sc = new Scanner(System.in);
int r1 = 0, r2 = 0;
int RA[ ] = {20, 40, 60, 80, 100};
int RB[ ] = {10, 30, 50, 70, 90, 66, 88, 62, 77};
boolean noCommon = true;

for(r1 = 0; r1 <= RA.length – 1; r1++)


{
for(r2 = 0; r2 <= RB.length – 1; r2++)
{
if(RA[r1] == RB[r2])
{
System.out.print(“Arrays HAVE Common Element.”);
noCommon = false;
break;
}
}
if(noCommon == false)
break;
}
if(noCommon == true)
{
System.out.print (“The arrays have NO Common Element.”);
}
}

412
PROGRAM AND ALGORITHMS

}
OUTPUT :
The arrays have NO Common Element.
14. Verify whether 2 one-d arrays contain no common elements.
Solution B : Application of label in a program in order to break a nested loop.
import java.util.*;
public class clJob
{
void fnArray2()
{
Scanner sc = new Scanner(System.in);
int r1 = 0, r2 = 0;
int RA[ ] = {20, 40, 60, 80, 100};
int RB[ ] = {10, 30, 20, 70, 90, 66, 88, 62, 77};
boolean noCommon = true;
abc :
for(r1 = 0; r1 <= RA.length – 1; r1++)
{
for(r2 = 0; r2 <= RB.length – 1; r2++)
{
if(RA[r1] == RB[r2])
{
System.out.print(“Arrays HAVE Common Element.”);
noCommon = false;
break abc;
}
}
System.out.println(“Testing 1”);
}
System.out.println(“Testing 2”);
if(noCommon == true)
{
System.out.print(“The arrays have NO Common Element.”);
}
}

413
ISC COMPUTER SCIENCE – XI

}
OUTPUT :
/* Execute the program to verify the output and test with other set of values in RA[ ]
& RB[ ] */
15. Verify whether an array is pre-sorted in ascending order or not [do not sort the
array].
import java.util.*;
public class clJob
{
int RA[ ] = {20, 35, 40, 45, 50, 80, 85, 90};
int RB[ ] = {99, 88, 66, 44, 33, 40, 22};
void fnPreSortedAsc() // Verifying RA[ ] is in ascending order or not
{
Scanner sc = new Scanner(System.in);
int r1 = 0;
boolean inOrderA = true;
for(r1 = 0; r1 <= RA.length – 2; r1++)
{
if(RA[r1] > RA[r1 + 1]) // each next should be smaller
{
System.out.println(“Sorry. Array RA[ ] NOT IN Ascending Order.”);
inOrderA = false;
break;
}
}
if(inOrderA == true)
{
System.out.println(“ Yes. Array RA[ ] IS IN Ascending Order. ”);
}
}
void fnPreSortedDesc() // Verifying RB[ ] is in descending order or not
{
Scanner sc = new Scanner(System.in);
int r1 = 0;
boolean inOrderB = true;
for(r1 = 0; r1 <= RB.length – 2; r1++)

414
PROGRAM AND ALGORITHMS

{
if(RB[r1] < RB[r1 + 1]) //each next should be bigger
{
System.out.println(“Sorry. Array RB[ ] NOT IN Descending Order.”);
inOrderB = false;
break;
}
}
if(inOrderB == true)
{
System.out.println(“Yes. Array RB[ ] IS IN Descending Order. ”);
}
}
void main()
{
fnPreSortedAsc();
fnPreSortedDesc();
}
}
OUTPUT :
Yes. Array RA[ ] IS IN Ascending Order.
Sorry. Array RB[ ] NOT IN Descending Order.
 ethod to Verify whether the array is pre-sorted or not (either ascending or
M
descending).
void fnPreSorted()
{
int st = 0;
if(RA[0] < RA[1])
{
st = 1;
}
else if(RA[0] > RA[1])
{
st = 2;
}

415
ISC COMPUTER SCIENCE – XI

int j = 2, order = 1;
while(j <= RA.length – 1 && order == 1)
{
if(st == 1 && RA[j] > RA[j – 1])
{
j++;
}
else if(st == 2 && RA[j] < RA[j–1])
{
j++;
}
else
{
System.out.print(“NOT IN ORDER”);
order = 0;
break;
}
}
if(order == 1)
{
System.out.print(“IN ORDER”);
}
}
OUTPUT :
/* test run the method with different values in RA[ ] */
Topic 4 Methods or Functions
1. Input a year and verify if it is Leap or not.
A year is Leap if it is — (i) Divisible by 4 and not by 100
OR
(ii) Divisible by 400
class clCheckLeap
{
boolean fnIsLeap(int y)
{
if((y % 400 == 0) | | ((y % 100 != 0) && (y % 4 == 0)))
return true;
else

416
PROGRAM AND ALGORITHMS

return false;
} //function to check for leap year
}

2. Input a number and verify if it is Prime or not.


Hint : A prime number has a total of only 2 factors.
class clPrime
{
int fnTotalFactors(int n)
{
int cnt = 0;
for(int i = 1; i <= n; i++)
{
if(n % i == 0)
{
cnt++;
}
}
return cnt;
}
boolean fnIsPrime(int v)
{
int c = fnTotalFactors(v); //applying nesting of methods
if(c == 2)
{
return true;
}
return false;
}
}
3. 
Input a number N and input two limits (L1, L2). Print the Multiplication Table
of N from Limit L1 to Limit L2.
class clTables
{
public void fnMulTab(int N, int L1, int L2)
{
417
ISC COMPUTER SCIENCE – XI

int j = 0, P = 0;
System.out.println(“The table of ” + N + “from” + L1 + “to” + L2 + “is –”);
if(L1 < L2)
{
for(j = L1; j <= L2; j++)
{
P = N * j;
System.out.println(N + “ * ” + j + “ = ” + P + “ . ”);
}
}
else
{
for(j = L1; j >= L2; j – –)
{
P = N * j;
System.out. println(N + “ * ” + j + “ = ” + P + “ . ”);
}
}
}
}
4. Input a number N. Print its Prime Factors.
import java.io.*;
import java.util.*;
class clPrimeFactor
{
int fnTotalFactors(int n)
{
int cnt = 0;
for(int i = 1; i <= n; i++)
{
if(n % i == 0)
{
cnt++;
}
}
418
PROGRAM AND ALGORITHMS

return cnt;
}
boolean fnIsPrime(int v)
{
int c = fnTotalFactors(v);
if(c == 2)
{
return true;
}
return false;
}
public void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number whose prime factors are to be found : ”);
int N = sc.nextInt();
System.out.println(“The prime factors are : ”);
for(int j = 2; j <= N; j++)
{
if(N % j == 0)
{
if(fnIsPrime(j) == true)
{
System.out.print(j + “ \t ”);
}
}
}
}
}
OUTPUT :
Enter the number whose prime factors are to be found : 60
The prime factors are :
2 3 5
5. Calculate and print S1 = 1!+ 2! + 3! + 4! + 5! + …….. upto n terms, where n is
user input and K! = 1 * 2 * 3 * … * K.
419
ISC COMPUTER SCIENCE – XI

import java.io.*;
import java.util.*;
class clS1
{
int fnFactorial(int k)
{
int i, term = 1;
for(i = 1; i <= k; i++)
{
term *= i;
}
return term;
}
public void main()
{
Scanner sc = new Scanner(System.in);
int j, n = 0;
double sum = 0.0, term = 0.0;
System.out.print(“ Enter the number of terms : ”);
n = sc.nextInt();

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


{
term = fnFactorial(j);
sum += term;
}
System.out.print(“The sum is ” + sum);
}
}
6. Calculate and print S2 = 1$ + 2$ + 3$ + 4$ + ………. upto n terms , where n is
user input and K$ = 1 + 2 + 3 + … + K
import java.util.*;
class clS2
{
public void main()
{

420
PROGRAM AND ALGORITHMS

Scanner sc = new Scanner(System.in);


int i, n = 0;
double sum = 0, term = 0;
System.out.print(“Enter the number of terms : ”);
n = sc.nextInt();
for(i = 1; i <= n; i++)
{
term = fnSum(i);
sum += term;
}
System.out.print(“The sum is : ” + sum);
}
int fnSum(int n)
{
int i, sum = 0;
for(i = 1; i <= n; i++)
{
sum += i;
}
return sum;
}
}
7. Calculate and print S3 = ( 1! / 1$ ) + ( 2! / 2$ ) + ( 3! / 3$ ) + ( 4! / 4$ ) + ……..
upto n terms.
class clS3
{
void fnS3(int n)
{
int i;
double sum = 0.0, t1 = 0.0, t2 = 0.0;
for(i = 1; i <= n; i++)
{
t1 = fnFactorial(i);
t2 = fnSum(i);
sum += t1/t2;
}

421
ISC COMPUTER SCIENCE – XI

System.out.print(“The sum is : ” + sum);


}
double fnFactorial(int k)
{
int i;
double term1 = 1.0;
for(i = 1; i <= k; i++)
{
term1 *= i;
}
return term1;
}
int fnSum(int n)
{
int i, term2 = 0;
for(i = 1; i <= n; i++)
{
term2 += i;
}
return term2;
}
}
8. Input a number N and verify if it is Palindrome or not. [N = its Reverse]
import java.util.*;
class clPalindrome
{
int fnReverseNum(int n)
{
int revNum = 0;
while(n > 0)
{
revNum = revNum * 10 + (n % 10);
n /= 10;
}
return revNum;
}

422
PROGRAM AND ALGORITHMS

void fnIsPalindrome(int N)
{
if(N == fnReverseNum(N))
{
System.out.print(“The number ” + N + “ IS palindrome number. ”);
}
else
{
System.out.print(“The number ” + N + “ IS NOT a palindrome number. ”);
}
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a number : ”);
int num = sc.nextInt();
fnIsPalindrome(num);
}
}
OUTPUT :
Enter a number : 565
The number 565 IS palindrome number.
Enter a number : 223
The number 223 IS NOT a palindrome number.
9. Input a number and verify if it is a Krishnamurthy number or not. To be a
Krishnamurthy number – Sum of the factorial of the digits = number itself.
E.g., 145  1 + 4! + 5!  1 + 24 + 120  145
(i)
import java.util.*;
class clKrishnamurthy
{
int fnFactorial(int n)
{ // Function to calculate the factorial of a number.
int i, factn = 1;
for(i = 1; i <= n; i++)
{

423
ISC COMPUTER SCIENCE – XI

factn = factn * i;
}
return factn;
}
boolean fnIsKrishnamurthy(int v)
{
int n = v, sum = 0;
while(n > 0)
{
sum += fnFactorial(n % 10);
//Calculating the sum of factorial of digits of the number.
n /= 10;
}
if(sum == v)
return true;
else
return false;
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a number : ”);
int num = sc.nextInt();
boolean status = fnIsKrishnamurthy(num);
if(status == true)
{
System.out.print(num + “ IS a Krishnamurti Number.”);
}
else
{
System.out.print(num + “ is NOT a Krishnamurti Number.”);
}
}
}

424
PROGRAM AND ALGORITHMS

OUTPUT :
Enter a number : 123
123 is NOT a Krishnamurti Number.

Enter a number : 145


145 IS a Krishnamurti Number.
10. Armstrong number — Sum of cube of digits = number itself
E.g., 153 → 1^3 + 5^3 + 3^3 → 1 + 125 + 27 → 153
class clArmstrong
{
double fnPow(int a)
{
int s = 1;
for(int i = 1; i <= 3; i++) // calculating a^3
s = s * a;
return s;
}
boolean fnIsArmstrong(int v)
{
int n = v, sum = 0;
while(n > 0)
{
sum += fnPow(n % 10);
//Calculating the sum of cube of digits of the number.
n /= 10;
}
if(sum == v)
return true;
else
return false;
}
}
11. D-Factors are a pair of factors of a number where one is the double of the
other.
For example N = 24 , factors - 1 2 3 4 6 8 12 24
D-Factors will be (1, 2), (3, 6), (4, 8), (6, 12), (12, 24)
425
ISC COMPUTER SCIENCE – XI

import java.util.*;
public class clDFactors
{
void fnDFactors(int n)
{
for(int f = 1; f <= n/2; f++)
{
if(n % f == 0 && n % (f * 2) == 0)
System.out.print(“(” + f + “,” + (f * 2) + “) ” + “ ; ”);
}
}

public void main()


{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number : ”);
int n = sc.nextInt();

System.out.println(“The D-Factors of the number are : ”);


fnDFactors(n);
}
}
OUTPUT :
Enter the number : 70
The D-Factors of the number are :
(1,2); (5,10); (7,14); (35,70);
12. Perfect Square – Square of the square root of a number = number itself.
e.g., :
(√25)2 = (5)2 = 25… 25 is a perfect square
2 2
(√10) = (3.33) ≠10  10 is not a perfect square
import java.util.Scanner;
class clPerfectSquare
{
public void main()
{
Scanner sc = new Scanner(System.in);

426
PROGRAM AND ALGORITHMS

int n;
double sqrt, sq;
System.out.print(“Enter the number to be checked :”);
n = sc.nextInt();

sqrt = Math.sqrt(n);
sq = sqrt * sqrt;
if(sq == n)
{
System.out.print(n + “IS a Perfect Square. ”);
}
else
{
System.out.print(n + “is NOT a Perfect Square. ”);
}
}
}
OUTPUT :
Enter the number to be checked : 65
65 is NOT a Perfect Square.
Enter the number to be checked : 225
225 IS a Perfect Square.
13. Perfect Number – Sum of the factors excluding itself is equal to the number.
e.g., : 28
Sum of Factors of 28 except itself : (1 + 2 + 4 + 7 + 14) = 28
Hence, 28 is a Perfect Number.
//Perfect Number
import java.util.*;
class NumberPerfect
{
boolean fnIsPerfectNumber(int N)
{
int s = 0;
for(int f = 1; f <= N/2; f++)
{

427
ISC COMPUTER SCIENCE – XI

if(N % f == 0)
{
s = s + f; // s is strong sum of factors
}
}
if(N == s)
{
return true;
}
return false;
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a number : ”);
int Num = sc.nextInt();

boolean isPerfect = fnIs Perfect Number(Num);


if(isPerfect == true)
{
System.out.print(Num + “is a Perfect Number”);
}
else
{
System.out.print(Num + “is NOT a Perfect Number.”);
}
}
}
14. Magic Number – Subsequent sum of digits is 1.
e.g., : 991, sum of digits (9 + 9 = 1) = 19 → sum of digits (9 + 1) = 10 → sum of digits
(1 + 0) = 1.
Hence, 991 is a Magic Number.
e.g., : 764, sum of digits (7 + 6 + 4) = 17 → sum of digits(1 + 7) = 8.
Hence, 764 is NOT a Magic Number.

428
PROGRAM AND ALGORITHMS

import java.util.*;
class NumberMagic
{
boolean fnIsMagicNumber(int N)
{
int cn = N, s = 0;
while(cn > 9)
{
s = 0;
while (cn > 0)
{
s = s + (cn % 10);
cn = cn / 10;
}
cn = s;
}
if(cn == 1)
{
return true;
}
return false;
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a number : ”);
int Num = sc.nextInt();
boolean isMagic = fnIsMagicNumber(Num);
if(isMagic == true)
{
System.out.print(Num + “is a Magic Number.”);
}
else
{
System.out.print(Num + “is NOT a Magic Number.”);
}
}
}

429
ISC COMPUTER SCIENCE – XI

15. Smith Number


A number is called a Smith Number if the sum of the digits of the number is
equal to the sum of the digits of the prime factors of the number.
e.g., : 666
Prime factors are 2, 3, 3, and 37
Sum of the digits are (6 + 6 + 6) = 18
Sum of the digits of the prime factors (2 + 3 + 3 + (3 + 7) ) = 18

import java.util.*;
class clSmithNumber
{
int fnSumofDigits(int n)
{
int s = 0, cn = n;
while(cn > 0)
{
s = s + cn % 10; // s is storing the sum of digits
cn = cn/10;
}
return s;
}
int fnAddPrimeFactors(int n)
{
int f = 2, s = 0, cn = n;
while(cn > 1)
{
if(cn % f == 0)
{
s = s + fnSumOfDigits(f); //f is storing the prime factor
cn = cn/f;
}
else
f++;
}

430
PROGRAM AND ALGORITHMS

return s;
}
void main()
{
Scanner sc = new Scanner(System.in);
int N = 0, sumDigits = 0, sum PFDigits = 0;
System.out.print(“Enter a number :”);
N = sc.nextInt();
sumDigits = fnSumOfDigits(N);
System.out.println(“Sum of Digits of” + N+ “ = ” + sumDigits);
sumPFDigits = fnAddPrimeFactors(N);
System.out.println(“Sum of PF Digits of” + N + “=” + sum PFDigits);
if(sumDigits == sumPFDigits)
System.out.print(N + “is a Smith Number”);
else
System.out.print(N + “is a NOT a Smitch Number”);
}
}

Topic 5 Arrays – One Dimensional


1. Find the sum of the prime elements of the array.
import java.util.*;
class Q1_Sum_of_Prime
{
boolean fnIsPrime(int n)
{
for(int i = 2; i < n/2; i++)
{
if(n % i == 0) //checking the condition for prime
return false;
else
return true;
}
}

431
ISC COMPUTER SCIENCE – XI

void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“enter the number of elements”);
int n = sc.nextInt();
int sum = 0;
int A[ ] = new int [n]; //initiating the array
System.out.println(“enter the numbers”);
for(int i = 0; i < n; i++)
{
A[i] = sc.nextInt(); //accepting the array
}
for(int i = 0; i < n; i++)
{
if(fnIsPrime(A[i]) == true) //challenging the condition
{
sum = sum + A[i]; //adding up the satisfied values
}
}
System.out.println(“The sum of Prime numbers” + sum); //printing the result
}
}
2. Input a number N. Fill an array with its factors.
import java.util.*;
class Q2_Array_Factor
{
int fnTotalFactors(int n)
{
int tf = 0;
for(int i = 2; i <= n/2; i++)
{
if(n % i== 0)
{
tf++; //calculating the factors
}

432
PROGRAM AND ALGORITHMS

}
tf = tf + 2; //adding 2 due to 1 and itself
return tf;
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number”);
int n = sc.nextInt(); //assigning digit
int NFactor[ ] = new int[fnTotalFactors(n)];
NFactor[0] = 1; //assigning 1
NFactor[fnTotalFactors(n) – 1] = n;//assigning itself
for(int i = 2, c = 1; i <= n/2; i++)
{
if(n % i == 0)
{
NFactor[c] = i; //keeping the factors
c++; //changing the cell number
}
}
for(int i = 0; i < fnTotalFactors(n); i++)
System.out.print(“ ” + NFactor[i]); //printing
}
}
3. Fill an array with variables. Verify if it is symmetric or not.
import java.util.*;
class Q3_Symmetric_Array
{
void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of elements”);
int n = sc.nextInt();

433
ISC COMPUTER SCIENCE – XI

int ar[ ] = new int[n];


boolean sm = true; //assigning
System.out.println(“Enter the elements : ”);
for(int i = 0; i < n; i++)
{
ar[i] = sc.nextInt(); //accepting the elements
}
for(int i = 0; i < n; i++)
{
System.out.print(ar[i] + “ ”); //printing the array
}
for(int j = 0, b = n – 1; j < n/2; j++, b – –) // j increases, b decreases
{
if(ar[j] != ar[b]) //comparing elements at front and back
{
sm = false;
break; //breaking if condition satisfies
}
}
if(sm == true)
System.out.println(“The array IS Symmetric”);
else
System.out.println(“The array is NOT Symmetric ”);
}
}
4. Fill an array and print its Max and Min elements along with their positions.
import java.util.*;
class Q4_Max_Min
{
void main()
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of elements : ”);
int n = sc.nextInt();
int a[ ] = new int[n]; //declaring the array

434
PROGRAM AND ALGORITHMS

int pos = 0, min = 1000, max = 0, pos1 = 0;


System.out.println(“Enter the numbers : ”);
for(int i = 0; i < n; i++) //storing the numbers
{
a[i] = sc.nextInt();
}
for(int i = 0; i < n; i++) //loop for the check
{
if(max < a[i]) //checking the maximum number
{
max = a[i]; //storing changed number
pos1 = i; //storing position
}
if(min > a[i])
{
min = a[i]; //storing changed number
pos = i; //storing position
}
}
System.out.println(“The highest number is ” + max + “at position” +(pos1 + 1));
System.out.println(“The lowest number is ” + min + “at position ” + (pos + 1));
}
}
5. Perform left/right shift on the elements of an array. [Circular Shift]
import java.util.Scanner;
public class Array_Shifts
{
int arr[ ], n;
Scanner ob = new Scanner(System.in);
public void Input()
{
System.out.print(“Enter the Size of the Array : ”);
n = ob.nextInt();
System.out.println(“Enter the Array Elements : ”);
arr = new int[n];

435
ISC COMPUTER SCIENCE – XI

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


{
System.out.println(“Enter the Element number” + (i + 1) + “ : ”);
arr[i] = ob.nextInt();
}
}
public void Display()
{
System.out.println(“\f\n The Array Elements are : ”);
int i;
for(i = 0; i < n; i++)
{
System.out.print(arr[i] + “ ”);
}
}
public void RightShiftCircular(int AS[ ])
{
int j, n = AS.length, tmp = AS[n – 1];
for(j = n – 1; j >= 1; j– –)
{
AS[j] = AS[j – 1]; //Right Shift of Elements
}
AS[0] = tmp;
}
public void LeftShiftCircular(int AR[ ])
{
int j, n = AR.length, tmp = AR[0];
for (j = 0; j <= n – 2; j++)
{
AR[j] = AR[j + 1]; //Right Shift of Elements
}
AR[n – 1] = tmp;
}
public void main()
{

436
PROGRAM AND ALGORITHMS

int i, ch;
do
{
ch = Menu();
switch(ch)
{
case 0 : System.out.print(“Thank you!”);

break;
case 1 : Input();

break;
case 2 : Display();

break;
case 3 : RightShiftCircular(arr);

break;
case 4 : LeftShiftCircular(arr);
break;
default : System.out.println(“Please enter a Valid Choice.\n”);
}
} while(ch != 0);
}
int Menu()
{
System.out.println(“\n\nPress the Corr Number for the required Operation :”);
System.out.println(“1. Fill the Array Elements.”);
System.out.println(“2. Display the current Array.”);
System.out.println(“3. Right Circular Shift.”);
System.out.println(“4. Left Circular Shift.”);
System.out.println(“0. Exit. ”);
System.out.print(“Enter a Choice: ”);
int ch = ob.nextInt();
return ch;
}
}
OUTPUT :
Press the Corresponding Number for the required Operation :
1. Fill the Array Elements.

437
ISC COMPUTER SCIENCE – XI

2. Display the current Array.


3. Right Circular Shift.
4. Left Circular Shift.
0. Exit.
Enter a Choice : 2
The Array Elements are :
11 22 33 44 55

Press the Corresponding Number for the required Operation :


1. Fill the Array Elements.
2. Display the current Array.
3. Right Circular Shift.
4. Left Circular Shift.
0. Exit.
Enter a Choice : 3
The Array Elements are:
55 11 22 33 44

6. Calculate mean, median, mode for a given set of data.

import java.util.Scanner;
public class MeanMedianMode
{
int arr[ ], arr1[ ], n;
Scanner ob = new Scanner(System.in);
public void Input()
{
System.out.println(“Enter the Size of the Array”);
n = ob.nextInt();
System.out.println(“Enter the Array Elements : ”);
int i;
arr = new int[n];
arr1 = new int[n];
for(i = 0; i < n; i++)
{
System.out.println(“Enter the Element number ” + (i + 1) + “ : ” );

438
PROGRAM AND ALGORITHMS

arr[i] = ob.nextInt();
}
}
public void Display()
{
System.out.println(“\f The Array Elements are : ”);
int i;
for(i = 0; i < n; i++)
{
if(arr[i] != –1)
{
System.out.print(arr[i] + “ ”);
}
}
System.out.println();
}
public void Mean()
{
int i, s = 0, m;
for(i = 0; i < n; i++)
{
s += arr[i];
}
m = s / n;
System.out.println(“The Mean is : ” + m);
}
public void Sort()
{
int i, j, t;
for(i = 0; i < n – 1; i++)
{
for(j = 0; j < n – i – 1; j++)
{
if(arr[j] > arr[j + 1])
{

439
ISC COMPUTER SCIENCE – XI

t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
}
private void Check_Sort()
{
int i;
if(arr[0] < arr[1])
{
boolean isSorted = CheckAsc();
if(! isSorted)
{
Sort();
}
}
else
Sort();
}
private boolean CheckAsc()
{
int i;
boolean sorted = true;
for(i = 0; i < n – 1; i++)
{
if(arr[i] > arr[i + 1])
{
sorted = false;
break;
}
}

440
PROGRAM AND ALGORITHMS

if(sorted)
{
return true;
}
return false;
}
public void Median()
{
int i, median;
Check_Sort();
if(n % 2 == 0)
{
median = arr[(n/2 – 1)];
System.out.print(“The medians are :” + median);
median = arr[(n/2)];
System.out.println(“ and ” + median);
}
else
{
median = arr[(n – 1)/2];
System.out.println(“The Median is :” + median);
}
}
public boolean isPresent(int n1)
{
int i;
for(i = 0; i < n; i++)
{
if(arr1[i] == n1)
{
return true;
}
}

441
ISC COMPUTER SCIENCE – XI

return false;
}
public void Mode()
{
int c = 0, e = 0, cm = 0, i, j, p = 0;
for(i = 0; i < n; i++)
{
c = 0;
if(! isPresent(arr[i]))
{
arr1[p++] = arr[i];
for(j = i; j < n; j++)
{
if(arr[j] == arr[i])
c++;
}
}
if(cm < c)
{
cm = c;
e = arr[i];
}
}
System.out.println(“The Mode is :” + e );
}
public void main()
{
int i;
int ch;
do
{
ch = Menu();
switch(ch)
{
case 0 : System.out.print(“Thank You”);
break;

442
PROGRAM AND ALGORITHMS

case 1
:
Input();

break;
case 2
:
Display();
break;
case 3
:
Mean();

break;
case 4
:
Median();

break;
case 5
:
Mode();

break;
default
:
System.out.println(“Please enter a Valid Choice. \n”);
}
}while(ch != 0);
}
int Menu()
{
int ch;
System.out.println(“Press the Corr Number for given Function :”);
System.out.println(“1. Input the Array Elements.”);
System.out.println(“2. Display the current Array.”);
System.out.println(“3. Mean”);
System.out.println(“4. Median”);
System.out.println(“5. Mode”);
System.out.println(“0. Exit”);
System.out.print(“Enter your Choice :”);
ch = ob.nextInt();
return ch;
}
}
OUTPUT :
The Array Elements are :
11 22 33 44 88
Press the Corr Number for given Function :
1. Input the Array Elements.

443
ISC COMPUTER SCIENCE – XI

2. Display the current Array.


3. Mean
4. Median
5. Mode
0. Exit
Enter your Choice : 3
The Mean is : 39

Press the Corr Number for given Function :


Enter your Choice : 4
The Median is : 33

Press the Corr Number for given Function :


Enter your Choice : 5
The Mode is : 11

Press the Corr Number for given Function :


Enter your Choice : 0
Thank You
Topic 6 Arrays : Two Dimensional
1. 
Fill a 2-D array with variables. Print the left diagonal and its sum. Also print
the right diagonal and its sum.
import java.util.*;
class clTwoQ1
{
void main()
{
// Random 1 digit number as order of the array
int n = (int)(Math.random() * 10);
n = (n <= 2) ? (3 + n) : n; // in case n is 0, it is modified
int AT[ ][ ] = new int[n][n]; //declaring the array
int r, c, sumLeft = 0, sumRight = 0;
for(r = 0; r < n; r++)
{
for(c = 0; c < n; c++)
{
444
PROGRAM AND ALGORITHMS

AT[r][c] = (int)(Math.random() * 100);


}
}
System.out.println(“The Matrix is :”);
for(r = 0; r < n; r++)
{
for(c = 0; c < n; c++)
{
System.out.print(“ ” + AT[r][c]);
}
System.out.println(“ ”);
}
System.out.println(“\nThe Left Diagonal is : ”);
for(r = 0; r < n; r++)
{
System.out.print(“ ” + AT[r][r]); //row & col number is same for left diag
sumLeft = sumLeft + AT[r][r];
}
System.out.println(“\nThe Sum of elements of Left Diagonal is : ” + sumLeft);

System.out.println(“\nThe Right Diagonal is : ”);


for(r = 0, c = n – 1; r < n; r++, c – –)
{
System.out.print(“ ” + AT[r][c]); // row increase & col decreases
sumRight = sumRight + AT[r][c];
}
System.out.println(“\nThe Sum of elements of Right Diagonal is : ” + sumRight);
}
}
OUTPUT :
The Matrix is :
76 15 47 42
65 18 45 44
52 48 61 17
69 80 41 94

445
ISC COMPUTER SCIENCE – XI

The Left Diagonal is :


76 18 61 94
The Sum of elements of Left Diagonal is : 249

The Right Diagonal is :


42 45 48 69
The Sum of elements of Right Diagonal is : 204
2. 
Compare two 2-D arrays and verify whether all the elements are same cell to
cell.
import java.util.*;
class clTwoQ2
{
void fnDisplay(int D[ ][ ])
{
for(int r = 0; r <= D.length – 1; r++)
{
for(int c = 0; c <= D[r].length – 1; c++)
{
if(D[r][c] <= 9)
System.out.print(“ ”);
System.out.print(“ ” + D[r][c]);
}
System.out.println();
}
}
boolean fnEqual(int DA[ ][ ], int DB[ ][ ])
{
boolean same = true; //to look for any different element
rep :
for(int r = 0; r <= DA.length – 1; r++)
{
for(int c = 0; c <= DA[r].length – 1; c++)
{
if(DA[r][c] != DB[r][c])
{
same = false;

446
PROGRAM AND ALGORITHMS

break rep;
}
}
}
return same;
}
void main()
{
// Random 1 digit number as order of the arrays
int m = (int)(Math.random() * 10);
m = (m <= 1) ? (2 + m) : m; // in case n is 0, it is modified
int n = (int)(Math.random() * 10);
n = (n <= 1) ? (2 + n) : n; // in case n is 0, it is modified
int AT[ ][ ] = new int[m][n]; //declaring the arrays
int BT[ ][ ] = new int[m][n];
int r, c;
//filling the arrays AT[ ][ ] and BT[ ][ ] with Random numbers
for(r = 0; r < m; r++)
{
for(c = 0; c < n; c++)
{
AT[r][c] = (int)(Math.random() * 100);
}
for(r = 0; r < m; r++)
{
for(c = 0; c < n; c++)
{
BT[r][c] = (int)(Math.random() * 100);
}
}
System.out.println(“Matrix AT[ ][ ] is : ”);
fnDisplay(AT);
System.out.println(“Matrix BT[ ][ ] is : ”)1;
fnDisplay(BT);

447
ISC COMPUTER SCIENCE – XI

boolean equal = fnEqual(AT, BT);


if(equal == true)
{
System.out.print(“\nBoth arrays are same”);
}
else
{
System.out.print(“\nBoth arrays are NOT same”);
}
}
}
}
OUTPUT :
Matrix AT[ ][ ] is :
80 82 84 72
11 28 5 11
Matrix BT[ ][ ] is :
29 54 28 34
73 26 60 43
Both arrays are NOT same
3. 
Compare two 2-D arrays and verify whether they have any common elements
or not.
import java.util.*;
class clTwoQ3
{
void fnFill(int A[ ][ ])
{
for(int r = 0; r < A.length; r++)
{
for(int c = 0; c < A[r].length; c++)
{
A[r][c] = (int)(Math.random() * 100);
}
}
}

448
PROGRAM AND ALGORITHMS

void fnDisplay(int D[ ][ ])
{
for(int r = 0; r <= D.length – 1; r++)
{
for(int c = 0; c <= D[r].length – 1; c++)
{
if(D[r][c] < = 9)
System.out.print(“ ”);
System.out.print(“ ” + D[r][c]);
}
System.out.println();
}
}
boolean fnAnyCommon(int DA[ ][ ], int DB[ ][ ])
{
boolean anyCommon = false; //to look for any different element
rep :
for(int r = 0; r <= DA.length – 1; r++)
{
for(int c = 0; c <= DA[r].length – 1; c++)
{
if(DA[r][c] == DB[r][c])
{
anyCommon = true;
break rep;
}
}
}
return anyCommon;
}
void main()
{
// Ranom 1 digit number as order of the arrays
int m = (int)(Math.random() * 10);
m = (m <= 1) ? (2 + m) : m; // in case n is 0, it is modified
int n = (int)(Math.random() * 10);
449
ISC COMPUTER SCIENCE – XI

n = (n <= 1) ? (2 + n) : n; // in case n is 0, it is modified

int AT[ ][ ] = new int[m][n]; //declaring the arrays


int BT[ ][ ] = new int[m][n];
int r, c;
//filling the arrays AT[ ][ ] and BT[ ][ ] with Random numbers
fnFill(AT);
fnFill(BT);
System.out.println(“Matrix AT[ ][ ] is : ”);
fnDisplay(AT);
System.out.println(“Matrix BT[ ][ ] is : ”);
fnDisplay(BT);

boolean equal = fnAnyCommon(AT, BT);


if(equal == true)
System.out.print(“\nArrays HAVE a Common element”);
else
System.out.print(“\nNO Common element”);
}
}
OUTPUT :
Matrix AT[ ][ ] is :
65 89 89 63
33 70 98 56
32 41 16 19
Matrix BT[ ][ ] is :
53 27 81 91
42 63 23 88
43 41 49 66
Arrays HAVE a Common element
4. Print Row-wise and Column-wise – Sum and, Maximum and Minimum
elements.

import java.util.*;
class clTwoQ4
{
void fnFill(int A[ ][ ])

450
PROGRAM AND ALGORITHMS

{
for(int r = 0; r < A.length; r++)
{
for(int c = 0; c < A[r].length; c++)
{
A[r][c] = (int)(Math.random() * 100);
}
}
}
void fnDisplay(int D[ ][ ])
{
for(int r = 0; r <= D.length – 1; r++)
{
for(int c = 0; c <= D[r].length – 1; c++)
{
if(D[r][c] <= 9)
System.out.print(“ ”);
System.out.print(“ ” + D[r][c]);
}
System.out.println();
}
}
void fnSumRows(int DA[ ][ ])
{
System.out.println(“\n Row-wise Sum”);
for(int r = 0; r <= DA.length – 1; r++)
{
int sum = 0;
for(int c = 0; c <= DA[r].length – 1; c++)
{
sum += DA[r][c];
}
System.out.println(“Row Number : ” + r + “, Sum = ” + sum);
}

451
ISC COMPUTER SCIENCE – XI

}
void fnMaxRows(int DA[ ][ ])
{
System.out.println(“\n Row-wise Max ”);
for(int r = 0; r <= DA.length – 1; r++)
{
int max = 0;
for(int c = 0; c <= DA[r].length – 1; c++)
{
if(max < DA[r][c])
{
max = DA[r][c];
}
}
System.out.println(“Row Number : ” + r + “ , Max = ” + max);
}
}
void main()
{
// Random 1 digit number as order of the arrays
int m = (int)(Math.random() * 10);
m = (m <= 1) ? (2 + m) : m; // in case n is 0, it is modified
int n = (int)(Math.random() * 10);
n = (n <= 1) ? (2 + n) : n; // in case n is 0, it is modified
int AT[ ][ ] = new int[m][n]; //declaring the arrays
int r, c;
//filling the array AT[ ][ ] with Random numbers
fnFill(AT);
System.out.println(“Matrix AT[ ][ ] is : ”);
fnDisplay(AT);
fnSumRows(AT);
fnMaxRows(AT);
}
452
PROGRAM AND ALGORITHMS

}
OUTPUT :
Matrix AT[ ][ ] is :
27 13 22 41 85 2
81 76 14 7 95 46
38 74 99 43 60 94
Row-wise Sum
Row Number : 0, Sum = 190
Row Number : 1, Sum = 319
Row Number : 2, Sum = 408
Row-wise Max
Row Number : 0, Max = 85
Row Number : 1, Max = 95
Row Number : 2, Max = 99

5. Create a vertical/horizontal Mirror Matrix.

import java.util.*;
class clTwoQ5
{
void fnFill(int A[ ][ ])
{
for(int r = 0; r < A.length; r++)
{
for(int c = 0; c < A[r].length; c++)
{
A[r][c] = (int)(Math.random() * 100);
}
}
}
void fnDisplay(int D[ ][ ])
{
for(int r = 0; r <= D.length – 1; r++)
{
for(int c = 0; c <= D[r].length – 1; c++)

453
ISC COMPUTER SCIENCE – XI

{
if(D[r][c] <= 9)
System.out.print(“ ”);
System.out.print(“ ” + D[r][c]);
}
System.out.println();
}
}
void fnHorizontalMirror(int DA[ ][ ])
{
for(int r = 0; r <= DA.length – 1; r++)
{
for(int c1 = 0, c2 = DA[r].length – 1; c1 <= (DA[r].length – 1)/2; c1++,
c2 – –)
{
int tmp = DA[r][c1];
DA[r][c1] = DA[r][c2];
DA[r][c2] = tmp;
}
}
}
void fnVerticalMirror(int DA[ ][ ])
{
for(int r1 = 0, r2 = DA.length – 1; r1 <= (DA.length – 1)/2; r1++, r2 – –)
{
for(int c = 0; c <= (DA[r1].length – 1); c++)
{
int tmp = DA[r1][c];
DA[r1][c] = DA[r2][c];
DA[r2][c] = tmp;
}
}
}
void main()

454
PROGRAM AND ALGORITHMS

{
// Ranom 1 digit number as order of the arrays
int m = (int)(Math.random() * 6);
m = (m <= 1) ? (2 + m) : m; // in case n is 0, it is modified
int n = (int)(Math.random() * 6);
n = (n <= 1) ? (2 + n) : n; // in case n is 0, it is modified
int AT[ ][ ] = new int[m][n]; //declaring the arrays
int r, c;
//filling the array AT[ ][ ] with Random numbers
fnFill(AT);
System.out.println(“Matrix AT[ ][ ] is : ”);
fnDisplay(AT);
System.out.println(“Horizontal Matrix of AT[ ][ ] is : ”);
fnHorizontalMirror(AT);
fnDisplay (AT);
System.out.println(“Vertical Matrix of AT[ ][ ] is : ”);
fnVerticalMirror(AT);
fnDisplay(AT);
}
}
OUTPUT :
Matrix AT[ ][ ] is :
85 65 53
87 15 32
1 82 18
Horizontal Matrix of AT[ ][ ] is :
53 65 85
32 15 87
18 82 1
Vertical Matrix of AT[ ][ ] is :
18 82 1
32 15 87
53 65 85

Note :
l Arrays apply “pass-by-reference” hence, it is getting changed with each method call].

455
ISC COMPUTER SCIENCE – XI

6. Print the Upper and Lower matrix of square matrix.


import java.util.*;
class clTwoQ6
{
void fnFill(int A[ ][ ])
{
for(int r = 0; r < A.length; r++)
{
for(int c = 0; c < A[r].length; c++ )
{
A[r][c] = (int)(Math.random() * 90 ) + 10;
}
}
}
void fnDisplay(int D[ ][ ])
{
for(int r = 0; r <= (D.length – 1); r++)
{
for(int c = 0; c <= (D[r].length – 1); c++)
{
if(D[r][c] <= 9)
System.out.print(“ ”);
System.out.print(“ ” + D[r][c]);
}
System.out.println();
}
}
void fnUpperMatrix(int DA[ ][ ])
{
for(int r = 0; r <= (DA.length – 1); r++)
{
for(int c = 0; c <= r – 1; c++)
{
System.out.print(“ ”);
}

456
PROGRAM AND ALGORITHMS

for(int c = r; c <= (DA.length – 1); c++)


{
System.out.print(“ ” + DA[r][c]);
}
System.out.println();
}
}
void fnLowerMatrix(int DA[ ][ ])
{
for(int r = 0; r <= DA.length – 1; r++)
{
for(int c = 0; c <= r; c++)
{
System.out.print(DA[r][c] + “ ”);
}
System.out.println();
}
}
void main()
{
// Random 1 digit number as order of the arrays
int n = (int)(Math.random() * 10);
n = (n <= 1) ? (2 + n) : n; // in case n is 0, it is modified
int AT[ ][ ] = new int[n][n]; //declaring the arrays
int r, c;
//filling the array AT[ ][ ] with Random numbers
fnFill(AT);
System.out.println(“Matrix AT[ ][ ] is : ”);
fnDisplay(AT);
System.out.println(“Upper Matrix of AT[ ][ ] is : ”);
fnUpperMatrix(AT);
System.out.println(“Lower Matrix of AT[ ][ ] is : ”);
fnLowerMatrix(AT);
}
}

457
ISC COMPUTER SCIENCE – XI

OUTPUT :
Matrix AT[ ][ ] is :
51 47 91 16
19 80 56 37
50 65 89 34
72 98 85 42
Upper Matrix of AT[ ][ ] is :
51 47 91 16
80 56 37
89 34
42
Lower Matrix of AT[ ][ ] is :
51
19 80
50 65 89
72 98 85 42

Topic 10 Project Program Analysis [Program Outline]


1. Digits in a Number : [A few sample methods shown here, upgradable programs]

import java.util.*;
class clDigit
{
int n;
int fnDigitProduct()
{
int p = 1, cn = n;
while(cn > 0)
{
p *= cn % 10;
cn /= 10;
}
return p;
}
int fnEvenDigitSum()
{

458
PROGRAM AND ALGORITHMS

int se = 0, cn = n, d = 0;
while(cn > 0)
{
d = cn % 10;
se += ( (d % 2 == 0) ? d : 0);
cn /= 10;
}
return se;
}
int fnCountDigits()
{
int cnt = 0, cn = n;
while(cn > 0)
{
cnt++;
cn /= 10;
}
return cnt;
}
int fnNewNumber1() // new number using the odd digits of n
{
int num1 = 0, cn = n, d = 0;
while(cn > 0)
{
d = cn % 10;
System.out.println(“d = ” + d);
num1 = (d % 2 != 0 ? (num1 * 10 + d) : num1);
cn /= 10;
}
return num1;
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter number :”);
n = sc.nextInt();

459
ISC COMPUTER SCIENCE – XI

System.out.println(“\nThe number is : ” + n + “\nMake a choice : ”);


System.out.println(“1. Product of Digits”);
System.out.println(“2. Sum of Even Digits”);
System.out.println(“3. Count of Digits”);
System.out.println(“4. Make a new number”);
System.out.println(“Enter Choice : ”);
int ch = sc.nextInt();
int r = 0;
switch(ch)
{
case 1 : r = fnDigitProduct();
break;
case 2 : r = fnEvenDigitSum();
break;
case 3 : r = fnCountDigits();
break;
case 4 : r = fnNewNumber1();
break;
default : ch = 5;
}
if(ch != 5)
System.out.print(“Result is” + r);
else
System.out.print(“Sorry ! Wrong Choice”);
}
}
2. Calculator : [A 5 function calculator with effect of continued calculation and refresh]
u For the 1st round, input both the operands (n1, n2) and the operand.
u For the next time onwards, allow a choice ( ch ) for clear or continue.
u If ch is clear, then input both the operands again.
u If ch is continue, then input the operator and the next operand.
u The process repeats as long as the user wants.
u The operators can be + – * / %
u Do not allow division by 0.
import java.util.*;
class clCalculator
{

460
PROGRAM AND ALGORITHMS

void main()
{
double a = 0, b = 0, r = 0;
char ch = ‘ ’;
String bfr;
Scanner sc = new Scanner(System.in);
boolean refresh = true;
do
{
if(refresh == true)
{
System.out.print(“Enter 1st number”);
a = sc.nextDouble();
bfr = sc.nextLine(); //clearing buffer for next char input
refresh = false;
}
System.out.print(“Enter operator ( + – * / %) : ”);
ch = sc.nextLine().charAt(0);
System.out.print(“Enter another number”);
b = sc.nextDouble();
bfr = sc.nextLine(); //clearing buffer for next char input

switch(ch)
{
case ‘+’ : r = a + b;
break;
case ‘*’ : r = a * b;
break;
default : System.out.print(“No such operator”);
}
System.out.println(“The Result is : ” + r);

System.out.print(“Enter choice: Refresh(R) or Exit(E) : ”);


ch = sc.nextLine().charAt(0);

if(ch == ‘R’)
{

461
ISC COMPUTER SCIENCE – XI

r = 0;
refresh = true;
}
else if(ch == ‘E’)
{
System.out.print(“\n Thank You.”);
}
}while(ch != ‘E’);
}
}

OUTPUT :
Enter 1st number 11
Enter operator (+ – * / %) : +
Enter another number 22
The Result is : 33.0

Enter choice : Refresh(R) or Exit(E) : x


Enter operator (+ – * / %) : +
Enter another number 33
The Result is : 44.0

Enter choice : Refresh(R) or Exit(E) : v


Enter operator (+ – * / %) : +
Enter another number 10
The Result is : 21.0

Enter choice : Refresh(R) or Exit(E) : R


Enter 1st number 30
Enter operator (+ – * / %) : +
Enter another number 20
The Result is : 50.0

Enter choice : Refresh(R) or Exit(E) : E


Thank You.
3. Set Application
u A set is a collection of unique integers.
Apply an integer array to represent a set. [ Fill it with unique values.]

462
PROGRAM AND ALGORITHMS

u For two sets, find their


l Union
l Intersection
l Difference
Ex : Set_A = {2, 6, 9, 4, 5} Set_B = {3, 8, 6, 1, 9, 2, 7}
Union : {2, 6, 9, 4, 5, 3, 8, 1, 7} Intersection : {2, 6, 9}
Difference (Set_A – Set_B) = {4, 5} (Set_B – Set_A) = {3, 8, 1, 7}
//SET HANDLING USING ARRAYS
import java.util. *;
public class clSet
{
boolean fnIsPresent(int A[], int p, int val)
{
for(int j = 0; j <= p – 1; j++)
{
if(A[j] == val)
{
return true;
}
}
return false;
}
int[ ] fnMakeSet(int n) // creates a set of size n and returns it
{
int S[] = new int [n];
int p = 0, val = 0;
Scanner sc = new Scanner(System.in);

System.out.print(“Enter” + n + “elements of the set :\n”);


while(p <= n – 1)
{

System.out.print(“\nEnter element for cell num” + p + “ : ”);


val = sc.nextInt();
if(fnIsPresent(S, p, val) == false)
{
S[p++] = val;
}
else
{

463
ISC COMPUTER SCIENCE – XI

System.out.print(“\n Element already present. Enter again”);


}
}
return S;
}
void fnSetIntersection(int A[], int B[])
{
int sm = (A.length < B.length) ? A.length : B.length;
int p = 0;
int IS[] = new int [sm];
//compare each element of the 1st set to all the elements of the 2nd set
//common elements are to be sent to set_intersection
for(int r = 0; r <= A.length – 1; r++)
{
for(int c = 0; c <= B.length – 1; c++)
{
if (A[r] == B[c])
{
IS[p++] = A[r]; // p inc with each common element found
break;
}
}
}
fnShowSet(IS, p);
}
void fnSetUnion(int A[], int B[])
{
int p = 0;
int US[] = new int [A.length + B.length];
for(int r = 0; r <= A.length – 1; r++)
{
US[p++] = A[r];
}
for(int r = 0; r <= B.length – 1; r++)
{

464
PROGRAM AND ALGORITHMS

if(fnIsPresent(US, p, B[r]) == false)


{
US[p++] = B[r];
}
}
fnShowSet(US, p);
}
void fnSetDifference(int A[], int B[])
{
int SD[] = new int [A.length];
int p = 0;
for(int r = 0; r <= A.length – 1; r++)
{
if(fnIsPresent(B, B.length, A[r]) == false)
{
SD[p++] = A[r];
}
}
fnShowSet(SD, p);
}
void fnShowSet(int S[])
{
System.out.print(“ { ”);
for(int j = 0; j <= S.length – 1; j++)
{
System.out.print(S[j] + “ ”);
}
System.out.print(“}\n”);
}
void fnShowSet(int S[], int p) //fn overloading
{
System.out.print(“\n The set with” + p + “ elements is { ”);
for(int j = 0; j <= p – 1; j++)
{
System.out.print(S[j] + “ ”);
}
System.out.print(“ } ”);
}

465
ISC COMPUTER SCIENCE – XI

void main()
{
int size = 6;
int Set1[] = new int [size];
Set1 = fnMakeSet(size);
int Set2[] = new int [size + 4];
Set2 = fnMakeSet(size + 4);
System.out.print(“\f Set1 is : ”); fnShowSet(Set1);
System.out.print(“\n Set2 is : ”); fnShowSet(Set2);
System.out.print(“\n\n Set1 Intersection Set2 is : ”);
fnSetIntersection(Set1, Set2);
System.out.print(“\nSet1 Union Set2 is : ”);
fnSetUnion(Set1, Set2);
System.out.print(“\nSet1 – Set2 is : ”);
fnSetDifference(Set1, Set2);
System.out.print(“\nSet2 – Set1 is : ”);
fnSetDifference(Set2, Set1);
}
}
OUTPUT :
Set1 is : {11 22 33 44 55 66}
Set2 is : {1 2 3 4 5 66 7 8 9 33}
Set1 Intersection Set2 is :
The set with 2 elements is {33 66}
Set1 Union Set2 is :
The set with 14 elements is {11 22 33 44 55 66 1 2 3 4 5 7 8 9}
Set1 – Set2 is :
The set with 4 elements is {11 22 44 55}
Set2 – Set1 is :
The set with 8 elements is {1 2 3 4 5 7 8 9}

4. Sort and Search , all as methods of a single program.


Sort : Bubble, Selection, Insertion.
Search : Linear, Binary

466
PROGRAM AND ALGORITHMS

Also write a method that shuffles the elements of the array each time it is
invoked.
Note : that Binary Search can be activated only if the array is pre-sorted.
import java.util.*;
public class clSortSearch
{
int RS[], size;
clSortSearch(int n)
{
size = n;
RS = new int [size];
}
void fnFill()
{
//fill the array RS[ ] with variables
}
void fnShow()
{
//print the array
}
boolean fnIsSorted()
{
//Verify whether the array is in (ascending) order or not
}
void fnSchuffle()
{
//Intermix up the elements of RS[ ] so that it gets shuffled
}
void fnSortBubble()
{
for(int i = 0; i <= size – 2; i++)
{
for(int j = 0; j < size – i – 1; j++)
{
if(RS[j] > RS[j + 1])
{

467
ISC COMPUTER SCIENCE – XI

int t = RS[j];
RS[j] = RS[j + 1];
RS[j + 1] = t;
}
}
}
}
boolean fnSearchLinear(int val)
{
for(int j = 0; j <= size – 1; j++)
{
if(RS[j] == val)
{
return true;
}
}
return false;
}
int Menu()
{
Scanner sc = new Scanner(System.in);
int ch;
System.out.println(“\n1. Fill Array Elements”);
System.out.println(“2. Display the current Array.”);
System.out.println(“3. Sort Bubble”);
System.out.println(“4. Sort Selection”);
System.out.println(“5. Sort Insertion”);
System.out.println(“6. Search Linear”);
System.out.println(“7. Search Binary”);
System.out.println(“8. Shuffle Array”);
System.out.println(“0. Exit”);
System.out.println(“Enter a Choice :”);
ch = sc.nextInt();
return ch;
}
void main()
{
int ch;
do

468
PROGRAM AND ALGORITHMS

{
ch = Menu();
switch(ch)
{
case 0 : System.out.print(“Thank you.”);
break;
case 1 : fnFill();
break;
case 2 : fnShow();
break;
case 3 : fnSortBubble();
break;
case 4 : fnSortSelection();
break;
case 5 : fnSortInsertion();
break;
case 6 : //input value to search
fnSearchLinear(value);
break;
case 7 : //input value to search
fnSearchBinary(value);
break;
case 8 : fnShuffle();
break;
default : System.out.println(“Please enter a Valid Choice. \n”);
}
} while(ch != 0);
}
}
5. Count the Frequency of each element in an array.
Eg., : 4 4 2 2 2 4 4 2 4
No of occurrences of :
4 → 5 2 → 4 [Note : Do not repeat the answer.]

6. 
Shrik / Pack an array (remove the duplicate elements, without using another
array).
Array : 4 3 2 4 2 4 4 2 2
After packing : 4 3 2
import java.util.Scanner;
public class Array_Pack

469
ISC COMPUTER SCIENCE – XI

{
int arr[ ], n;
Scanner ob = new Scanner(System.in);
public void fnInput()
{
System.out.print(“Enter the Size of the Array : ”);
n = ob.nextInt();
System.out.println(“Enter the Array Elements : ”);
arr = new int[n];
for(int i = 0; i < n; i++)
{
System.out.println(“Enter the Element number” + (i + 1) + “ : ”);
arr[i] = ob.nextInt();
}
}
public void fnDisplay()
{
System.out.println(“\f\n The Array Elements are : ”);
int i;
for(i = 0; i < n; i++)
{
System.out.print(arr[i] + “ ”);
}
}
Public void fnPack()
{
int i, j, e, f = 0, p;
for(int c = 1; c <= n – 1; c++)
{
int tmp = arr[c];
boolean isp = false;
for(int lp = 0; l p <= c – 1; lp++)
{
if(arr[lp] == tmp)

470
PROGRAM AND ALGORITHMS

{
isp = true;
break;
}
}
if(isp == true)
{
for(int rp = c + 1; rp <= n – 1; rp++)
{
arr[rp – 1] = arr[rp];
}
n 
– –;
c – –;
}
System.out.println(“In c = ” + c + “ n = ” + n);
}
for(int c = 0; c <= n – 1; c++)
{
System.out.print(“ ” + arr[c]);
}
}
public void main()
{
fnInput();
fnDisplay();
fnPack();
fnDisplay();
}
}

7. BINOMIAL SERIES
Input a, x, n, and calculate the result of the Binomial Series.
(a + x)^n = nC0 * a^n * x^0 + nC1 * a^(n – 1) * x^1 + … + nCr * a^(n – r) * x^r
+ .. + nCn * a^(n – n) * x^n where nCr = n! / ( r! x (n – r) ! )
import java.util.Scanner;

471
ISC COMPUTER SCIENCE – XI

public class clBinomial


{
int a, x, n;
public void fnInput()
{
Scanner sc = new Scanner(System.in);
System.out.print(“For (a + x)^n \nEnter a : ”);
n = sc.nextInt();
System.out.print(“Enter x : ”);
x = sc.nextInt();
System.out.print(“Enter n : ”);
n = sc.nextInt();
}
double fnPower(int p, int q)
{
//calculate p^q, without Math method
//return ..;
}
double fnFactorial(int p)
{
//calculate factorial of p
//return ..;
}
double fnNCR(int n, int r)
{
//calculate nCr, combination of n, r
//return ..;
}
double fnSeries()
{
// Sum of the Binomial Series
for(int t = 0; t <= n; t++)
{
// term1 = fnNCR(n, t)
// term2 = fnPower(a, n – 0);
// term3 = fnPower(x, t);

472
PROGRAM AND ALGORITHMS

// sum of product of the above terms


}
//return .. ;
}

public void main()


{
fnInput();
fnSeries();
}
}
8. Conversion of a number from one base to another [ decimal / binary ].
import java.util.*;
class clConversion
{
int[ ] fnDeciToBinary(int n)
{
int cn = n, d = 0, j = 0;
int B[ ] = new int [32];
while(cn != 0)
{
B[d++] = cn % 2;
cn /= 2;
} // d stores how many cells were filled
System.out.print(“\n the corresponding binary number is :\n”);
for(j = d – 1; j >= 0; j – –)
{
System.out.print(B[j]);
}
return B;
}
int fnBinToDeci(String B)
{
//Convert the binary number B to decimal
//return D
}
void main()
{

473
ISC COMPUTER SCIENCE – XI

// menu to choose and input and print accordingly


}
}
10. Date Handing
Program of Calendar of Any Year
import java.util.*;
public class clCalendar
{
int mntEnd[ ] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int baseYear = 2015;
int baseYearDayNum = 5;
int fnIsLeap(int y)
{
if(( y % 4 == 0 && y % 100 != 0 ) || ( y % 400 == 0 ))
return 1;
return 0;
}
int fnYearDayNum(int year)
{
int c = 0;
if(year > baseYear)
{
c = baseYearDayNum + (year – baseYear);
for(int y = baseYear; y < year; y++)
{
c = c + fnIsLeap(y);
}
c = (c % 7 == 0) ? 7 : (c % 7);
}
else
{
c = baseYearDayNum – (baseYear – year);
for(int y = baseYear–1; y >= year; y– –)
{
c = c – fnIsLeap(y);

474
PROGRAM AND ALGORITHMS

if(c < 1)
c += 7;
}
System.out.println(“old c = ” + c);
}
return c;
}
int fnNextMonthDayNum(int thisMntNum, int thisMntDayNum)
{
return ( (thisMntDayNum + mntEnd[thisMntNum] % 7) % 7);
}
void fnMonthDisplay(int thisMntNum, int thisMntDayNum)
{
System.out.println(“Sun \t Mon \t Tue \t Wed \t Thu \t Fri \t Sat\t ”);
int date = 1 , dn = 1;
while(dn <= thisMntDayNum – 1)
{
System.out.print(“\t”);
dn++;
}
while(date <= mntEnd[thisMntNum])
{
System.out.print(date++ + “\t”);
if(dn % 7 == 0)
System.out.println();
dn++;
}
}
void main()
{
Scanner sc = new Scanner(System.in);
System.out.print(“ Enter Year : ”);

475
ISC COMPUTER SCIENCE – XI

int year = sc.nextInt();


mntEnd[2] += fnIsLeap(year);
int dayNum = fnYearDayNum(year);
String Months[ ] = {“ ”, “JAN”, “FEB”, “MAR”, “APR”, “MAY”, “JUN”, “JUL”,
“AUG”, “SEP”, “OCT”, “NOV”, “DEC”};
for(int m = 1; m <= 12; m++)
{
System.out.println(“\n\n” + Months[m]);
fnMonthDisplay(m, dayNum);
dayNum = fnNextMonthDayNum(m, dayNum);
}
}
}
OUTPUT :
Enter Year : 2000
JAN
Sun Mon Tue Wed Thu Fri Sat
1

2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
FEB
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5

6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29
MAR
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4

5 6 7 8 9 10 11

476
PROGRAM AND ALGORITHMS

12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
NOV
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4

5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
DEC
Sun Mon Tue Wed Thu Fri Sat
1 2

3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
qq

477
NOTES
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
NOTES
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
NOTES
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________

You might also like