Sunteți pe pagina 1din 31

www.surabooks.com This material only for sample www.surabooks.

com
Namma Kalvi

UNIT-I
 www.nammakalvi.org

PROBLEM SOLVING TECHNIQUES

1
Chapter
FUNCTION

ns
CHAPTER SNAPSHOT
1.1 Introduction

io
1.2 Function with respect to Programming language
at
1.2.1 Function Specification
1.2.2 Parameters (and arguments)
ic
1.3 Interface vs Implementation
1.4 Pure functions
bl

1.4.1 Impure functions


1.4.2 Side-effects (Impure functions)
Pu

1.4.3 Chameleons of Chromeland problem using function


ra
Su

[1]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit I - Chapter 1
www.surabooks.com

Sura’s ➠ XII Std - Computer Science

Evaluation
 
This material only for sample www.surabooks.com

www.nammakalvi.org

8. Which of the following carries out the


Part - I instructions defined in the interface?
Choose the best answer  (1 mark) (a) Operating System (b) Compiler
(c) Implementation (d) Interpreter
1. The small sections of code that are used to  [Ans. (c) Implementation]
perform a particular task is called
(a) Subroutines (b) Files 9. The functions which will give exact result
(c) Pseudo code (d) Modules when same arguments are passed are called
 [Ans. (a) subroutines] (a) Impure functions (b) Partial Functions
(c) Dynamic Functions (d) Pure functions
2. Which of the following is a unit of code that is  [Ans. (d) Pure functions]
often defined within a greater code structure?
(a) Subroutines (b) Function 10. The functions which cause side effects to the
arguments passed are called
(c) Files (d) Modules

ns
(a) impure function (b) Partial Functions
 [Ans. (b) Function]
(c) Dynamic Functions (d) Pure functions
3. Which of the following is a distinct syntactic  [Ans. (a) impure function]

io
block?
Part - II
(a) Subroutines (b) Function
(c) Definition (d) Modules
at
Answer the following questions
 [Ans. (c) Definition]  (2 marks)
ic
4. The variables in a function definition are 1. What is a subroutine?
bl

called as
Ans. (i) Subroutines are the basic building blocks of
(a) Subroutines (b) Function
Pu

computer programs. Subroutines are small


(c) Definition (d) Parameters sections of code that are used to perform a
 [Ans. (d) Parameters] particular task that can be used repeatedly.
5. The values which are passed to a function (ii) In Programming languages these
ra

definition are called subroutines are called as Functions.


(a) Arguments (b) Subroutines 2. Define Function with respect to Programming
Su

(c) Function (d) Definition language.


 [Ans. (a) Arguments] Ans. A function is a unit of code that is often defined
within a greater code structure. Specifically, a
6. Which of the following are mandatory to function contains a set of code that works on
write the type annotations in the function many kinds of inputs, like variants, expressions
definition? and produces a concrete output.
(a) Curly braces (b) Parentheses
(c) Square brackets (d) indentations 3. Write the inference you get from X:=(78).
 [Ans. (b) Parentheses] Ans. X:= (78) has an expression in it but (78) is not
itself an expression. Rather, it is a function
7. Which of the following defines what an object definition. Definitions bind values to names,
can do? in this case the value 78 being bound to the
(a) Operating System (b) Compiler name ‘X’. Definitions are not expressions, at
(c) Interface (d) Interpreter the same time expressions are also not treated
 [Ans. (c) Interface] as definitions. Definitions are distinct syntactic
blocks. Definitions can have expressions nested
inside them, and vice-versa.

2
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

4. Differentiate interface and implementation.


Ans. The difference between interface and
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


3. What is the side effect of impure function.
Give example.

Function
implementation is Ans. (i) The variables used inside the function may
Interface Implementation cause side effects though the functions
Interface just Implementation carries which are not passed with any arguments.
defines what an out the instructions In such cases the function is called impure
object can do, but defined in the interface function.
won't actually do it (ii) When a function depends on variables or
functions outside of its definition block,
5. Which of the following is a normal function
you can never be sure that the function will
definition and which is recursive function
behave the same every time it’s called.
definition.
i) let rec sum x y : (iii) For example the mathematical function
random() will give different outputs for the
return x + y
same function call.
ii) let disp :
Program :

ns
print 'welcome'
let Random number
iii) let rec sum num :
let a := random()
if (num!=0) then return num + sum

io
if a > 10 then
(num-1)
return: a
else
return num
at else
return: 10
ic
Ans. (i) Recursive function
(iv) Here the function Random is impure as it
(ii) Normal function
is not sure what will be the result when we
bl

(iii) Recursive function call the function.


Part - III
Pu

4. Differentiate pure and impure function.


Answer the following questions Ans.

 (3 marks) Interface Implementation


ra

The return value of The return value


1. Mention the characteristics of Interface. the pure functions of the impure
Su

Ans. (i) The class template specifies the interfaces to solely depends on its functions does not
enable an object to be created and operated arguments passed. solely depend on its
properly. Hence, if you call arguments passed.
(ii) An object's attributes and behaviour is the pure functions Hence, if you call the
controlled by sending functions to the with the same set of impure functions
object. arguments, you will with the same set of
always get the same arguments,
2. Why strlen is called pure function? return values. you might get the
Ans. (i) strlen is a pure function because the They do not have any different return
function takes one variable as a parameter, side effects. values. For example,
and accesses it to find its length. random(), Date().
(ii) This function reads external memory but They do not modify They may modify the
does not change it, and the value returned the arguments which arguments which are
derives from the external memory accessed. are passed to them passed to them

3
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 1
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


5. What happens if you modify a variable outside
the function? Give an example.
 
This material only for sample www.surabooks.com

www.nammakalvi.org
compared to 0 with the equality operator,
so ‘b’ is also a type of ‘int’. Since ‘a’ is
Ans. One of the most popular groups of side effects is multiplied with another expression using
modifying the variable outside of function. the * operator, ‘a’ must be an int.
For example : (ii) Parameter with Type : Now let us write
let y: = 0 the same function definition with types for
(int) inc (int) x some reason:
y: = y + x; (requires: b> 0 )
(returns: a to the power of b )
return (y)
let rec pow (a: int) (b: int) : int :=
Part - IV if b=0 then 1
Answer the following questions else a * pow b (a-1)
■ When we write the type annotations for
 (5 marks) ‘a’ and ‘b’ the parentheses are mandatory.
1. What are called Parameters and write a note Generally we can leave out these

ns
on annotations, because it's simpler to let the
(i) Parameter without Type compiler infer them.
(ii) Parameter with Type ■ T  here are times we may want to explicitly

io
write down types. This is useful on
Ans. Parameters (and arguments) : Parameters at times when you get a type error from
are the variables in a function definition and
the compiler that doesn't make sense.
arguments are the values which are passed to a
Explicitly annotating the types can help
function definition.
ic
with debugging such an error message.
(i)  Parameter without Type : Let us see an
bl

example of a function, definition : 2. Identify in the following program


(requires: b>=0 ) let rec gcd a b :=
Pu

(returns: a to the power of b) if b <> 0 then gcd b (a mod b) else return a


let rec pow a b:=
if b=0 then 1 i) Name of the function
ii) Identify the statement which tells it is a
ra

else a * pow a (b –1)


■  In the above function definition variable recursive function
‘b’ is the parameter and the value which is iii) Name of the argument variable
Su

passed to the variable ‘b’ is the argument. iv) Statement which invoke the function
The precondition (requires) and recursively
postcondition (returns) of the function is v) Statement which terminates the recursion
given. Ans. (i) gcd
■  Note we have not mentioned any types: (ii) let rec gcd
(data types). Some language compiler (iii) a, b
solves this type (data type) inference
problem algorithmically, but some require (iv) gcd b (a mod b)
the type to be mentioned. (v) return a
■  In the above function definition if 3. Explain with example Pure and impure
expression can return 1 in the then branch, functions.
by the typing rule the entire if expression Ans. Pure functions :
has type int.
(i) Pure functions are functions which will
■  Since the if expression has type ‘int’, the give exact result when the same arguments
function's return type also be ‘int’. ‘b’ is are passed.

4
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

(ii) For example the mathematical function sin


(0) always results 0. This means that every
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


(ii) When a function depends on variables or
functions outside of its definition block,

Function
time you call the function with the same you can never be sure that the function
arguments, you will always get the same will behave the same every time it’s called.
result. For example the mathematical function
(iii) A function can be a pure function provided random() will give different outputs for the
it should not have any external variable same function call.
which will alter the behaviour of that let Random number
variable. let a := random()
Let us see an example if a > 10 then
let square x return: a
else
return: x * x
return: 10
(iv) The above function square is a pure function (iii) Here the function Random is impure as it
because it will not give different results for is not sure what will be the result when we
same input. call the function.

ns
(v) There are various theoretical advantages of
having pure functions. One advantage is 4. Explain with an example interface and
that if a function is pure, then if it is called implementation.

io
several times with the same arguments, Ans. (i) An interface is a set of action that an object
the compiler only needs to actually call the can do. For example when you press a light
function once. Lt’s see an example
at switch, the light goes on, you may not have
let i: = 0; cared how it splashed the light. In Object
ic
if i <strlen (s) then Oriented Programming language, an
-- Do something which doesn't  Interface is a description of all functions
bl

 affect s that a class must have in order to be a new


interface.
Pu

++i
(vi) If it is compiled, strlen (s) is called each (ii) In our example, anything that "ACTS
time and strlen needs to iterate over the LIKE" a light, should have function
whole of ‘s’. If the compiler is smart definitions like turn_on () and a turn_off
ra

enough to work out that strlen is a pure (). The purpose of interfaces is to allow the
function and that ‘s’ is not updated in the computer to enforce the properties of the
Su

loop, then it can remove the redundant class of TYPE T (whatever the interface is)
extra calls to strlen and make the loop to must have functions called X, Y, Z, etc.
execute only one time. (iii) A class declaration combines the
(vii) From these what we can understand, strlen external interface (its local state) with an
is a pure function because the function implementation of that interface (the code
takes one variable as a parameter, and that carries out the behaviour). An object
accesses it to find its length. This function is an instance created from the class. The
reads external memory but does not interface defines an object’s visibility to the
change it, and the value returned derives outside world.
from the external memory accessed.  The difference between interface and
Impure functions : implementation is
(i) The variables used inside the function may Interface Implementation
cause side effects though the functions Interface just Implementation
which are not passed with any arguments. defines what an carries out the
In such cases the function is called impure object can instructions defined
function. do, but won't in the interface
actually do it

5
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 1
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


(iv) In object oriented programs classes are the
interface and how the object is processed
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(iii) The person who drives the car doesn't care
about the internal working. To increase
and executed is the implementation. the speed of the car he just presses the
Characteristics of interface : accelerator to get the desired behaviour.
(i) The class template specifies the interfaces to Here the accelerator is the interface
enable an object to be created and operated between the driver (the calling / invoking
properly. object) and the engine (the called object).
(ii) An object's attributes and behaviour is (iv) In this case, the function call would be
controlled by sending functions to the Speed (70): This is the interface. Internally,
object. the engine of the car is doing all the things.
For example, let's take the example of It's where fuel, air, pressure, and electricity
increasing a car’s speed. come together to create the power to move
the vehicle.
ENGINE (v) All of these actions are separated from the
driver, who just wants to go faster. Thus we
separate interface from implementation.

ns
(vi) Let us see a simple example, consider the
getSpeed
following implementation of a function

io
that finds the minimum of its three
No arguments:
required
speed
Pull Fuel
at
let min 3 x y z :=
Yes
if x < y then
ic
if x < z then x else z
Return
else
bl


if y < z then y else z

additional questions and Answers


Pu

Choose the Correct Answer 1 MARK 4. Which of the following are the values which
are passed to a function definition?
ra

1. Which of the following are expressed using (a) Parameters (b) Algorithm
statements of a programming language? (c) Data types (d) Arguments
Su

(a) Functions (b) Algorithm  [Ans. (d) Arguments]


(c) Interface (d) Implementation 5. The function definition is introduced by the
 [Ans. (b) Algorithm] keyword
(a) def (b) rec
2. What must the used when a bulk of statements (c) let (d) infer
to be repeated for many number of times? [Ans. (c) let]
(a) Algorithm (b) Program 6. The recursive function is defined using the
(c) Subroutines (d) Parameters keyword
 [Ans. (c) Subroutines] (a) let (b) let rec
(c) name (d) infer
3. Which of the following contains a set a
 [Ans. (b) let rec]
code that works an many kinds of input and
7. A function definition which call itself is called
produces a concrete output?
(a) user defined function
(a) Function (b) Algorithm (b) built-in function
(c) Arguments (d) Language (c) derived function
 [Ans. (a) Function] (d) recursive function
 [Ans. (d) recursive function]

6
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com

 
DATA ABSTRACTION
2
Chapter


www.nammakalvi.org

ns
io
CHAPTER SNAPSHOT at
2.1 Data Abstraction – Introduction
2.2 Abstract Data Types
ic
2.3 Constructors and Selectors
2.4 Representation of Abstract datatype using Rational numbers
bl

2.5 Lists, Tuples


Pu

2.5.1 List
2.5.2 Tuple
2.6 Data Abstraction in Structure
ra
Su

[9]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit I - Chapter 2
www.surabooks.com

Sura’s ➠ XII Std - Computer Science

Evaluation
 
This material only for sample www.surabooks.com

www.nammakalvi.org

8. Bundling two values together into one can be


Part - I considered as
Choose the best answer  (1 mark) (a) Pair
(b) Triplet
1. Which of the following functions that build
the abstract data type ? (c) Single
(a) Constructors (b) Destructors (d) Quadrat [Ans. (a) Pair]
(c) Recursive (d) Nested
9. Which of the following allow to name the
 [Ans. (a) Constructors]
various parts of a multi-item object?
2. Which of the following functions that retrieve (a) Tuples
information from the data type?
(b) Lists
(a) Constructors (b) Selectors
(c) Classes
(c) Recursive (d) Nested

ns
 [Ans. (b) Selectors] (d) Quadrats [Ans. (c) Classes]

3. The data structure which is a mutable ordered 10. Which of the following is constructed by

io
sequence of elements is called placing expressions within square brackets?
(a) Built in (b) List
at (a) Tuples (b) Lists
(c) Tuple (d) Derived data (c) Classes (d) Quadrats
 [Ans. (b) List]  [Ans. (b) Lists]
ic
4. A sequence of immutable objects is called Part - II
bl

(a) Built in (b) List Answer the following questions


(c) Tuple (d) Derived data  (2 marks)
Pu

 [Ans. (c) Tuple] 1. What is abstract data type?


Ans. (i) Abstract Data type (ADT) is a type (or
5. The data type whose representation is known
class) for objects whose behavior is defined
are called
ra

by a set of value and a set of operations.


(a) Built in datatype
(ii) The definition of ADT only mentions what
(b) Derived datatype
Su

operations are to be performed but not how


(c) Concrete datatype these operations will be implemented.
(d) Abstract datatype 
(iii) It does not specify how data will be
 [Ans. (b) Derived datatype ] organized in memory and what algorithms
6. The data type whose representation is will be used for implementing the
unknown are called operations. It is called “abstract” because
(a) Built in datatype it gives an implementation independent
view. The process of providing only the
(b) Derived datatype
essentials and hiding the details is known
(c) Concrete datatype
as abstraction.
(d) Abstract datatype 
 [Ans. (c) Concrete datatype] 2. Differentiate constructors and selectors.
Ans. (i) Constructors are functions that build the
7. Which of the following is a compound
abstract data type.
structure?
(ii) Selectors are functions that retrieve
(a) Pair (b) Triplet
information from the data type.
(c) Single (d) Quadrat
 [Ans. (a) Pair]

10
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com

3. What is a Pair? Give an example.


This material only for sample

Ans. (i) Any way of bundling two values together


Sura’s
www.surabooks.com

➠ XII Std - Computer Science


2. Which strategy is used for program designing?
Define that Strategy.

Data Abstraction
into one can be considered as a Pair. Lists Ans. A powerful strategy for designing programs:
are a common method to do so. Therefore 'wishful thinking'. Wishful Thinking is the
List can be called as Pairs. formation of beliefs and making decisions
(ii) Example : List = [10,20,30] according to what might be pleasing to imagine
4. What is a List? Give an example. instead of by appealing to reality.
Ans. (i) List is constructed by placing expressions 3. Identify Which of the following are
within square brackets separated by constructors and selectors?
commas. (a) N1=number()
(ii) Such an expression is called a list literal. (b) accetnum(n1)
List can store multiple values. Each value (c) displaynum(n1)
can be of any type and can even be another (d) eval(a/b)
list. (e) x,y= makeslope (m), makeslope(n)

ns
(iii) The elements of a list can be accessed in (f) display()
two ways. The first way is via our familiar
Ans. (a) Constructors
method of multiple assignment, which
(b) Selector

io
unpacks a list into its elements and binds
each element to a different name. at (c) Selector
(d) Constructors
(iii) Example : lst := [10, 20]
(e) Constructors
x, y := lst
ic
(f) Selector
5. What is a Tuple? Give an example.
bl

Ans. (i) A tuple is a comma-separated sequence of 4. What are the different ways to access the
values surrounded with parentheses. Tuple elements of a list. Give example.
Pu

is similar to a list. Ans. (i) The elements of a list can be accessed in


(ii) The difference between the two is that you two ways. The first way is via our familiar
cannot change the elements of a tuple once method of multiple assignment, which
it is assigned whereas in a list, elements can unpacks a list into its elements and binds
ra

be changed. each element to a different name.


(iii) Example : colour= ('red', 'blue', 'Green') lst := [10, 20]
Su

Part - III x, y := lst


(ii) In the above example x will become10 and
Answer the following questions
y will become 20.
 (3 marks) (iii) A second method for accessing the elements
1. Differentiate Concrete datatype and Abstract in a list is by the element selection operator,
datatype. also expressed using square brackets. Unlike
Ans. (i) Concrete datatypes or structures (CDT's)
a list literal, a square-brackets expression
are direct implementations of a relatively directly following another expression does
simple concept. not evaluate to a list value, but instead
selects an element from the value of the
(ii) Abstract Datatypes (ADT's) offer a
preceding expression.
high level view (and use) of a concept
lst[0]
independent of its implementation.
10
(iii) A concrete data type is a data type whose
lst[1]
representation is known and in abstract
data type the representation of a data type 20
is unknown
11
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 2
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


5. Identify Which of the following are List, Tuple
and class ?
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(v) In the above code read distance(), getlat()
and getlon() as functions and read lt
(a) arr [1, 2, 34] as latitude and lg longitude. Read := as
(b) arr (1, 2, 34) “assigned as” or “becomes”
(c) student [rno, name, mark] (vi) lt1, lg1 := getlat(city1), getlon(city1) is read
(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) as lt1 becomes the value of getlat(city1) and
(e) x= [2, 5, 6.5, [5, 6], 8.2] lg1 becomes the value of getlont(city1).
(f) employee [eno, ename, esal, eaddress] (vii) Notice that you don’t need to know how
Ans. (a) List these functions were implemented. You are
(b) Tuple assuming that someone else has defined
(c) Class them for us.
(d) Tuple (viii) It’s okay if the end user doesn’t know how
(e) List functions were implemented. However,
(f) Class the functions still have to be defined by
Part - IV someone.

ns
(ix) Let us identify the constructors and
Answer the following questions
selectors in the above code. As you already

io
 (5 marks) know that Constructors are functions that
at build the abstract data type. In the above
1. How will you facilitate data abstraction. pseudo code the function which creates the
Explain it with suitable example. object of the city is the constructor.
ic
Ans. To facilitate data abstraction, you will need to city = makecity (name, lat, lon)
create two types of functions: constructors and
bl

(x) Here makecity (name, lat, lon) is the


selectors.
Constructors and Selectors : constructor which creates the object
Pu

city.
(i) Constructors are functions that build the
abstract data type. Selectors are functions (name, lat, lon) value passed as parameter
that retrieve information from the data
ra

type.
(ii) For example, say you have an abstract data make city ( )
Su

type called city. This city object will hold the


city’s name, and its latitude and longitude.
To create a city object, you’d use a function city
like
city = makecity (name, lat, lon) lat lon
(iii) To extract the information of a city object,
Constructor
you would use functions like
getname(city) Selectors are nothing but the functions that
getlat(city) retrieve information from the data type.
getlon(city) Therefore in the above code
(iv) The following pseudo code will compute
getname(city)
the distance between two city objects:
getlat(city)
distance(city1, city2):
lt1, lg1 := getlat(city1), getlon(city1) getlon(city)
lt2, lg2 := getlat(city2), getlon(city2) (xi) are the selectors because these functions
return ((lt1 - lt2)**2 + extract the information of the city object.
 (lg1 -lg2)**2))½
12
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

2. What is a List? Why List can be called as Pairs.


Explain with suitable example.
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


3. How will you access the multi-item? Explain
with example.

Data Abstraction
Ans. To enable us to implement the concrete level Ans. (i) The structure construct (In OOP languages
of our data abstraction, Some languages like it's called class construct) is used to
Python provides a compound structure called represent multi-part objects where each
Pair which is made up of list or Tuple. The first part is named (given a name). Consider the
way to implement pairs is with the List construct. following pseudo code:
List : class Person:
(i) List is constructed by placing expressions creation( )
within square brackets separated by
firstName := " "
commas. Such an expression is called a list
literal. List can store multiple values. Each lastName := " "
value can be of any type and can even be id := " "
another list. email := " "
Example for List is [10, 20]. The new data type Person is pictorially
represented as

ns
(ii) The elements of a list can be accessed in
two ways. The first way is via our familiar
Person class name (multi part data representation)
method of multiple assignment, which

io
unpacks a list into its elements and binds
each element to a different name. creation ( )
at function belonging to the new datatype

}
lst := [10, 20]
x, y := lst
ic
first Name
(iii) In the above example x will become10 and
bl

y will become 20. A second method for last Name


accessing the elements in a list is by the datatype
id
Pu

element selection operator, also expressed


using square brackets. email
(iv) Unlike a list literal, a square-brackets
expression directly following another Let main() contains
ra

expression does not evaluate to a list value, p1:=Person() statement creates


but instead selects an element from the the object
Su

value of the preceding expression. firstName := "Padmashri" setting a field called


lst[0] first Name with
10 value Padmashri
lst[1] lastName :="Baskar" setting a field called
20 lastName with
(v) In both the example mentioned above value Baskar
mathematically we can represent list similar id :="994–222–1234" setting a field called
to a set. id value 994–222–
lst[(0, 10), (1, 20)] - where 1234
(o, 10) (1, 20) email="compsci@gamil.com" setting a filed called
email with value
Index position Value Index position Value compsci@gmail.
com
(vi) Any way of bundling two values together
into one can be considered as a pair. Lists - - output of firstName : Padmashri
are a common method to do so. Therefore
List can be called as Pairs.

13
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 2
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


(ii) The class (structure) construct defines the
form for multi-part objects that represent a
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(iv) Here class Person as a cookie cutter, and
p1 as a particular cookie. Using the cookie
person. Its definition adds a new data type, cutter you can make many cookies. Same
in this case a type named Person. way using class created many objects of that
(iii) Once defined, we can create new variables type.
(instances) of the type. In this example (v) A class defines a data abstraction by
Person is referred to as a class or a type, grouping related data items. A class is not
while p1 is referred to as an object or an just data, it has functions defined within it.
instance. We say such functions are subordinate to
the class because their job is to do things
with the data of the class.

additional questions and Answers


Choose the Correct Answer 1 MARK 6. The process of providing only the essentials
and hiding the details is known as

ns
1. Which of the following is a powerful concept
that allows programmers to treat codes as (a) Functions (b) Abstraction
objects? (c) Encapsulation (d) Pairs

io
(a) Encapsulation (b) Data Abstraction  [Ans. (b) Abstraction]
(c) Inheritance (d) Polymorphism
 [Ans. (b) Data Abstraction]
at
7. Which of the following gives an implementation
independent view?
ic
2. Which of the following provides modularity? (a) Abstract
(a) Datatypes (b) Subroutines (b) Concrete
bl

(c) Classes (d) Abstraction (c) Datatype


 [Ans. (b) Objects] (d) Behavior of an object
Pu

3. ADT expansion is  [Ans. (a) Abstract]


(a) Abstract Data Template 8. How many ways to implement an ADT?
(b) Absolute Data Type (a) Only one (b) Two
ra

(c) Abstract Data Type (c) Three (d) Many


(d) Application Development Tool  [Ans. (d) Many]
Su

 [Ans. (c) Abstract Data Type]


9. Which of the following are implemented using
4. Which of the following is a type for objects & lists?
whose behavior is defined by a set of value and (a) Singly linked list ADT
a set of operations?
(a) User-defined datatype (b) Doubly Linked list ADT
(b) Derived datatype (c) Stack ADT
(c) Built-in datatype
(d) Queue ADT
(d) Abstract datatype
(e) All of these [Ans. (e) All of these]
[Ans. (d) Abstract datatype]
10. Which of the following replicate how we think
5. ADT behavior is defined by about the world?
(i) Set of Variables (ii) Set of Value
(a) Queue ADT
(iii) Set of Functions (iv) Set of Operations
(b) Data Hiding
(a) i, ii (b) ii, iii
(c) Data Abstraction
(c) ii, iv (d) i, iii
 [Ans. (c) ii, iv] (d) Stack ADT[Ans. (c) Data Abstraction]

14
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com

 
SCOPING
3
Chapter

www.nammakalvi.org
CHAPTER SNAPSHOT
3.1 Introduction
3.2 Variable Scope
3.3 LEGB rule
3.4 Types of Variable Scope
3.5 Module

Evaluation

ns
Part - I 6. The process of subdividing a computer program

io
Choose the best answer  (1 mark) into separate sub-programs is called
(a) Procedural Programming
1. Which of the following refers to the visibility
of variables in one part of a program to
at
(b) Modular programming
another part of the same program. (c) Event Driven Programming
ic
(a) Scope (b) Memory (d) Object oriented Programming
[Ans. (b) Modular programming]
bl

(c) Address (d) Accessibility


[Ans. (a) Scope] 7. Which of the following security technique that
Pu

regulates who can use resources in a computing


2. The process of binding a variable name with
environment?
an object is called
(a) Password (b) Authentication
(a) Scope (b) Mapping
(c) Access control (d) Certification
ra

(c) late binding (d) early binding


[Ans. (c) Access control]
[Ans. (b) Mapping]
Su

8. Which of the following members of a class can be


3. Which of the following is used in programming
handled only from within the class?
languages to map the variable and object?
(a) Public members
(a) :: (b) := (c) = (d) ==
(b) Protected members
[Ans. (c) =]
(c) Secured members
4. Containers for mapping names of variables to (d) Private members
objects is called [Ans. (a) Public members]
(a) Scope (b) Mapping
(c) Binding (d) Namespaces 9. Which members are accessible from outside the
class?
[Ans. (d) Namespaces]
(a) Public members
5. Which scope refers to variables defined in (b) Protected members
current function? (c) Secured members
(a) Local Scope (b) Global scope (d) Private members
(c) Module scope (d) Function Scope [Ans. (a) Public members]
 [Ans. (a) Local Scope]
[19]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit I - Chapter 3
www.surabooks.com

Sura’s
This material only for sample

➠ XII Std - Computer Science


10. The members that are accessible from within
the class and are also available to its sub-
  www.surabooks.com

www.nammakalvi.org
(iii) Look at this example :
1. Disp(): Entire program Output
classes is called 2. a:=7 of the
(a) Public members 3. print a Disp( ): Program
a:=7
(b) Protected members 4. Disp() print a 7
(c) Secured members Disp ( )
(d) Private members
[Ans. (b) Protected members]
(iv) On execution of the above code the variable
Part - II a displays the value 7, because it is defined
Answer the following questions and available in the local scope.
 (2 marks) 2. Define Global scope with an example.
1. What is a scope? Ans. (i) A variable which is declared outside of all
Ans. Scope refers to the visibility of variables, the functions in a program is known as
parameters and functions in one part of a Global variable.

ns
program to another part of the same program.
(ii) This means, global variable can be accessed
2. Why scope should be used for variable. State inside or outside of all the functions in a

io
the reason. program. Consider the following example
Ans. Scobe should be used for a variable because every at 1. a:=10 Entire program Output
part of the program can access the variable. 2. Disp(): of the
a:=10
3. What is Mapping? 3. a:=7 Disp( ) Program
ic
a:=7
Ans. The process of binding a variable name with an 4. print a print a 7
object is called mapping.= (equal to sign) is used 5. Disp() 10
bl

Disp 1( ):
print a
in programming languages to map the variable 6. print a
and object.
Pu

(iii) On execution of the above code the variable


4. What do you mean by Namespaces? a which is defined inside the function
Ans. Namespaces are containers for mapping names displays the value 7 for the function call
of variables to objects. Disp() and then it displays 10, because a is
ra

5. How Python represents the private and defined in global scope.


protected Access specifiers?
Su

3. Define Enclosed scope with an example.


Ans. Python prescribes a convention of prefixing Ans. (i) All programming languages permit
the name of the variable/method with single or functions to be nested. A function (method)
double underscore to emulate the behaviour of within another function is called nested
protected and private access specifiers. function.
Part - III (ii) A variable which is declared inside a
Answer the following questions function which contains another function
definition with in it, the inner function
 (3 marks) can also access the variable of the outer
1. Define Local scope with an example. function. This scope is called enclosed
scope.
Ans. (i) Local scope refers to variables defined in
current function. Always, a function will (iii) When a compiler or interpreter search for
first look up for a variable name in its local a variable in a program, it first searches
scope. Local, and then searches Enclosing scopes.
Consider the following example
(ii) Only if it does not find it there, the outer
scopes are checked.

20
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com

1. Disp():
2. a:=10
Entire program
Disp( )
This material only for sample

Output
of the
Sura’s

1. Disp():
www.surabooks.com

➠ XII Std - Computer Science


Look at this example
Entire program Output

Scoping
3. Disp1(): a:=10 Program 2. a:=7 of the
Disp 1( ):
4. print a print a 10 3. print a Disp( ): Program
a:=7
5. Disp1() Disp 1( ): 10 4. Disp() print a 7
print a
6. print a Disp( ) Disp ( )
7. Disp()

4. Why access control is required? (ii) On execution of the above code the variable
Ans. (i) Access control is a security technique that a displays the value 7, because it is defined
regulates who or what can view or use and available in the local scope.
resources in a computing environment. Global Scope:
(ii) It is a fundamental concept in security that (i) A variable which is declared outside of all
minimizes risk to the object. the functions in a program is known as
5. Identify the scope of the variables in the global variable.

ns
following pseudo code and write its output
(ii) This means, global variable can be accessed
color:= Red
inside or outside of all the functions in a
mycolor():

io
program. Consider the following example
b:=Blue
1. a:=10 Entire program Output
lue
myfavcolor():
at 2. Disp(): a:=10 of the
3. a:=7 Disp( ) Program
g:=Green
ic
a:=7
4. print a print a 7
printcolor, b, g 10
5. Disp()
bl

Disp 1( ):
myfavcolor() print a
6. print a
printcolor, b
Pu

mycolor() (iii) On execution of the above code the variable


print color 'a' which is defined inside the function
Ans. color : =Red – global scope displays the value 7 for the function call
Disp() and then it displays 10, because a is
ra

b:=Blue – local scope


defined in global scope.
g:=Green – Enclosed scope
Enclosed Scope :
Su

Part - IV (i) All programming languages permit


functions to be nested. A function (method)
Answer the following questions with in another function is called nested
 (5 marks) function.
(ii) A variable which is declared inside a
1. Explain the types of scopes for variable or function which contains another function
LEGB rule with example. definition with in it, the inner function
Ans. Types of Variable Scope : can also access the variable of the outer
There are 4 types of Variable Scope, let's discuss function. This scope is called enclosed
them one by one: scope.
Local Scope : (iii) When a compiler or interpreter search for a
(i) Local scope refers to variables defined in variable in a program, it first search Local,
current function. Always, a function will and then search Enclosing scopes. Consider
first look up for a variable name in its local the following example
scope. Only if it does not find it there, the
outer scopes are checked.

21
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 3
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


1. Disp():
2. a:=10
Entire program Output
of the

 
This material only for sample

Output :

www.surabooks.com

www.nammakalvi.org

outer x variable
Disp( )
Program inner x variable
3. Disp1(): a:=10

4. print a
Disp 1( ):
print a 10 (i) Above statements give different outputs
10 because the same variable name 'x' resides
5. Disp1() Disp 1( ):
print a in different scopes, one inside the function
6. print a Disp( ) display() and the other in the upper level.
7. Disp()
The value ‘outer x variable’ is printed
(iv) In the above example Disp1() is defined when x is referenced outside the function
with in Disp(). The variable ‘a’ defined in definition.
Disp() can be even used by Disp1() because (ii) Whereas when display() gets executed,
it is also a member of Disp(). ‘inner x variable’ is printed which is the
Built-in Scope : x value inside the function definition. From
(i) Finally, we discuss about the widest scope. the above example, we can guess that there
The built-in scope has all the names that are is a rule followed, in order to decide from
pre-loaded into the program scope when which scope a variable has to be picked.

ns
we start the compiler or interpreter. (iii) The LEGB rule is used to decide the order
(ii) Any variable or module which is defined in which the scopes are to be searched

io
in the library functions of a programming for scope resolution. The scopes are listed
language has Built-in or module scope. at below in terms of hierarchy (highest to
They are loaded as soon as the library files lowest).
are imported to the program. Local(L) Defined inside function/
ic
Entire program Library files class
Built in/module scope associated
bl

Enclosed(E) Defined inside enclosing


with the software functions (Nested
Disp( )
Pu

Disp 1( ):
function concept)
print a Global(G) Defined at the uppermost
Disp 1( ): level
print a
Built-in(B) Reserved names in built-
ra

Disp( )
in functions (modules)

Su

LEGB rule :
BUILT-IN
(i) Scope also defines the order in which
variables have to be mapped to the object GLOBAL
in order to obtain the value. ENCLOSED
(ii) Let us take a simple example as shown
LOCAL
below:
1. x:= 'outer x variable'
2. display():
3. x:= 'inner x variable' 2. Write any Five Characteristics of Modules.
4. print x Ans. The following are the desirable characteristics of
5. display() a module.
(iii) When the above statements are executed (i) Modules contain instructions, processing
the statement (4) and (5) display the result logic, and data.
as (ii) Modules can be separately compiled and
stored in a library.

22
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

(iii) Modules can be included in a program.


(iv) Module segments can be used by invoking
Sura’s
(iv) Modular
www.surabooks.com

➠ XII Std - Computer Science


programming allows many
programmers to collaborate on the same
application.
a name and some parameters.

Scoping
(v) Module segments can be used by other (v) The code is stored across multiple files.
modules. (vi) Code is short, simple and easy to
understand.
3. Write any five benefits in using modular
programming. (vii) Errors can easily be identified, as they are
localized to a subroutine or function.
Ans. (i) Less code to be written.
(viii) The same code can be used in many
(ii) A single procedure can be developed for
applications.
reuse, eliminating the need to retype the
code many times. (ix) The scoping of variables can easily be
controlled.
(iii) Programs can be designed more easily
because a small team deals with only a
small part of the entire code.

ns
additional questions and Answers

io
Choose the Correct Answer 1 MARK 5. How the names are mapped with objects in
at programming language?
1. The part of a program that can see or use the (a) name == object (b) name :: object
variables are called (c) name := object (d) object := name
ic
(a) Scope (b) Parameter [Ans. (c) name := object]
bl

(c) Function (d) Indentation


6. The order in which variables have to be
[Ans. (a) Scope] mapped to the object in order to obtain the
Pu

2. Which of the following refers to the addresses value is called


to an object in memory? (a) Rule (b) Syntax
(a) Functions (b) Indentation (c) Scope (d) Hierarchy
ra

(c) Variables (d) Operators  [Ans. (c) Scope]


 [Ans. (b) Indentation] 7. Which of the following rule is used to decide
Su

3. How many variables can be mapped to the the order in which the scopes are to be searched
for scope resolution?
same instance?
(a) LEGB (b) LGEB
(a) 2 (b) 3
(c) LBEG (d) LGBE
(c) 4 (d) Multiple  [Ans. (a) LEGB]
 [Ans. (d) Multiple]
8. Write the below interns of hierarchy (highest
4. Which of the following keeps track of all these to lowest)?
mappings with namespaces? (1) Reversed names in built in functions
(a) Programming languages (2) Defined inside function
(3) Defined inside enclosing function
(b) Application software
(4) Defined at the uppermost level
(c) System software
(a) 3, 2, 1, 4 (b) 1, 4, 2, 3
(d) My SQL (c) 2, 3, 1, 4 (d) 2, 3, 4, 1
 [Ans. (a) Programming languages] [Ans. (d) 2, 3, 4, 1]

23
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 3
www.surabooks.com

Sura’s
This material only for sample

➠ XII Std - Computer Science


Choose the correct statement
  www.surabooks.com

www.nammakalvi.org
4. Write the output of the following program.
Ans.
1. Choose the correct statement from the
following. Entire program Output of
(i) A Program cannot be divided into modules the Program
that work together to get the output. Disp( ):
a:=7
7
print a
(ii) Modules can be separately compiled and
stored in a library. Disp ( )
(iii) Procedure, subroutines and functions are
not examples of modules.
(iv) Modules contain instructions, logic and data 5. Write the output of the following program.
(a) i and ii (b) ii and iii Ans.
(c) iii and iv (d) ii and iv
Entire program Output of
 [Ans. (d) ii and iv] the Program
Choose the incorrect statement a:=10
Disp( ) 7
a:=7

ns
1. Choose the incorrect statement from the print a 10
following. Disp 1( ):
print a
(i) There a different types of variable scope

io
(ii) Enclosed and extended are the type of
variable scope 6. Write the output of the following program.
(iii) A variable is declared outside of all the
at
Ans.
function is called global variable
ic
Entire program Output of
(iv) Built-in Scope is also called Module scope.
the Program
bl

(a) i, iii and iv (b) ii and iii Disp( )


a:=10 10
(c) i and ii (d) iii only Disp 1( ):
10
Pu

print a
 [Ans. (c) i and ii]
Disp 1( ):
print a

Very Short Answers 2 MARKS Disp( )


ra

1. Define variable. 7. What is modular programming?


Ans. Variable are addresses (references, or pointers), Ans. The process of subdividing a computer program
Su

to an object in memory. into separate sub-programs is called modular


programming.
2. What is the use of LEGB rule?
8. What is meant by module?
Ans. The LEGB rule is used to decide the order in
which the scopes are to be searched for scope Ans. A module is a part of a program. Programs
resolution. The scopes are listed below in terms are composed of one or more independently
of hierarchy (highest to lowest). developed modules.

3. Name the types of variable scope.


Short Answers 3 MARKS
Ans. (i) Local scope 1. How the changes inside the function can’t affect
(ii) Enclosed scope the variable on the outside of the function in
unexpected ways?
(iii) Global scope
Ans. (i) Every variable defined in a program has
(iv) Built-in scope.
global scope.

26
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

(ii) Once defined, every part of your program


can access that variable. But it is a good
practice to limit a variable's scope to a
Sura’s
(iv) Modular
www.surabooks.com

➠ XII Std - Computer Science


programming enables
programmers to divide up the work and

Scoping
debug pieces of the program independently.
single definition.
The examples of modules are procedures,
(iii) This way, changes inside the function can't
affect the variable on the outside of the subroutines, and functions.
function in unexpected ways. 4. How will you ensure the principle of
2. Write a note on built-in scope. data encapsulation in object – oriented
Ans. (i) Built-in scope is the widest scope. The programming?
built-in scope has all the names that are Ans. Public members (generally methods declared
pre-loaded into the program scope when
in a class) are accessible from outside the class.
we start the compiler or interpreter.
The object of the same class is required to invoke
(ii) Any variable or module which is defined
in the library functions of a programming a public method. This arrangement of private
language has Built-in or module scope. instance variables and public methods ensures

ns
They are loaded as soon as the library files the principle of data encapsulation.
are imported to the program.
5. Write a note on access modifiers of a class.

io
Entire program Library files
Ans. (i) 
Public members (generally methods
Built in/module scope associated
declared in a class) are accessible from
Disp( )
with the software
at outside the class.
ic
Disp 1( ): (ii) Protected members of a class are accessible
print a
Disp 1( ):
from within the class and are also available
bl

print a to its sub-classes.


Disp( )
(iii) Private members of a class are denied access
Pu

(iii) 
Normally only Functions or modules from outside the class. They can be handled
come along with the software, as packages, only from within the class.
therefore they will come under Built in
ra

scope. 6. Write a short note on types of variable scope.


Ans. (i) 
Public members (generally methods
3. Write a note on module.
Su

declared in a class) are accessible from


Ans. (i) A module is a part of a program. Programs
outside the class.
are composed of one or more independently
(ii) A variable which is declared outside of all
developed modules. A single module can
the functions in a program is known as
contain one or several statements closely
global variable.
related each other.
(iii) 
A variable which is declared inside a
(ii) Modules work perfectly on individual level
function which contains another function
and can be integrated with other modules.
definition with in it, the inner function
A software program can be divided into
can also access the variable of the outer
modules to ease the job of programming
function. This scope is called enclosed
and debugging as well.
scope.
(iii) A program can be divided into small
(iv) Built-in scope the widest scope has all the
functional modules that work together to
names that are pre-loaded into program
get the output. The process of subdividing
scope when we start the compiler or
a computer program into separate sub-
interpreter.
programs is called Modular programming.
27
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com

Chapter
 

4 ALGORITHMIC STRATEGIES
www.nammakalvi.org


CHAPTER SNAPSHOT

ns
4.1 Introduction to Algorithmic strategies
4.2 Complexity of an Algorithm

io
4.2.1 Time Complexity
4.2.2. Space Complexity
at
4.3 Efficiency of an algorithm
ic
4.3.1 Method for determining Efficiency
4.3.2 Space-Time tradeoff
bl

4.3.3 Asymptotic Notations


4.3.4 Best, Worst, and Average ease Efficiency
Pu

4.4 Algorithm for Searching Techniques


4.4.1 Linear Search
4.4.2. Binary Search
ra

4.5 Sorting Techniques


4.5.1 Bubble sort algorithm
Su

4.5.2 Selection sort


4.5.3 Insertion sort
4.6 Dynamic programming
4.6.1 Fibonacci Series – An example
4.6.2 Fibonacci Iterative Algorithm with Dynamic programming approach

[29]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit I - Chapter 4
www.surabooks.com

Sura’s ➠ XII Std - Computer Science

Evaluation
 
This material only for sample www.surabooks.com

www.nammakalvi.org

8. The Θ notation in asymptotic evaluation


Part - I represents
(a) Base case (b) Average case
Choose the best answer  (1 mark)
(c) Worst case (d) NULL case
1. The word comes from the name of a Persian [Ans. (b) Average case]
mathematician Abu Ja’far Mohammed ibn-i
Musa al Khowarizmi is called? 9. If a problem can be broken into subproblems
(a) Flowchart (b) Flow which are reused several times, the problem
(c) Algorithm (d) Syntax possesses which property?
[Ans. (c) Algorithm] (a) Overlapping subproblems
(b) Optimal substructure
2. From the following sorting algorithms which (c) Memoization
algorithm needs the minimum number of
(d) Greedy
swaps?
[Ans. (a) Overlapping subporblems]

ns
(a) Bubble sort (b) Quick sort
10. In dynamic programming, the technique of
(c) Merge sort (d) Selection sort
storing the previously calculated values is

io
[Ans. (d) Selection sort]
called ?
3. Two main measures for the efficiency of an at (a) Saving value property
algorithm are (b) Storing value property
(a) Processor and memory (c) Memoization
ic
(b) Complexity and capacity (d) Mapping [Ans. (c) Memoization]
bl

(c) Time and space (d) Data and space


Part - II
[Ans. (c) Time and space]
Answer the following questions
Pu

4. The complexity of linear search algorithm is


(a) O(n) (b) O(log n)
 (2 marks)
(c) O(n2) (d) O(n log n) 1. What is an Algorithm?
ra

[Ans. (a) O(n)] Ans. An algorithm is a finite set of instructions to


accomplish a particular task. It is a step-by-step
5. From the following sorting algorithms which
Su

procedure for solving a given problem.


has the lowest worst case complexity?
(a) Bubble sort (b) Quick sort 2. Define Pseudo code.
(c) Merge sort (d) Selection sort Ans. (i) Pseudo code is an informal high level
[Ans. (c) Merge sort] description of the operations principle of a
computer program or other algorithm.
6. Which of the following is not a stable sorting
(ii) It uses the structural conventions of a
algorithm?
normal programming language, but is
(a) Insertion sort (b) Selection sort
intended for human reading rather than
(c) Bubble sort (d) Merge sort machine reading.
[Ans. (b) Selection sort]
3. Who is an Algorist?
7. Time complexity of bubble sort in best case is Ans. (i) Algorism is the technique of performing
(a) θ (n) (b) θ (nlogn) basic arithmetic by writing numbers in
(c) θ (n2) (d) θ (n(logn) 2) place value form and applying a set of
[Ans. (a) θ (n)] memorized rules and facts to the digits.
(ii) One who practices algorism is known as an
algorist.

30
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com

4. What is Sorting?
This material only for sample

Sura’s
www.surabooks.com

➠ XII Std - Computer Science


3. What are the factors that influence time and

Algorithmic strategies
Ans. Sorting is any process of arranging information space complexity?
or data in an ordered sequence either in Ans. (i) Time Factor -Time is measured by
ascending or descending order. counting the number of key operations like
5. What is searching? Write its types. comparisons in the sorting algorithm.
Ans. Searching is designed to check for an element (ii) Space Factor - Space is measured by the
or retrieve an element from any data structure maximum memory space required by the
where it is store(d) algorithm.
Types : 4. Write a note on Asymptotic notation.
(i) Linear Search Ans. Asymptotic Notations are languages that uses
(ii) Binary Search. meaningful statements about time and space
Part - III complexity. The following three asymptotic
notations are mostly used to represent time
Answer the following questions complexity of algorithms:
 (3 marks)

ns
(i) Big O : Big O is often used to describe the
worst-case of an algorithm.
1. List the characteristics of an algorithm.
(ii) Big Ω : Big Omega is the reverse Big O, if

io
Ans. (i) Input
Bi O is used to describe the upper bound
(ii) Output (worst - case) of a asymptotic function, Big
(iii) Finiteness
at Omega is used to describe the lower bound
(iv) Definiteness (best-case).
ic
(v) Effectiveness (iii) Big Θ : When an algorithm has a complexity
bl

(vi) Correctness with lower bound = upper bound, say that


(vii) Simplicity an algorithm has a complexity O (n log
Pu

(viii) Unambiguous n) and Ω (n log n), it’s actually has the


(ix) Feasibility complexity Θ (n log n), which means the
(x) Portable running time of that algorithm always falls
(xi) Independent in n log n in the best-case and worst-case.
ra

2. Discuss about Algorithmic complexity and its 5. What do you understand by Dynamic
types. programming?
Su

Ans. The complexity of an algorithm f (n) gives the Ans. (i) Dynamic programming is an algorithmic
running time and/or the storage space required design method that can be used when the
by the algorithm in terms of n as the size of input solution to a problem can be viewed as the
data. result of a sequence of decisions.
(i) Time Complexity : The Time complexity (ii) Dynamic programming approach is similar
of an algorithm is given by the number of to divide and conquer. The given problem
steps taken by the algorithm to complete is divided into smaller and yet smaller
the process. possible sub-problems.
(ii) Space Complexity : Space complexity (iii) Dynamic programming is used whenever
of an algorithm is the amount of memory problems can be divided into similar
required to run to its completion. sub-problems. So that their results can be
re-used to complete the process.

31
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 4
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


(iv) Dynamic programming approaches are
used to find the solution in optimized way.
 
This material only for sample www.surabooks.com

www.nammakalvi.org
2. Discuss about Linear search algorithm.
Ans. (i) Linear search also called sequential search is
For every inner sub problem, dynamic a sequential method for finding a particular
algorithm will try to check the results of value in a list.
the previously solved sub-problems. The
(ii) This method checks the search element with
solutions of overlapped sub-problems are
each element in sequence until the desired
combined in order to get the better solution.
element is found or the list is exhausted. In
this searching algorithm, list need not be
Part - IV ordered.
Answer the following questions Pseudo code :
 (5 marks) (i) Traverse the array using for loop

1. Explain the characteristics of an algorithm. (ii)  In every iteration, compare the target
search key value with the current value of
Ans.
the list.
Input Zero or more quantities to be  If the values match, display the current

ns
supplied. index and value of the array
Output Al least one quantity is produced. If the values do not match, move on to the

io
Finiteness next array element.
Algorithms must terminate after
finites number of steps.
at (iii) If no match is found, display the search
Definiteness element not found.
all operations should be well
defined. For example operations To search the number 25 in the array given
ic
involving division by zero or below, linear search will go step by step in a
sequential order starting from the first element
bl

taking square root for negative


number are unacceptable. in the given array if the search element is found
that index is returned otherwise the search is
Pu

Effectiveness Every instruction must be carried continued till the last index of the array. In this
out effectively. example number 25 is found at index number 3.
Correctness The algorithms should be error index 0 1 2 3 4
free.
ra

Simplicity East to implement. values 10 12 20 25 30


Su

Unambiguous Algorithm should be clear and Example 1 :


unambiguous. Each of its steps Input: values[] = {5, 34, 65, 12, 77, 35}
and their inputs/outputs should target = 77
be clear and must lead to only one Output: 4
meaning.
Example 2:
Feasibility Should be feasible with the Input: values[] = {101, 392, 1, 54, 32, 22, 90, 93}
available resources.
target = 200
Portable An algorithm should be generic, Output: -1 (not found)
independent of any programming
language or an operating system 3. What is Binary search? Discuss with example.
able to handle all range of inputs. Ans. Binary search : Binary search also called half-
Independent An algorithm should have interval search algorithm. It finds the position
step-by-step directions, which of a search element within a sorted array. The
should be independent of any
binary search algorithm can be done as divide-
programming code.
and-conquer search algorithm and executes in
logarithmic time.

32
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


www.surabooks.com

Pseudo code for Binary search :


Start with the middle element:
This material only for sample

Sura’s

www.surabooks.com

➠ XII Std - Computer Science

10 20 30 40 50 60 70 80 90 99

Algorithmic strategies
0 1 2 3 4 5 6 7 8 9
(i) If the search element is equal to the middle
element of the array i.e., the middle value = (vi) Now we change our low to mid + 1 and find
number of elements in array/2, then return the new mid value again using the formula.
the index of the middle element.
low to mid + 1
(ii) If not, then compare the middle element
with the search value, mid = low + (high - low) / 2
(iii) If the search element is greater than the (vii) Our new mid is 7 now. We compare the
number in the middle index, then select value stored at location 7 with our target
the elements to the right side of the middle value 31.
index, and go to Step-1.
(iv)  If the search element is less than the
number in the middle index, then select 10 20 30 40 50 60 70 80 90 99
the elements to the left side of the middle 0 1 2 3 4 5 6 7 8 9
index, and start with Step-1.

ns
(viii) The value stored at location or index 7 is
(v) When a match is found, display success
message with the index of the element not a match with search element, rather it is
matched. more than what we are looking for. So, the

io
(vi) If no match is found for all comparisons, search element must be in the lower part
then display unsuccessful message.
Binary Search Working principles :
at from the current mid value location

(i) List of elements in an array must be sorted 10 20 30 40 50 60 70 80 90 99
ic
first for Binary search. The following 0 1 2 3 4 5 6 7 8 9
bl

example describes the step by step operation (ix) The search element still not found. Hence,
of binary search. we calculated the mid again by using the
Pu

(ii) Consider the following array of elements, formula.


the array is being sorted so it enables to do
the binary search algorithm. Let us assume high = mid -1
that the search element is 60 and we need mid = low + (high - low)/2
ra

to search the location or index of search Now the mid value is 5.


element 60 using binary search.
Su


10 20 30 40 50 60 70 80 90 99 10 20 30 40 50 60 70 80 90 99
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

(iii) First, we find index of middle element of (x) Now we compare the value stored at
the array by using this formula : location 5 with our search element. We
mid = low + (high - low) / 2 found that it is a match.
(iv) Here it is, 0 + (9 - 0 ) / 2 = 4 (fractional part
10 20 30 40 50 60 70 80 90 99
ignored). So, 4 is the mid value of the array.
0 1 2 3 4 5 6 7 8 9

10 20 30 40 50 60 70 80 90 99 (xi) We can conclude that the search element 60


0 1 2 3 4 5 6 7 8 9 is found at location or index 5. For example
(v) Now compare the search element with the if we take the search element as 95, For this
value stored at mid value location 4. The
value this binary search algorithm return
value stored at location or index 4 is 50,
which is not match with search element. As unsuccessful result.
the search value 60 is greater than 50.
33
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 4
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


4. Explain the Bubble sort algorithm with
example.
 
This material only for sample

(v) The
www.surabooks.com

www.nammakalvi.org
above pictorial example is for
iteration–1. Similarly, remaining iteration
Ans. Bubble sort algorithm: can be done. The final iteration will give the
(i) Bubble sort is a simple sorting algorithm. sorted array. At the end of all the iterations
The algorithm starts at the beginning of the we will get the sorted values in an array as
list of values stored in an array. It compares given below :
each pair of adjacent elements and swaps 11 12 13 14 15 16
them if they are in the unsorted order.
(ii) This comparison and passed to be continued 5. Explain the concept of Dynamic programming
until no swaps are needed, which indicates with suitable example.
that the list of values stored in an array is
(i) Dynamic programming is an algorithmic
sorted. The algorithm is a comparison sort,
is named for the way smaller elements design method that can be used when the
"bubble" to the top of the list. solution to a problem can be viewed as the
(iii) Although the algorithm is simple, it is too result of a sequence of decisions.
slow and less efficient when compared to (ii) Dynamic programming approach is similar

ns
insertion sort and other sorting methods. to divide and conquer. The given problem
(iv) Assume list is an array of n elements. The is divided into smaller and yet smaller
swap function swaps the values of the given

io
possible sub-problems.
array elements.
(iii) Dynamic programming is used whenever
Pseudo code :
(i) Start with the first element i.e., index = 0,
at problems can be divided into similar sub-
compare the current element with the next problems. so that their results can be re-
ic
element of the array. used to complete the process.
(ii) If the current element is greater than the (iv) Dynamic programming approaches are
bl

next element of the array, swap them. used to find the solution in optimized way.
Pu

(iii) If the current element is less than the next For every inner sub problem, dynamic
or right side of the element, move to the algorithm will try to check the results of the
next element. Go to Step 1 and repeat until previously solved sub-problems.
end of the index is reached. (v) The solutions of overlapped sub-problems
ra

(iv) Let's consider an array with values {15, 11, are combined in order to get the better
16, 12, 14, 13} Below, we have a pictorial solution.
Su

representation of how bubble sort will sort Steps to do Dynamic programming :


the given array.
(i)  The given problem will be divided into
15>11
15 11 16 12 14 13 smaller overlapping sub-problems.
So interchange
(ii) An optimum solution for the given problem
15>16
15 11 16 12 14 13 can be achieved by using result of smaller
No swapping
sub-problem.
(iii) Dynamic algorithms uses Memoization.
16>12
11 15 16 12 14 13
So interchange Fibonacci Series – An example :
(i) Fibonacci series generates the subsequent
16>14 11 15 12 16 14 13 number by adding two previous numbers.
So interchange
Fibonacci series starts from two numbers −
16>13 Fib 0 & Fib 1. The initial values of Fib 0 &
11 15 12 14 16 13
So interchange Fib 1 can be taken as 0 and 1.

11 15 12 14 13 16

34
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

(ii) Fibonacci series satisfies the following


conditions :
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


step-1: Print the initial values of Fibonacci f0
and f1

Algorithmic strategies
Fibn = Fibn-1 + Fibn-2 step-2: Calculate fibanocci fib ← f0 + f1
(iii) Hence, a Fibonacci series for the n value 8 step-3: Assign f0← f1, f1← fib
can look like this step-4: Print the next consecutive value of
Fib8 = 0 1 1 2 3 5 8 13 fibanocci fib
Fibonacci Iterative Algorithm with Dynamic step-5: Goto step-2 and repeat until the specified
programming approach : The following exam- number of terms generated
ple shows a simple Dynamic programming For example if we generate fibobnacci series
approach for the generation of Fibonacci series. upto 10 digits, the algorithm will generate the
Initialize f0=0, f1 =1 series as shown below:
The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55.

additional questions and Answers


Choose the Correct Answer 1 MARK 6. Which of the following is not a type of

ns
searching technique?
1. Which of the following is a finite set of (i) Linear (ii) Binary

io
instructions to accomplish a particular task? (iii) Selection (iv) Merge
(a) Flowchart (b) Functions at (a) Only i (b) Only ii
(c) Algorithm (d) Abstraction (c) Only iii (d) iii and iv
 [Ans. (c) Algorithm] [Ans. (d) iii and iv]
ic
2. Which of the following are the characteristics 7. Which of the following is not a sorting
bl

of an algorithm? technique?
(i) Definiteness (a) Bubble (b) Binary
Pu

(ii) Correctness (c) Insertion (d) Quick


(iii) Effectiveness  [Ans. (b) Binary]
(a) i, ii (b) ii, iii
8. The way of defining an algorithm is called
ra

(c) Only ii (d) i, ii and iii


(a) Pseudo strategy
[Ans. (d) i, ii and iii]
(b) Programmic strategy
Su

3. Which of the following is not a characteristic (c) Algorithmic strategy


of an algorithm? (d) Data structured strategy
(a) Definiteness (b) Correctness  [Ans. (c) Algorithmic strategy]
(c) Data structure (d) Effectiveness
9. Which characteristics of algorithm defined the
 [Ans. (c) Data structure]
operation involving division by zero?
4. Which of the following is not an example of (a) Finiteness (b) Definiteness
data structures?
(c) Input (d) Correctness
(a) Control statement (b) Structure
(c) List (d) Dictionary  [Ans. (b) Definiteness]
 [Ans. (a) Control statement] 10. Which characteristics of an algorithm should
5. Which of the following is an example of data be generic, independent of any programming
structures? language?
(a) List (b) Tuple (a) Independent (b) Portable
(c) Dictionary (d) All of these. (c) Feasibility (d) Unambiguous
 [Ans. (d) All of these]
[Ans. (b) Portable]

35
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 4
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


3. Choose the incorrect pair from the following
(a) Big O – Worst case
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(ii) The running time of an operation is
calculated as how many programming
(b) Big Ω - First case instructions is executed per operation.
(c) Big µ - Best case 6. What is algorithm analysis?
(d) Big α - Average case Ans. An estimation of the time and space complexities
 [Ans. (b) Big Ω - First case] of an algorithm for varying input sizes is called
algorithm analysis.
4. Choose the incorrect statement from the
7. How the analysis of algorithms and
following.
performance evaluation can be divided?
(i) In Algorithm, All operations in should be Explain.
well defined
Ans. Analysis of algorithms and performance
(ii) Algorithms must not terminate after finite evaluation can be divided into two different
number of steps.
phases:
(iii) In algorithms, errors are acceptable
(i) A Priori estimates : This is a theoretical
(iv) An algorithm should have step-by-step performance analysis of an algorithm.

ns
directions.
Efficiency of an algorithm is measured by
(a) i and ii (b) i, iii and iv assuming the external factors.

io
(c) ii and iii (d) iii only
(ii) A Posteriori testing : This is called
 [Ans. (c) ii and iii] at performance measurement. In this analysis,
actual statistics like running time and
Very Short Answers 2 MARKS required for the algorithm executions are
ic
collected.
1. Give an example of data structures.
bl

Ans. Examples for data structures are arrays, 8. Name the two factors, which decide the
structures, list, tuples, dictionary. efficiency of an algorithm.
Pu

Ans. (i) Time factor


2. What in algorithmic strategy? Give an
example. (ii) Space factor
Ans. (i) The way of defining an algorithm is called 9. Give an example. How the time efficiency of an
ra

algorithmic strategy. algorithm is measured.


(ii) For example to calculate factorial for Ans. The time efficiency of an algorithm is measured
Su

the given value n then it can be done by by different factors. For example, write a program
defining the function to calculate factorial for a defined algorithm, execute it by using any
once for the iteration-1 then it can be called programming language, and measure the total
recursively until the number of required time it takes to run.
iteration is reached. 10. What is algorithmetic strategy?
3. What is algorithmic solution? Ans. A way of designing algorithm is called algorithmic
Ans. An algorithm that yields expected output for a strategy.
valid input is called an algorithmic solution. 11. What is best algorithm?
4. How the efficiency of an algorithm is defined? Ans. The best algorithm to solve a given problem is
Ans. Efficiency of an algorithm is defined by the one that requires less space in memory and takes
utilization of time and space complexity. less time to execute its instructions to generate
output.
5. What does analysis of an algorithm deals with?
Ans. (i) Analysis of an algorithm usually deals with 12. What are asymptotic notations?
the running and execution time of various Ans. Asymptotic Notations are languages that uses
operations involved. meaningful statements about time and space
complexity.

40
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

13. What are the three asymptotic notations used


to represent time complexity of algorithms?
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


3. Write a note on time/space trade off.

Algorithmic strategies
Ans. (i) A space-time or time-memory trade off
Ans. (i) Big O is a way of solving in less time by using
(ii) Big W more storage space or by solving a given
(iii) Big μ
algorithm in very little space by spending
more time.
14. Write a note on Big omega asymptotic (ii) To solve a given programming problem,
notation. many different algorithms may be used.
Ans. Big Omega is the reverse Big O, if Big O is used Some of these algorithms may be extremely
to describe the upper bound (worst - case) of time-efficient and others extremely space-
a asymptotic function, Big Omega is used to efficient.
describe the lower bound (best-case). (iii) Time/space trade off refers to a situation
15. Write a note on memorization. where you can reduce the use of memory
Ans. Memoization or memoisation is an optimization at the cost of slower program execution,
technique used primarily to speed up computer or reduce the running time at the cost of

ns
programs by storing the results of expensive increased memory usage.
function calls and returning the cached result 4. Write a note on two factors in which space
when the same inputs occur again.

io
required by an algorithm is decided.
Short Answers 3 MARKS Ans. The space required by an algorithm is equal to
at the sum of the following two components:
1. List the manipulation manipulated effectively
(i) A fixed part is defined as the total
through data structures by algorithm.
ic
space required to store certain data and
Ans. variables for an algorithm. For example,
bl

Search To search an item in a data simple variables and constants used in an


structure using linear and binary algorithm.
Pu

search. (ii) A variable part is defined as the total


Sort To sort items in a certain order space required by variables, which sizes
using the methods such as bubble depends on the problem and its iteration.
ra

sort, insertion sort, selection sort, For example: recursion used to calculate
etc. factorial of a given value n.
Insert
Su

To insert an item (s) in a data 5. Write the different factors in which the time
structure. efficiency of an algorithm its measured.
Update To updata an existing item (s) in a Ans. The execution time that you measure in this case
data structure. would depend on a number of factors such as:
Delete To delete an existing item (s) in a (i) Speed of the machine
data structure. (ii) Compiler and other system Software tools
2. Design an algorithm to find square of the (iii) Operating System
given number and display the result. (iv) Programming language used
Ans. The algorithm can be written as: (v) Volume of data required
Step 1 – start the process 6. Write a pseudo code for linear search.
Step 2 – get the input x
Ans. (i) Traverse the array using 'for loop'
Step 3 – calculate the square by multiplying the
(ii) In every iteration, compare the target
input value ie., square ← x* x
search key value with the current value of
Step 4 − display the result square the list.
Step 5 − stop
(iii) 
If the values match, display the current
index and value of the array
41
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 4
www.surabooks.com

Sura’s
This material only for sample

➠ XII Std - Computer Science


(iv) If the values do not match, move on to the
next array element.
  www.surabooks.com

www.nammakalvi.org
10. Write a pseudo code for Insertion sort.
Ans. Step 1 − If it is the first element, it is already
(v) If no match is found, display the search
sorted.
element not found.
Step 2 − Pick next element
7. Write a pseudo code for Binary search. Step 3 − Compare with all elements in the sorted
Ans. Start with the middle element: sub-list
(i) If the search element is equal to the middle Step 4 − Shift all the elements in the sorted
element of the array i.e., the middle value = sub-list that is greater than the value to
number of elements in array/2, then return be sorted
the index of the middle element. Step 5 − Insert the value
(ii) If not, then compare the middle element Step 6 − Repeat until list is sorted.
with the search value,
11. Write the steps to do dynamic programming.
(iii) If the search element is greater than the
Ans. (i)  The given problem will be divided into
number in the middle index, then select
smaller overlapping sub-problems.
the elements to the right side of the middle

ns
index, and go to Step-1. (ii) An optimum solution for the given problem
(iv)  If the search element is less than the can be achieved by using result of smaller
number in the middle index, then select sub-problem.

io
the elements to the left side of the middle (iii) Dynamic algorithms uses Memoization.
index, and start with Step-1. at
(v) When a match is found, display success 12. Write a pseudo code that defines Fibonacci
message with the index of the element Iterative algorithm with Dynamic
ic
matched. programming approach.
(vi) If no match is found for all comparisons, Ans. The following shows a simple Dynamic
bl

then display unsuccessful message. programming approach for the generation of


8. Write a pseudo code for bubble sort. Fibonacci series.
Pu

Ans. (i) Start with the first element i.e., index = 0, Initialize f0=0, f1 =1
compare the current element with the next Step 1 - Print the initial values of Fibonacci f0
element of the array. and f1
ra

(ii) If the current element is greater than the Step 2 - Calculate fibanocci fib ← f0 + f1
next element of the array, swap them. Step 3 - Assign f0← f1, f1← fib
Su

(iii) If the current element is less than the next Step 4 - Print the next consecutive value of
or right side of the element, move to the fibanocci fib
next element. Go to Step 1 and repeat until step 5 - Goto step-2 and repeat until the specified
end of the index is reached. number of terms generated
9. Write a pseudo code for selection sort. For example if we generate fibobnacci series
upto 10 digits, the algorithm will generate the
Ans. (i) Start from the first element i.e., index-0,
series as shown below:
we search the smallest element in the array,
The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55
and replace it with the element in the first
position. Long Answers 5 MARKS
(ii) Now we move on to the second element
position, and look for smallest element 1. Explain Best, worst and Average case efficiency
present in the sub-array, from starting of an algorithm with an example.
index to till the last index of sub - array. Ans. (i) Let us assume a list of n number of values
(iii) Now replace the second smallest identified stored in an array. Suppose if we want to
in step-2 at the second position in the or search a particular element in this list, the
original array, or also called first position in algorithm that search the key element in
the sub array.
42
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

the list among n elements, by comparing


the key element with each element in the
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


required by an algorithm is equal to the

Algorithmic strategies
sum of the following two components:
list sequentially. ■ A fixed part is defined as the total
(ii) The best case would be if the first element in space required to store certain data and
the list matches with the key element to be variables for an algorithm. For example,
searched in a list of elements. The efficiency simple variables and constants used in an
in that case would be expressed as O(1) algorithm.
because only one comparison is enough. ■ A variable part is defined as the total
(iii) Similarly, the worst case in this scenario space required by variables, which sizes
would be if the complete list is searched and depends on the problem and its iteration.
the element is found only at the end of the For example: recursion used to calculate
list or is not found in the list. The efficiency factorial of a given value n.
of an algorithm in that case would be 3. Write a note on Efficiency of an algorithm.
expressed as O(n) because n comparisons
required to complete the search. Ans. (i) Computer resources are limited that should
be utilized efficiently. The efficiency of

ns
(iv) The average case efficiency of an algorithm
an algorithm is defined as the number
can be obtained by finding the average
number of comparisons as given below: of computational resources used by the
algorithm.

io
Minimum number of comparisons = 1
Maximum number of comparisons = n at (ii) An algorithm must be analyzed to
If the element not found then determine its resource usage. The efficiency
maximum number of comparison = n of an algorithm can be measured based on
ic
Therefore, average number the usage of different resources.
of comparisons = (n + 1)/2 (iii) For maximum efficiency of algorithm
bl

(v) Hence the average case efficiency will be we wish to minimize resource usage. The
expressed as O (n). important resources such as time and space
Pu

2. Explain complexity of an algorithm. complexity cannot be compared directly,


Ans. Suppose A is an algorithm and n is the size so time and space complexity could be
of input data, the time and space used by the considered for an algorithmic efficiency.
ra

algorithm A are the two main factors, which


Method for determining Efficiency :
decide the efficiency of A.
Su

(i) Time Factor : Time is measured by (i) The efficiency of an algorithm depends on
counting the number of key operations like how efficiently it uses time and memory
comparisons in the sorting algorithm. space.
(ii) Space Factor : Space is measured by the (ii) The time efficiency of an algorithm is
maximum memory space required by the measured by different factors. For example,
algorithm. The complexity of an algorithm write a program for a defined algorithm,
f (n) gives the running time and/or the execute it by using any programming
storage space required by the algorithm in language, and measure the total time it
terms of n as the size of input data. takes to run.
(iii) Time Complexity : The Time complexity (iii) The execution time that you measure in this
of an algorithm is given by the number of case would depend on a number of factors
steps taken by the algorithm to complete such as:
the process. ■ Speed of the machine
(iv) Space Complexity : Space complexity of ■ Compiler and other system Software
an algorithm is the amount of memory tools
required to run to its completion. The space ■ Operating System

43
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 4
www.surabooks.com

Sura’s




This material only for sample

➠ XII Std - Computer Science


Programming language used
Volume of data required
  www.surabooks.com

www.nammakalvi.org
(iii) This algorithm repeatedly selects the next-
smallest element and swaps in into the
right place for every pass. Hence it is called
(iv) However, to determine how efficiently
selection sort.
an algorithm solves a given problem, you
would like to determine how the execution Pseudo code :
time is affected by the nature of the (i) Start from the first element i.e., index-0,
algorithm. we search the smallest element in the array,
(v) Therefore, we need to develop fundamental and replace it with the element in the first
laws that determine the efficiency of a position.
program in terms of the nature of the (ii) Now we move on to the second element
underlying algorithm. position, and look for smallest element
present in the sub-array, from starting
4. Differentiate Algorithm and program. index to till the last index of sub - array.
Ans.
(iii) Now replace the second smallest identified
Algorithm Program in step-2 at the second position in the or

ns
original array, or also called first position in
Algorithm helps to Program is an expression
the sub array.
solve a given problem of algorithm in a
(iv) This is repeated, until the array is completely

io
logically and it can be programming language.
contrasted with the at sorted.
program (v) Let's consider an array with values {13, 16,
Algorithm can be Algorithm can be 11, 18, 14, 15}
ic
categorized based on implemented by (vi) Below, we have a pictorial representation of
their implementation structured or object how selection sort will sort the given array.
bl

methods, design oriented programming 6. Explain the sorting algorithm that uses n-1
techniques etc approach number passes to get the final sorted list.
Pu

There is no specific Program should be written


Ans. (i) Insertion sort is a simple sorting algorithm.
rules for algorithm for the selected language
It works by taking elements from the list
writing but some with specific syntax
one by one and inserting then in their
ra

guidelines should be
correct position in to a new sorted list.
followed.
(ii) This algorithm builds the final sorted array
Su

Algorithm resembles Program is more specific at the end. This algorithm uses n-1 number
a pseudo code which to a programming of passes to get the final sorted list as per the
can be implemented language pervious algorithm as we have discussed.
in any language
Pseudo for Insertion sort :
5. Explain Selection sort sorting algorithm. Step 1 − If it is the first element, it is already
Ans. (i) The selection sort is a simple sorting sorted.
algorithm that improves on the performance Step 2 − Pick next element
of bubble sort by making only one exchange Step 3 − Compare with all elements in the sorted
for every pass through the list. sub-list
(ii) This algorithm will first find the smallest Step 4 − Shift all the elements in the sorted sub-
elements in array and swap it with the list that is greater than the value to be
element in the first position of an array, sorted
then it will find the second smallest element Step 5 − Insert the value
and swap that element with the element in Step 6 − Repeat until list is sorted
the second position, and it will continue
until the entire array is sorted in respective
order. www.nammakalvi.org

44
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

S-ar putea să vă placă și