0% found this document useful (0 votes)
8 views

XII CS Chapter 1 TO 4 - NOTES

The document is a study guide for a Computer Science course, covering topics such as functions, data abstractions, and algorithmic strategies. It includes multiple-choice questions, short answer questions, and explanations of concepts like pure and impure functions, interfaces, and implementation. The guide aims to help students understand key programming concepts and their applications.

Uploaded by

vhemavaradan7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

XII CS Chapter 1 TO 4 - NOTES

The document is a study guide for a Computer Science course, covering topics such as functions, data abstractions, and algorithmic strategies. It includes multiple-choice questions, short answer questions, and explanations of concepts like pure and impure functions, interfaces, and implementation. The guide aims to help students understand key programming concepts and their applications.

Uploaded by

vhemavaradan7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

AMALORPAVAM

HIGHE
IGHER SECONDARY SCHOOL
PUDUCHERRY

XII – COMPUTER SCIENCE

1 • FUNCTION

2 • DATA ABSTRACTIONS

3 • SCOPING

4 • ALGORITHMIC STRATEGIES
CHAPTER – 1 FUNCTION
Part - I
Choose the best answer (1 Mark)
1. The small sections of code that are used to perform a particular task is called
called
(a) Subroutines (b) Files (c) Pseudo code (d) Modules
2. Which of the following is a unit of code that is often defined within a greater code structure?
(a) Subroutines (b) Function (c) Files (d) Modules
3. Which of the following is a distinct
nct syntactic block?
(a) Subroutines (b) Function (c) Definition (d) Modules
4. The variables in a function definition are called as
(a) Subroutines (b) Function (c) Definition (d) Parameters
5. The values which are passed to a function definition are called
(a) Arguments (b) Subroutines (c) Function (d) Definition
6. Which of the following are mandatory to write the type annotations in the function definition?
(a) Curly braces (b) Parentheses (c) Square brackets (d) indentations
7. Which of thee following defines what an object can do?
(a) Operating System (b) Compiler (c) Interface (d) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(a) Operating System (b) Compiler (c) Implementation (d) Interpreter
In
9. The functions which will give exact result when same arguments are passed are called
(a) Impure functions (b) Partial Functions (c) Dynamic Functions (d)Pure functions
10. The functions which cause side effects to the arguments passed are called
(a) impure function (b) Partial Functions (c) Dynamic Functions (d) Pure functions
Part - II
Answer the following questions (2 Marks)
1. What is a subroutine?
Subroutines are small sections of code that are used to perform a particular task that can be used
repeatedly.
2. Define Function with respect to Programming language.
 A function is a unit of code that is often defined within a greater code structure.
 Specifically, a function contains a set of code that works on many kinds of inputs, like variants,
variant
expressions and produces a concrete output.
3. Write the inference you get from X:=(78).
 X:= (78) has an expression in it but (78) is not itself an expression. Rather, it is a function definition.
 Definitions bind values to names, in this case the value 7878 being bound to the name ‘X’.
4. Differentiate interface and implementation.
Interface Implementation

Interface just defines what an object can do, but Implementation carries out the instructions
won’t actually do it defined in the interface.

5. Which of the
he following is a normal function definition and which is recursive function
definition?
i) let rec sum x y:
return x + y
ii) let disp :
print ‘welcome’
iii) let rec sum num:
if (num!=0) then
return num + sum(num-1)
sum(num
else
return num
Ans: i) Recursive function ii) Normal function iii)Recursive function
Part - III
Answer the following questions (3 Marks)
1. Mention the characteristics of Interface.
 The class template specifies the interfaces to enable an object to be created and operated properly.
 An object's attributes and behaviour is controlled by sending functions to the object.

2. Why strlen is called pure function?


 strlen is a pure function because the function takes one variable as a parameter, and accesses it
to find its length.
 This function reads external memory but does not change it, and the value returned derives
from the external memory accessed.
 strlen (s) is called each time and strlen needs to iterate over the whole of ‘s’.
 If the compiler is smart enough to work out that strlen is a pure function and that ‘s’ is not
updated in the loop, then it can remove the redundant extra calls to strlen and make the loop to
execute only one time.
3. What is the side effect of impure function? Give example.
 Function has side effects when it has observable interaction with the outside world.
 There are situations our functions can become impure though our goal is to make our functions
pure.
For example
let y: = 0
(int) inc (int) x
y: = y + x;
return (y)

 In the above example the value of y get changed inside the function definition due to which the
result will change each time.
 The side effect of the inc () function is it is changing the data of the external visible variable
‘y’.
4. Differentiate pure and impure function.

Pure Function Impure Function

The return value of the pure functions solely The return value of the impure functions does
depends on its arguments passed. not solely depend on its arguments passed.

Hence, if you call the pure functions with the Hence, if you call the impure functions with
same set of arguments, you will always get the the same set of arguments, you might get the
same return values. different return values For example, random(),
Date().

They do not have any side effects. They have side effects.

They do not modify the arguments which are They may modify the arguments which are
passed to them passed to them

5. What happens if you modify a variable outside the function? Give an example.
One of the most popular groups of side effects is modifying the variable outside of
function.
For example
let y: = 0
(int) inc (int) x
y: = y + x;
return (y)
 In the above example the value of y get changed inside the function definition due to which the
result will change each time.
 The side effect of the inc () function is it is changing the data of the external visible variable ‘y’.
Part - IV
Answer the following questions (5Marks)
1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type
Parameters are the variables in a function definition and arguments are the values which are passed to
a function definition.
1. Parameter without Type:
Let us see an example of a function definition:
(requires: b>=0 )
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else a * pow a (b-1)
 In the above function definition variable ‘b’ is the parameter and the value which is passed to the
variable ‘b’ is the argument.
 The precondition (requires) and postcondition (returns) of the function is given. Note we have
not mentioned any types: (data types).
 Some language compiler solves this type (data type) inference problem algorithmically.
 In the above function definition if expression can return 1 in the then branch, by the typing rule
the entire if expression has type int.
 Since the if expression has type ‘int’, the function's return type also be ‘int’. ‘b’ is compared to 0
with the equality operator, so ‘b’ is also a type of ‘int’.
 Since ‘a’ is multiplied with another expression using the * operator, ‘a’ must be an int.
2. Parameter with Type:
 Now let us write the same function definition with types for some reason:
(requires: b>0 )
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int :=
if b=0 then 1
else a * pow a (b-1)
 When we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory.
 There are times we may want to explicitly write down types.
 This is useful on times when you get a type error from the compiler that doesn't make sense.
 Explicitly annotating the types can help with debugging such an error message.
2. Identify in the following program :
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function - gcd
ii) Identify the statement which tells it is a recursive function - rec
iii) Name of the argument variable - a,b
iv) Statement which invoke the function recursively – gcd b (a mod b)
v) Statement which terminates the recursion – 0
return a
3. Explain with example Pure and impure functions.
Pure functions
 Pure functions are functions which will give exact result when the same arguments are
passed.
 For example the mathematical function sin(0) always results 0.
 This means that every time you call the function with the same arguments, you will always get
the same result.
 Let us see an example
let square x
return: x * x
 The above function square is a pure function because it will not give different results for same
input.
 One advantage of pure function is that if a function is pure, then if it is called several times with
the same arguments, the compiler only needs to actually call the function once.
Impure functions :
 The variables used inside the function may cause side effects though the functions which are
not passed with any arguments.
 In such cases the function is called impure function.
 When a function depends on variables or functions outside of its definition block, you can
never be sure that the function will behave the same every time it’s called.
 For example the mathematical function random() will give different outputs for the same
function call.
let Randomnumber
let a := random()
if a > 10 then
return: a
else
return: 10
 Here the function Random is impure as it is not sure what will be the result when we call the
function.
4. Explain with an example interface and implementation.
Interface:
 An interface is a set of action that an object can do.
 For example when you press a light switch, the light goes on, you may not have cared how it
splashed the light.
 In Object Oriented Programming language, an Interface is a description of all functions that a
class must have.
 In our example, anything that "ACTS LIKE" a light, should have function definitions like turn_on
() and a turn_off ().
 The purpose of interfaces is to allow the computer to enforce the properties of the class of TYPE
T (whatever the interface is) must have functions called X, Y, Z, etc.
 The interface defines an object’s visibility to the outside world.
 Interface just defines what an object can do, but won’t actually do it.
 In object oriented programs classes are the interface.
Implementation:
 Implementation carries out the instructions defined in the interface.
 How the object is processed and executed is the implementation.
CHAPTER – 2 DATA ABSTRACTION
Part - I
Choose the best answer (1 Mark)
1. Which of the following functions that build the abstract data type ?
(a) Constructors (b) Destructors (c) recursive (d)Nested
2. Which of the following functions that retrieve information from the
the data type?
(a)Constructors (b) Selectors (c) recursive (d)Nested
3. The data structure which is a mutable ordered sequence of elements is called
(a)Built in (b) List (c) Tuple (d) Derived data
4. A sequence of immutable objects is called
(a)Built in (b) List (c) Tuple (d) Derived data
5. The data type whose representation is known are called
(a)Built in datatype (b) Derived datatype (c)Concrete datatype (d) Abstract datatype
6. The data type whose representation is unknown are called
(a)Built in datatype (b) Derived datatype (c)Concrete datatype (d) Abstract datatype
7. Which of the following is a compound structure?
(a)Pair (b) Triplet (c) single (d) quadrat
8. Bundling two values together into one can be considered as
(a)Pair (b) Triplet
riplet (c) single (d) quadrat
9. Which of the following allow to name the various parts of a multi-item
multi item object?
(a)Tuples (b) Lists (c) Classes (d) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(a)Tuples (b) Lists (c) Classes (d) quadrats
Part - II
Answer the following questions (2 Marks)
1. What is abstract data type?
 Abstract Data type (ADT) is a type (orclass) for objects whose behavior is definedby a set of value
and a set of operations.
 Abstraction provides modularity(modularity means splitting a program into many modules).
2. Differentiate constructors and selectors.
Constructors Selectors
Constructors are functions that build the Selectors are functions that retrieve
retriev information
abstract data type. from the data type.
city = makecity (name, lat, lon)  getname(city)
 getlat(city)
Here, makecity (name, lat, lon) is the
 getlon(city)are the selectors
constructor which creates the object city.

3. What is a Pair? Give an example.


 Any way of bundling
ndling two values together into one can be considered as a pair.
 E.g. lst := [10, 20]
4. What is a List? Give an example.
 List is constructed by placing
placin expressions within square brackets separated by commas.
commas
 E.g. lst := [10, 20]
5. What is a Tuple? Give an example.
mple.
 A tuple is a comma-separatedsequence
separatedsequence of values surrounded withparentheses.
 Example colour= ('red', 'blue', 'Green')
Part - III
Answer the following questions (3 Marks)
1. Differentiate Concrete data type and abstract datatype.
Concrete data type Abstract data type
A concrete data type is a data type whose In abstract datatype the representation of a data type
representation is known. is unknown.
A concrete data type representation is defined. The basic idea of data abstraction is to structure
programs so that they operateon abstract data.
A concrete data representation is defined as an Our programs should use data in such a way, as to
independent part of the program. make as few assumptions about the data as possible.

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


 We are using here a powerful strategy for designing programs: 'Wishful thinking'.
 Wishful Thinking is the formation of beliefs and making decisions according to what might be
pleasing to imagine instead of by appealing to reality.
3. Identify Which of the following are constructors and selectors?
(a) N1=number() - Constructor (b) accetnum(n1) – Selector
(c) displaynum(n1) - Selector (d) eval(a/b) - Selector
(e) x,y= makeslope (m), makeslope(n) - Constructor
(f) display() - Selector
4. What are the different ways to access the elements of a list. Give example.
 List is constructed by placing expressions within square brackets separated by commas.
 The elements of a list can be accessed in two ways.
 The first way is via our familiar method of multiple assignment, which unpacks a list into its
elements and binds each element to a different name.
lst := [10, 20]
x, y := lst
 In the above example x will become10 and y will become 20.
 A second method for accessing the elements in a list is by the element selection operator, also
expressed using square brackets.
 Unlike a list literal, a square brackets expression directly following another expression does not
evaluate to a list value, but instead selects an element from the value of the preceding
expression.
lst[0]
10
lst[1]
20
5. Identify Which of the following are List, Tuple and class ?
(a) arr [1, 2, 34] - List (b) arr (1, 2, 34) -Tuple
(c) student [rno, name, mark] - Class (d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) -Tuple
(e) x= [2, 5, 6.5, [5, 6], 8.2] - List (f) employee [eno, ename, esal, eaddress] - Class
Part - IV
Answer the following questions (5Marks)
1. How will you facilitate data abstraction. Explain it with suitable example
 To facilitate data abstraction, you will need to create two types of functions: constructors and
selectors.
 Constructors are functions that build the abstract data type.
 For example, say you have an abstractdata 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 like
city = makecity (name, lat, lon)
 To extract the information of a city object, you would use functions like
• getname(city)
• getlat(city)
• getlon(city)
 The function whichch creates the object of the city is the constructor.
 city = makecity (name, lat, lon)
 Here makecity (name, lat, lon) is the constructor which creates the object city.

 Selectors are nothing but thefunctions that retrieve information from the data type.
• getname(city)
• getlat(city)
• getlon(city)
are the selectors because these functions extract the information of the city object

2. What is a List? Why List can be called as Pairs. Explain with suitable example.
 List is constructed by placing expressions within square brackets separated by commas.
 The elements of a list can be accessed in two ways.
 The first way is via our familiar method of multiple assignment, which unpacks a list into its
elements and binds each element to a different name.
lst := [10, 20]
x, y := lst
 In the above example x will become10 and y will become 20.
 A second method for accessing the elements in a list is by the element selection operator, also
expressed using square brackets.
 Unlike a list literal, a square brackets expression directly following another expression does not
evaluate to a list value, but instead selects an element from the value of the preceding
expression.
lst[0]
10
lst[1]
20
 In both the example mentioned above mathematically we can represent list similar to a set.
lst[(0, 10), (1, 20)] – where

 Any way of bundling two values together into one can be considered as apair.
 Lists are a common method to do so.
 Therefore List can be called as Pairs.
3. How will you access the multi-item.
multi Explain with example.
 When we have a multi item object where each 'item' is a named thing: the firstName, the lastName,
the id, and the email,One
One could use a list to represent a person:
person=['Padmashri', 'Baskar', '994-222-1234',
'994 1234', 'compsci@gmail.com']
 Butut such a representation doesn't
doesn' explicitly specify what each part represents.
 instead of using a list, you can use the structure construct (In OOP languages it's called class
construct) to represent multi--part
part objects where each part is named (given a name).
 Consider the following pseudoudo code:
class Person:
creation( )
firstName := " "
lastName := " "
id := " "
email := " "
 The new data type Person is pictorially represented as

 The class (structure) construct defines the form for multi-part


multi part objects that represent a person.
 Its definition
tion adds a new data type, in this case a type named Person.
 Once defined, we can create new variables (instances) of the type.
 In this example Person is referred to as a class or a type,
 while p1 is referred to as an object or an instance.
 A class is nott just data, it has functions defined within it.
We say such functions are subordinate to the class because their job is to do things with the data of the class,
e.g., to modify or analyze the data of a Person object.
Therefore we can define a class as bundleddled data and the functions that work on that data.
data abstraction is that we can treat complex data in a very simple way.
CHAPTER – 3 SCOPING
Part - I
Choose the best answer (1 Mark)
1. Which of the following refers to the visibility of variablesin one part of a program to another part of
the same program?
(a)Scope (b) Memory (c) Address (d) Accessibility
2. The process of binding a variable name with an object
ob is called ………….
(a)Scope (b) Mapping (c) late binding (d) early binding
3. Which of the following is used in programming languages to map the variable and object?
(a):: (b) := (c) = (d) ==
4. Containers for mapping names of variables to objects
ob is called
(a)Scope (b) Mapping (c) Binding (d) Namespaces
5. Which scope refers to variables defined in current function?
(a)Local Scope (b) Global scope (c)Module scope (d) Function Scope
6. The process of subdividing a computer program into int separate sub-programs
programs is called
(a)Procedural Programming (b) Modular programming
(c)Event Driven Programming (d) Object oriented Programming
7. Which of the following security technique that regulates who canuse resources in a computing
environment?
(a)Password (b)Authentication (c)Access control (d) Certification
8. Which of the following members of a class can be handled only from within the class?
(a)Public members (b)Protected members (c)Secured members (d) Private members
9. Which members are re accessible from outside the class?
(a)Public members (b)Protected members
(c)Secured members (d) Private members
10. The members that are accessible from within the class and are also available to its sub-classes
sub is called
(a)Public members (b)Protected members
(c)Secured members (d) Private members
Part - II
Answer the following questions (2 Marks)
1. What is a scope?
 Scope refers to the visibility of variables, parameters and functions in one part of a program to
another part of thesame program.
 In other words, which parts of your program can see or use it.
2. Why scope should be used for variable. State the reason.
 Every
very variable defined in a program has global scope.
 Once defined, every part ofyour program can access that variable.
 But it is a good practice to limit a variable's scope to a single definition.
 This way, changes inside the function can't affect the variable on the outside of the function in
unexpected ways.
 So, scope must be used for a variable.
3. What is Mapping?
 The process
ess of binding avariable name with an object is calledmapping.
 := (colon equal to sign) is used in programming languages to map thevariable and object.
4. What do you mean by Namespace?
 Programming languages keeps track of all these mappings with namespaces.
 Namespaces are containers for mapping names of variables to objects.
objects
5. How Python represents the private and protected Access specifiers?
Python prescribes a convention of prefixing the name of the variable or method with single or double
underscore to emulate
late the behaviour of protected and private access specifiers.
Part - III
Answer the following questions (3 Marks)
1. Define Local scope with an example.
 Local scope refers to variables defined in current function.
 Always, a function will first look up for or a variable name in its local scope. Only if it does not
find it there, the outer scopes are checked.
Look at this example

 On execution of the above code the variable a displays the value 7, because it is defined
and available in the local scope.
2. Definee Global scope with an example.
 A variable which is declared outside of all the functions in a program is known as global
variable.
 This means, global variable can be accessed inside or outside of all the functions in a program.
 Consider the following example
ex

1. a:=10 Entire program Output of the Program

2. Disp(): a:=10 7

3. a:=7 Disp() 10

4. print a a:=7

5. Disp() print a

6. print a Disp()

print a

 On execution of the above code the variable


variable a which is defined inside the functiondisplays the
value 7 for the function call Disp() and then it displays 10, because a is defined inglobal scope
3. Define Enclosed scope with an example.
example
 All programming languages permit functions to be nested.
 A function
unction (method) within another function is called nested function.
 A variable which is declared inside a function which contains another function definition with in
it, the inner function can also access the variable of the outer function.
 This scope is called enclosed scope.
 When a compiler or interpreter search for a variable in a program, it first search Local, and then
search Enclosing scopes.
 Consider the following example

 In the above example Disp1() is defined with in Disp().


 The variable ‘a’ defined in Disp() can be even used by Disp1() because it is also a member of
Disp()
4. Why access control is required?
 Access control is a security technique that regulates who or what can view or user esources in a
computing environment.
 It is a fundamental concept in securitythat minimizes risk to the object.
 In otherwords access control is a selective restriction of access to data.
 In Object oriented programming languages it is implemented through access modifiers.
modifiers
 Classical object oriented languages, suchsuch as C++ and Java, control the access to class members by
public, private and protected keywords.
5. Identify the scope of the variables in the following pseudo code and write its output
color:= Red
mycolor():
b:=Blue
myfavcolor():
g:=Green
printcolor, b, g
myfavcolor()
printcolor, b
mycolor()
print color
Ans: Red Blue Green
Red Blue
Red
Part - IV
Answer the following questions (5Marks)
1. A)Explain the types of scopes for variable Answers of Part III 1,2,3 Questions and
Built-in Scope:
 Finally, wee discuss about the widest scope.
 The built-in in scope has all the names that are pre-loaded
loaded into the program scope when we
start the compiler or interpreter.
 Any variable or module which is defined in the library functions of a programming
language has Built-in
in or module scope.
 They are loaded as soon as the library files are imported to the program.

 Normally only Functions or modules come along with the software, as packages.
 Thereforefore they will come under Built-in
Built scope.
B)Explain LEGB rule with example.
examp
Scope also defines the order in which variables have to be mapped to the object in order to obtain
the value.
Let us take as imple example as shown below:
1. x:= 'outer x variable'
2. display():
3. x:= 'inner x variable'
4. print x
5. display()
When the above statements are executed the statement (4) and (5) display the result as
Output:
outer x variable
inner x variable
 Above statements give different outputs because the same variable name x resides in different
scopes, one inside the function display()
display() and the other in the upper level.
 The value ‘outer x variable’ is printed when x is referenced outside the function definition.
 Whereas when display() gets executed, ‘inner x variable’ is printed which is the x value inside
the function definition.
 From the above example, we can guess that there is a rule followed, in order to decide from
which scope a variable has to be picked.
 The LEGB rule is used to decide the order in which the scopes are to be searched for scope
resolution.
 The scopes are listed
ed below in terms of hierarchy (highest to lowest).

2. Write any Five Characteristics of Modules.


The following are the desirable characteristics of a module.
1. Modules contain instructions, processing logic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by othermodules.
othermodules
3. Write any five benefits in using modular programming.
The benefits of using modular programming include
• Less code to be written.
• A single procedure can be developed for reuse, eliminating the need to retype thecode many
times.
• Programs can be designed more easily because a small team deals with only a small part of the
entire code.
• Modular programming allows many programmers to collaborate on the same application.
• The code is stored across multiple files.
• Code is short, simple and easy to understand.
• Errors can easily be identified, as they are localized to a subroutine or function.
f
• The same code can be used in many applications.
• The scoping of variables can easily be controlled.
CHAPTER 4 ALGORITHMIC STRATEGIES
Part - I
Choose the best answer: (1 Marks)
1. The word comes from the name of a Persian mathematician Abu Ja’far Mohammed ibn-i ibn Musa al
Khowarizmi is called?
(a)Flowchart (b) Flow (c) Algorithm (d) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number numb of swaps?
(a)Bubble sort (b) Quick sort (c) Merge sort (d) Selection sort
3. Two main measures for the efficiency of an algorithm are
(a)Processor and memory (b) Complexity and capacity
(c)Time and space (d) Data and space
4. The complexity off linear search algorithm is
(a)O(n) (b) O(log n) (c) O(n2) (d) O(n log n)
5. From the following sorting algorithms which has the lowest worst case complexity?
(a)Bubble sort (b) Quick sort (c) Merge sort (d) Selection sort
6. Which of the following ng is not a stable sorting algorithm?
(a)Insertion sort (b) Selection sort (c) Bubble sort (d) Merge sort
7. Time complexity of bubble sort in best case is
(a)θ (n) (b) θ (nlogn) (c) θ (n2) (d) θ (n(logn) 2)
8. The Θ notation in asymptotic evaluation represents
(a)Base case (b) Average case (c) Worst case (d) NULL case
9. If a problem can be broken into subproblems which are reused several times, the problem possesses
which property?
(a)Overlapping subproblems (b) Optimal substructure
(c)Memoization (d) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is called ?
(a) Saving value property (b) Storing value property
(c)Memoization (d) Mapping
Part - II
Answer the following questions (2 Marks)
1. What is an Algorithm?
 An algorithm is a finite set of instructions to accomplish a particular task.
 It is a step-by-step
step procedure for solving a given problem.
2. Define Pseudo code.
Pseudocode is a simpler version of a programming code in plain English which whi uses short phrases to
write code for a program before it is implemented in a specific programming language.
3. Who is an Algorist?
One who practices algorithm is known as an algorist.
4. What is Sorting?
 Sorting is nothing but arranging the data in ascending
ascending or descending order.
 Sorting arranges data in a sequence which makes searching easier.
5. What is searching? Write its types.
 Searching is a process of locating a particular element present in a given set of elements. The
element may be a record, a table, or a file.
 Searching types are Linear search, Binary search, Jump search, Interpolation search,
Exponential search, Fibonacci search etc.
Part - III
Answer the following questions (3 Marks)
1. List the characteristics of an algorithm.
Characteristics of ann algorithm are:
Input, Output, Finiteness ,Definiteness
Definiteness, Effectiveness, Correctness, Simplicity,
Simplicity Unambiguous,
Feasibility, Portable, Independent.
Independent
2. Discuss about Algorithmic complexity and its types.
The complexity of an algorithm f(n) gives the running time and/or the storage space required by the
algorithm in terms ofn as the size of input data.
1. Time Complexity:
The Time complexity of an algorithm is given by the number of steps taken by the algorithm to
complete the process.
2. Space Complexity:
Space complexity of an algorithm is the amount of memory required to run to its completion. The
space required by an algorithm is equal to the sum of the following two components:
A fixed part is defined as the total space required to store certain data and variables for an algorithm.
For example, simple variables and constants used in an algorithm.
A variable part is defined as the total space required by variables, which sizes depends on the
problem and its iteration.
For example: recursion used to calculate factorial of a given value n.
3. What are the factors that influence time and space complexity?
Suppose A is an algorithm and n is the size of input data, the time and space used by the algorithm A
are the two mainfactors, which decide the efficiency of A.
Time Factor - Time is measured by counting the number of key operations like comparisons in the
sorting algorithm.
Space Factor - Space is measured by the maximum memory space required by the algorithm.
4. Write a note on Asymptotic notation.
Asymptotic Notations are languages that uses meaningful statements about time and space complexity.
The following thre easymptotic notations are mostly used to represent time complexity of algorithms:
(i) Big O
Big O is often used to describe the worst-case of an algorithm.
(ii) Big Ω
Big Omega is the reverse Big O, if Big O is used to describe the upper bound(worst - case) of a
asymptotic function, Big Omega is used to describe the lower bound(best-case).
(iii) Big Θ
When an algorithm has a complexitywith lower bound = upper bound, say that an algorithm has a
complexity O(n log n) and Ω(n log n), it’s actually has the complexity Θ(n log n), which means the
running time of that algorithm always falls in n log n in the best-case and worst-case.
5. What do you understand by Dynamic programming?
 Dynamic programming is an algorithmic design method that can beused when the solution to a
problem can be viewed as the result of a sequence of decisions.
 Dynamic programming approach is similar to divide and conquer. Th e given problem is
divided into smaller and yet smaller possible sub-problems.
 Dynamic programming is used whenever problems can be divided into similar sub-problems.
so that their results can be re-used to complete the process.
 Dynamic programming approaches are used to find the solution in optimized way.
 For every inner sub problem, dynamic algorithm will try to check the results of the previously
solved sub-problems.
 The solutions of overlapped sub-problems are combined in order to get the better solution.
Part - IV
Answer the following questions (5Marks)
1. Explain the characteristics of an algorithm.
An algorithm should have thefollowing characteristics:
Input : Zero or more quantities to be supplied.
Output: At least one quantity is produced.
Finiteness: Algorithms must terminate after finite number of steps.
Definiteness : All operations should be well defined. For example operations involving division by
zero or taking square root for negative number are unacceptable.
Effectiveness: Every instruction must be carried out effectively.
Correctness: The algorithms should be error free.
Simplicity: Easy to implement.
Unambiguous: Algorithm should be clear and unambiguous.Each of its steps and their inputs/outputs
should be clear and must lead to only one meaning.
Feasibility: Should be feasible withthe available resources.
Portable: An algorithm should be generic, independent of any programming language or an
operating system able to handle all range of inputs.
Independent: An algorithm should have step-by-step directions, which should be independent of any
programming code.
2. Discuss about Linear search algorithm.
 Linear search also called sequential search is a sequential method for finding a particular value
in a list.
 This method checks the search element with each elementeleme in sequence until the desired element
is found or the list is exhausted.
 In this searching algorithm, list need not be ordered.
Pseudo code:
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the currentt value of the list.
• If the values match, display the current index and value of the array
• If the values do not match, move on to the next array element.
3. If no match is found, display the search element not found.
 To search the number 25 in the array arra given below, linear search will go step by step in a
sequential order starting from the first element in the given array if the search element is found
that index is returned otherwise the search is continued till the last index of the array.
In this example number 25 is found at index number 3.

3. What is Binary search? Discuss with example.


 Binary search also called half-interval
half search algorithm.
 It finds the position of a search element within a sorted array.
 The binary search algorithm can be done d as divide-and-conquer
conquer search algorithm and executes
in logarithmic time.
Pseudo code for Binary search:
1. Start with the middle element:
• If the search element is equal to the middle element of the array i.e., the middle value =
number of elements in array/2, then return the index of the middle element.
• If not, then compare the middle element with the search value,
• If the search element is greater than the number in the middle index, then select the elements
to the right side of the middle index,
in and go to Step-1.
• If the search element is less than the number in the middle index, then select the elements to
the left side of the middle index, and start with Step-1.
Step
2. When a match is found, display success message with the index of the element
elem matched.
3. If no match is found for all comparisons, then display unsuccessful message.
Binary Search working |Principles:
 List of elements in an array must be sorted first for Binary search.
 The following example describes the step by step operation
operatio of binary search.
 Consider the following array of elements,
elem nts, the array is being sorted so it enables to do the binary
search algorithm.
 Let us assume that the search element is 60a nd we need to search the location or index of
search element 60 using binary
bina search.

 First, we find index of middle element of the array by using this formula :
mid = low + (high - low) / 2
 Here it is, 0 + (9 - 0 ) / 2 = 4 (fractional part ignored). So, 4 is the mid value of the array.

 Now compare the search element with the value stored at mid value location 4.
 The value stored at location or index 4 is 50, which is not match with search element.
 As the search value 60 is greater than 50.


 Now we change our low to mid + 1 and find the new mid value again using the formula.
low to mid + 1
mid = low + (high - low) / 2
 Our new mid is 7 now.
 We compare the value stored at location 7 with our target value 31.

 The value stored at location or index 7 is not a match with search element, rather it is more
than what we are looking for.
 So, the search element must be in the lower part from the current mid value location.
location

 The search element still not found.


 Hence, we calculated the mid again by using the formula.
high = mid -1
mid = low + (high - low)/2
 Now the mid value is 5.

 Now we compare the value stored at location 5 with our search element.
 We found that it is a match.
 We can conclude that the search element 60 is found at location
l ation or index 5.
 For example if we take the search element as 95, For this value this binary
bin search algorithm
return unsuccessful result.

4. Explain the Bubble sort algorithm with example.


 Bubble sort is a simple sorting algorithm.
 The algorithm starts at the beginning of the list of values stored in anarray.
 It compares each pair of adjacent
adjacen elements and swaps them if they are in the unsorted order.
 This comparison and passed to be continued until no swaps are needed, which indicates that the
list of values stored in an array is sorted.
 The algorithm is a comparison sort, is named for the way way smaller elements "bubble" to the top
of the list.
 Although the algorithm is simple, it is too slow and less efficient when compared to insertion
sort and other sorting methods.
 Assume list is an array of n elements.
 The swap function swaps the values of the given array elements.
Pseudo code:
1. Start with the first element i.e., index =0, compare the current element with the
next element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element
ement is less than the next or right side of the element, move to the next
element. Go to Step 1 and repeat until end of the index is reached.
 Let's consider an array with values {15, 11, 16, 12, 14, 13} Below, we have a pictorial
representation of how bubble
bub sort will sort the given array.

 The above pictorial example is for iteration-1.


iteration
 Similarly, remaining iteration can bedone.
 The final iteration will give the sorted array.
 At the end of all the iterations we will get the sorted values in an array as given below:
5. Explain the concept of Dynamic programming with suitable example.
 Dynamic programming is an algorithmic design method that can be used when the solution to a
problem can be viewed as the result of a sequence of decisions.
 Dynamic programming approach is similar to divide and conquer. Th e given problem is divided into
smaller and yet smaller possible sub-problems.
 Dynamic programming is used when ever problems can be divided into similar sub-problems. so that
their results can be re-used to complete the process.
 Dynamic programming approaches areused to find the solution in optimized way.
 For every inner sub problem, dynamicalgorithm will try to check the results of the previously solved
sub-problems.
 The solutions of overlapped sub-problems are combined in order to get the better solution.
Steps to do Dynamic programming:
•Th e given problem will be divided into smaller overlapping sub-problems.
• An optimum solution for the given problem can be achieved by using result of smaller sub-problem.
• Dynamic algorithms uses Memoization
Fibonacci Series – An example
 Fibonacci series generates the subsequent number by adding two previous numbers.
 Fibonacci series starts from two numbers − Fib 0 & Fib 1.
 The initial values of Fib 0 & Fib 1 can be taken as 0 and 1.
 Fibonacci series satisfies the following conditions :
Fibn = Fibn-1 + Fibn-2
 Hence, a Fibonacci series for the n value 8 can look like this
Fib8 = 0 1 1 2 3 5 8 13
Fibonacci Iterative Algorithm with Dynamic programming approach:
 The following example shows a simple Dynamic programming approach for the generation of
Fibonacci series.
 Initialize f0=0, f1 =1
step-1: Print the initial values of Fibonacci
f0 and f1
step-2: Calculate Fibonacci fib ← f0 + f1
step-3: Assign f0← f1, f1← fib
step-4: Print the next consecutive value of Fibonacci fib
step-5: Goto step-2 and repeat until the specified number of terms generated
 For example if we generate Fibonacci series upto 10 digits, the algorithm will generate
the series as shown below:
The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy