Documente Academic
Documente Profesional
Documente Cultură
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]
Evaluation
This material only for sample www.surabooks.com
www.nammakalvi.org
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
2
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com This material only for sample
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
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
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
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
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
++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
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
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
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.1 List
2.5.2 Tuple
2.6 Data Abstraction in Structure
ra
Su
[9]
Evaluation
This material only for sample www.surabooks.com
www.nammakalvi.org
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
10
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com
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
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
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
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
13
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 2
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.
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
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
Sura’s
This material only for sample
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
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
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
21
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 3
www.surabooks.com
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
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
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
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
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
print a
[Ans. (c) i and ii]
Disp 1( ):
print a
26
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com This material only for sample
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
(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
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
[29]
Evaluation
This material only for sample www.surabooks.com
www.nammakalvi.org
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
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
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
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
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
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
32
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com
Sura’s
www.surabooks.com
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
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
(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
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
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.
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
35
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit I - Chapter 4
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
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
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
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
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
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
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
(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
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
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