Professional Documents
Culture Documents
Computer Science - Textbook For - Rupa Pandit
Computer Science - Textbook For - Rupa Pandit
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
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
2. Encodings 63 – 83
l Numbers
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.
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
15
ISC COMPUTER SCIENCE – XI
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 :
18
NUMBERS
.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
8 125 125/8 Q = 15 R = 5 5
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 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]
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
16 50 50/16 Q = 3 R = 2 2
16 3 50/16 Q = 0 R = 2 3
16 0
21
ISC COMPUTER SCIENCE – XI
Ex 4. (175.125)10 = (?)16
The integer part — (175)10 = (AF)16
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
26
NUMBERS
27
ISC COMPUTER SCIENCE – XI
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
28
NUMBERS
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
→ 3 × 1 + 5 × 8 + 5 × 0.125
→ 3 + 40 + 0.625
→ (43.625)10
(43.625)10 = (?)16[(decimal) → (hexadecimal)]
The integer part–
→ 12 × 1 + 2 × 16 + 8 × 0.0625
→ 12 + 32 + 0.5
→ (44.5)10
(44.5)10 = (?)8[(decimal) → (octal)]
The integer part —
31
ISC COMPUTER SCIENCE – XI
2. Conversion Clues :
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
32
NUMBERS
33
ARITHMETIC
1B OPERATIONS
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
(v) Verification
1 1
1 1 – Result
+ 1 – Num2
1 0 0 – Num1
Ans : (11)2
38
ARITHMETIC OPERATIONS
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
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 :
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
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
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 :
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
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
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
Fraction Handling
Examples : Complement of the given numbers in given bases :
54
ARITHMETIC OPERATIONS
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
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
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
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
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
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.
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
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
(0.0050684001)10 = 5.0684001 × 10 –3
(60052401)8 = 6.0052401 × 87
In a normalized floating point number, two cases occur depending on the size of the
exponent namely, overflow and underflow.
67
ISC COMPUTER SCIENCE – XI
For example :
• 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 :
For example :
2.4 × 10–3
× 6.3 × 102
15.12 × 10–3+2 = 15.12 × 10–1
= 1.512 × 100
= 1.512
68
ENCODINGS
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
OR OPERATOR
Example : 100011 OR 110010
Sol. 100011
AND 110010
1 1 0 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
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
71
ISC COMPUTER SCIENCE – XI
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
73
ISC COMPUTER SCIENCE – XI
74
ENCODINGS
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
(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
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
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
⇒ –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.
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
83
PROPOSITIONAL
3 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
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.
PROPOSITIONAL DEFINITIONS
(i) Well Formed Formula. (ii) Tautology.
(iii) Contradiction. (iv) Contingency.
(v) Satisfiable. (vi) Unsatisfiable.
87
ISC COMPUTER SCIENCE – XI
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
Note :
l The operations on propositions result in True or False which are denoted by 1 or 0
only.
91
ISC COMPUTER SCIENCE – XI
92
PROPOSITIONAL LOGIC
93
ISC COMPUTER SCIENCE – XI
94
PROPOSITIONAL LOGIC
95
ISC COMPUTER SCIENCE – XI
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
97
ISC COMPUTER SCIENCE – XI
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
EXERCISE
98
PROPOSITIONAL LOGIC
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).
101
4 LOGIC GATES
l Logic Gate
Elementary Logic Gates (AND, NOT, OR)
Universal Gates (NAND, NOR)
Other Gates (XOR, XNOR)
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
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
Product terms are those in which elementary propositions are multiplied. For
e.g., A.B’.C
Sum terms are those in which elementary propositions are added. For e.g., (A+B’+C)
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
(iii) F3 = A + B’ + A’.B’
105
ISC COMPUTER SCIENCE – XI
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.
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.]
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. :
F3
108
LOGIC 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
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.
A (A + A)' = A'
110
LOGIC GATES
OR using NOR :
OR Gate : OR Gate using NOR Gate :
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.]
(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 :
112
LOGIC GATES
A B
1
H3
3
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).]
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.
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
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
P Q R
116
LOGIC GATES
P Q R
S
EXERCISE
117
ISC COMPUTER SCIENCE – XI
(b)
118
INTRODUCTION
5 TO JAVA
(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.
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
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.
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
I. Click on the BlueJ icon on the start menu. It will show the BlueJ
opening screen.
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.
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
128
INTRODUCTION TO JAVA
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 :
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
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
EXERCISE
133
ISC COMPUTER SCIENCE – XI
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.
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());
136
JAVA STATEMENTS
Program Example :
import java.util.*;
public class SampleInput2
{
private int x;
double f;
char vh;
String sh;
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);
}
}
CONDITIONS
Relational Operators
Conditions are made by using Relational operators. There are six relational operators,
given below :
Relational
Use Example
Operator
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
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.*;
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
143
ISC COMPUTER SCIENCE – XI
PROGRAM
switch(dn)
{
case 1 : System.out.print(“\n dn = ” + dn + “ is SUNDAY.”);
break;
144
JAVA STATEMENTS
145
ISC COMPUTER SCIENCE – XI
dn = 5 is FRIDAY.
dn = 5 is SATURDAY.
dn = 5 is an INVALID day number.
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
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
void sample2()
{
for(int k = 1; k <= 5; k++)
{
System.out.println(“Inside 1st block k =” +k);
}
for(int k = 11; k <= 15; k++)
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.
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
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
int j = 0;
if(j == 15)
break;
156
JAVA STATEMENTS
Value of j = 10
Value of j = 11
Value of j = 12
Value of j = 13
Value of j = 14
int j = 0;
break;
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.
int j = 0;
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
158
JAVA STATEMENTS
}
qq
159
EXCEPTION
7 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.
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
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
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
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
“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
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
EXERCISE
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 );
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
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
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
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
fnDisplay(nov);
System.out.print(“\n Second Array : ”);
fnDisplay(dec);
182
METHODS (FUNCTIONS)
183
ISC COMPUTER SCIENCE – XI
import java.util.*;
public class clArTest
{
184
METHODS (FUNCTIONS)
void main()
{
int tmp[] = new int[10];
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;
cAdd.fnShowComplex();
}
public void main()
{
clComplex cA = new clComplex();
clComplex cB = new clComplex();
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
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
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();
BookCost.fnInput();
191
ISC COMPUTER SCIENCE – XI
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;
}
193
ISC COMPUTER SCIENCE – XI
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 “ ”.
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)
EXERCISE
(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
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;
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
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
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
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
209
ISC COMPUTER SCIENCE – XI
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
212
PROGRAM TOOLS AND ARRAYS
The name of the array here is TA. It has 4 rows and 5 columns.
213
ISC COMPUTER SCIENCE – XI
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
The advantage of using this method is that we can have multiple cells filled with
variables without executing the input statement.
216
PROGRAM TOOLS AND ARRAYS
217
ISC COMPUTER SCIENCE – XI
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
220
PROGRAM TOOLS AND ARRAYS
EXERCISE
221
ISC COMPUTER SCIENCE – XI
222
PROGRAM TOOLS AND ARRAYS
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
225
ISC COMPUTER SCIENCE – XI
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
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.
[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
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
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
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
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
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Low
High
Mid
237
ISC COMPUTER SCIENCE – XI
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
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
}
}
}
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
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
(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
246
STRINGS AND LIBRARY METHODS
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”
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
251
ISC COMPUTER SCIENCE – XI
252
STRINGS AND LIBRARY METHODS
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
256
STRINGS AND LIBRARY METHODS
257
ISC COMPUTER SCIENCE – XI
int c = 0;
se = se.toUpperCase();
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
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
263
ISC COMPUTER SCIENCE – XI
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
268
STRINGS AND LIBRARY METHODS
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
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
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
275
ISC COMPUTER SCIENCE – XI
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
277
ISC COMPUTER SCIENCE – XI
278
STRINGS AND LIBRARY METHODS
279
ISC COMPUTER SCIENCE – XI
SCANNER CLASS
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
281
ISC COMPUTER SCIENCE – XI
282
STRINGS AND LIBRARY METHODS
283
ISC COMPUTER SCIENCE – XI
284
STRINGS AND LIBRARY METHODS
285
ISC COMPUTER SCIENCE – XI
286
STRINGS AND LIBRARY METHODS
288
STRINGS AND LIBRARY METHODS
290
STRINGS AND LIBRARY METHODS
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
296
STRINGS AND LIBRARY METHODS
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
300
DATA FILE
12 HANDLING
Byte
v Streams
Character
v Streams
Standard Streams
v
l Operations on Files
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
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
306
DATA FILE HANDLING
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
309
ISC COMPUTER SCIENCE – XI
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
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
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
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
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
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
328
DATA FILE HANDLING
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
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
333
ISC COMPUTER SCIENCE – XI
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
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
338
RECURSIVE FUNCTIONS
13 RECURSIVE
FUNCTIONS
340
RECURSIVE FUNCTIONS
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
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);
}
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
344
RECURSIVE FUNCTIONS
345
ISC COMPUTER SCIENCE – XI
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
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
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.
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
353
ISC COMPUTER SCIENCE – XI
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
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
EXERCISE
357
ISC COMPUTER SCIENCE – XI
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.
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.
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.
364
TRENDS IN COMPUTING AND ETHICAL ISSUES
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
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.
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
370
TRENDS IN COMPUTING AND ETHICAL ISSUES
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
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
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]
YES
<=
NO
375
ISC COMPUTER SCIENCE – XI
EXERCISE
376
ALGORITHM
(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)
379
ISC COMPUTER SCIENCE – XI
PROGRAMS AND
17 ALGORITHMS
l Programs
l Algorithms
l Programs Solutions
PROGRAMS
380
PROGRAM AND ALGORITHMS
381
ISC COMPUTER SCIENCE – XI
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
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
389
ISC COMPUTER SCIENCE – XI
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
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
395
ISC COMPUTER SCIENCE – XI
396
PROGRAM AND ALGORITHMS
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
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
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
400
PROGRAM AND ALGORITHMS
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;
}
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 :: ”);
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
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
411
ISC COMPUTER SCIENCE – XI
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
}
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();
420
PROGRAM AND ALGORITHMS
421
ISC COMPUTER SCIENCE – XI
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.
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) + “) ” + “ ; ”);
}
}
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();
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
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”);
}
}
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
434
PROGRAM AND ALGORITHMS
435
ISC COMPUTER SCIENCE – XI
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
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
445
ISC COMPUTER SCIENCE – XI
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
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
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
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
456
PROGRAM AND ALGORITHMS
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
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
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);
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
462
PROGRAM AND ALGORITHMS
463
ISC COMPUTER SCIENCE – XI
464
PROGRAM AND ALGORITHMS
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}
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
472
PROGRAM AND ALGORITHMS
473
ISC COMPUTER SCIENCE – XI
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
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
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________