0% found this document useful (0 votes)
3 views28 pages

CH 1 4

The document covers key concepts in computer science, including functions, data abstraction, and scoping. It defines essential terms such as subroutines, pure and impure functions, and interfaces, while providing examples and differentiations between various programming constructs. Additionally, it discusses the importance of scope in variable visibility and the use of constructors and selectors in abstract data types.

Uploaded by

selvipayfixation
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)
3 views28 pages

CH 1 4

The document covers key concepts in computer science, including functions, data abstraction, and scoping. It defines essential terms such as subroutines, pure and impure functions, and interfaces, while providing examples and differentiations between various programming constructs. Additionally, it discusses the importance of scope in variable visibility and the use of constructors and selectors in abstract data types.

Uploaded by

selvipayfixation
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/ 28

12 th

COMPUTER SCIENCE

CHAPTER
NO CONTENT
1 FUNCTIONS
2 DATA ABSTRACTION
3 SCOPING
4 ALGORITHMIC STRATEGIES
1. FUNCTION

2 Mark

1. What is a subroutine?
Subroutines are the basic building blocks of computer programs. 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. A function works on many kinds of inputs and produces a concrete output.

3. Write the inference you get from X:=(78)


 X:=78 is a function definition
 Definitions bind values to names
 Hence, the value 78 bound to the name ‘X’.

4. Differentiate Interface and Implementation.


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

5. Which of the following is a normal function definition and which is recursive function
definition?
i) let sum x y:
return x+y
Ans: Normal Function
ii) let disp:
print ‘welcome’
Ans: Normal Function
ii) let rec sum num:
if(num!=0) then
return num + sum (num-1)
else
return num
Ans: Recursive function

2
3 Mark

1. Mention the characteristics of Interface.


The class template specifies the interface to enable an object to be created
and operated properly.
An objects‟ attribute and behavior is controlled by sending functions to the object.
2. Why strlen is called pure function?
s=”Name”
let length s:=
i:=0
if i < strlen(s) then
print s[i]
++i
Output
4
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.
3. What is the side effect of impure function. Give example.
Side effect of impure function is that it doesn‟t take any arguments and it
doesn‟t return any value. It is depends on variables or functions outside of its
definition block. If you call the impure functions with the same set of arguments,
 inc(4) // y=4
let y:=0
 inc(4) // y=8
let inc(x:int ) : int :=  inc( ) will change

y := y+x every time if the value


of ‘y’ get changed
return y
inside the function
definition
you might get the different return values.

3
4. Differentiate pure and impure function

Pure Function Impure Function


Pure functions will give exact result Impure functions with the same set of
arguments, you might get the different
when the same arguments are passed.
return values.
Pure function does not cause any side Impure function causes side effects to
effects to its output. its output.
The return value of the pure functions The return value of the impure functions
solely depends on its arguments passed does not solely depend on its arguments
passed
Example: strlen(), sqrt( ) Example: random( ), Date( )

5. What happens if you modify a variable outside the function? Give an


example.

Modifying the variable outside of the function causes side effect.

Example:

let y:=0  inc(4)


// y=4
let inc(x:int ) : int :=  inc(4) // y=8
 inc( ) will change
y := y+x
every time if the value
return y
of ‘y’ get changed
inside the function
definition

4
5 Mark

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.

Parameter Without Type

(requires : b>=0)
(returns : a to the power of b)
let rec pow a b:=
if b=0 then 1
else a * pow b(a-1)

The precondition (requires) and post condition (returns) of the function is


given. We have not mentioned any data types. This is called parameter
without type. The expression has type ‘int’, so the functions return type also
be „int‟ by implicit.
Parameter With Type

(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 b(a-1)

The types of argument and return type as „int‟. The type annotations for
„a‟ and „b‟ the parentheses are mandatory. This is the way passing parameter
with type which helps the compiler to easily infer them.

5
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


Ans: gcd
ii) Identify the statement which tells it is a recursive function
Ans: let rec gcd a b :=
(“rec” keyword tells the compiler it is a recursive function.)
iii) Name of the argument variable
Ans: „a‟ and „b‟
iv) Statement which invoke the function recursively
Ans: gcd b(a mod b)
v) Statement which terminates the recursion
Ans: return a

3. Explain with example Pure and Impure functions.

Pure Function Impure Function


Pure functions will give exact result Impure functions with the same set of
when the same arguments are passed. arguments, you might get the different
return values.
Pure function does not cause any side Impure function causes side effects to
effects to its output. its output.
The return value of the pure functions The return value of the impure functions
solely depends on its arguments passed does not solely depend on its arguments
passed
They do not modify the arguments They may modify the arguments which
which are passed to them are passed.

6
Example: Example:
let square x let a:= random( )
return: x * x let random( ) :=
if a>10 then
return: a
else
return: 10
4. Explain with an example interface and implementation.
Interface
An interface is a set of action that an object can do.
 Interface just defines what an object can do, but won‟t actually do it.

 The class template specifies the interface to enable an


object to be created and operated properly.
 An objects‟ attribute and behavior is controlled by sending
functions to the object.
Example

7
 when you press a light switch, the light goes on, you may not
have cared how is splashed the light .
 A light should have function definitions like turn_on( ) and turn_off( ).
Implementation
 Implementation carries out the instructions defined in the interface.
 A class declaration combines the external interface with an
implementation of the interface.
 An object is an instance created from the class
Example
 The person who drives the car doesn’t care about the internal working.

 To increase the speed of the car he just presses the accelerator to


get the desired behavior. This is the interface.
 Internally, the engine of the car is doing all things.

 Its’ where fuel, air, pressure, and electricity come together to


create the power to move the vehicle.
 Thus we separate interface from implementation.

2. DATA ABSTRACTION
2 Mark
1. What is abstract data type?

Abstract Data type is a type or class for objects whose behavior is


defined by a set of value and a set of operations.
2. Differentiate constructors and selectors.
CONSTRUCTORS SELECTORS
Constructors are functions that Selectors are functions that retrieve
build the abstract data type. information from the data type.
Constructors create an object, Selectors extract individual pieces
bundling of information from the object.
together different pieces of
information.
8
3. What is a Pair? Give an example.
Any way of bundling two values together into one can be considered as a
pair, Lists are a common method to do so. Therefore List can be called
as Pairs. Example

lst[(0, 10), (1, 20)]

4. What is a List? Give an example.


List is constructed by placing expressions within square brackets
separated by commas. Such an expression is called a list literal. List
can store multiple values.
Example
lst := [10, 20]

x, y := lst // x will become 10 and y will become 20

5. What is a Tuple? Give an example.


A tuple is a comma-separated sequence of values surrounded with
parentheses. Tuple is similar to a list. cannot change the elements of a tuple.
Example

colour = („red‟, „blue‟, „green‟)

3 Mark

1. Differentiate Concrete data type and abstract data type.

Concrete Data Type Abstract Data Type


Concrete data types or structures Abstract Data types offer a high
are direct implementations of a level view of a concept
relatively simple concept. independent of its implementation.
Concrete Data Type is a data type Abstract Data Type is the
whose representation is known. representation of a data type is
unknown.
9
2. Which strategy is used for program designing? Define that Strategy.

 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 imaging instead of by
appealing to reality.
3. Identify which of the following are constructors and selectors?

a N1= number( ) a Constructors


b accetnum(n1) b Selectors
c displaynum(n1) c Selectors
d eval(a/b) d Selectors
e x, y = makeslope (m), e Constructors
makeslope(n)
f display ( ) f Selectors
4. What are the different ways to access the elements of a list. Give example.
The first way method of multiple assignments, which unpacks a
list into its elements and binds each element to a different name.
Example
lst := [10,20]

x, y := lst // x will become 10 and y will become 20

The second method for accessing the elements in a list is by the


element selection operator, also expressed using square brackets.
Example
lst[0]

10

lst[1]

20

10
4. Identify which of the following are List, Tuple and Class?
a arr[1,2,3,4] a List
b arr(1,2,34) b Tuple
c student[rno, name, mark] c Class
d day = („sun‟, „mon‟ ,„tue‟, „wed‟) d Tuple
e x = [2, 5, 6.5,[5,6],8.2] e List
f employee[eno, ename, esal, eaddress] f Class
5 Mark

1. How will you facilitate data abstraction. Explain it with suitable example.
Data abstraction is supported by defining an abstract data type,
which is a collection of constructors and selectors.
Constructors
 Constructors are functions that build the abstract data type.
 Constructors create an object, bundling together different pieces of
information.
Example
city = makecity(name, lat, lon)
Here makecity(name, lat, lon) is the constructor which creates the object
city.
Selectors
 Selectors are functions that retrieve information from the data type.
 Selectors extract individual pieces of information from the object.
Example
getname(city)

getlat(city)

getlon(city)

These are the selectors because these functions extract the


information of the city object.
11
2. What is a List? Why List can be called as Pairs. Explain with
suitable example.
List

List is constructed by placing expressions within square brackets


separated by commas. Such an expression is called a list literal. List
can store multiple values.
The first way method of multiple assignments, which unpacks a list
into its elements and binds each element to a different name.
Example
lst := [10,20]

x, y := lst // x will become 10 and y will become 20

The second method for accessing the elements in a list is by the


element selection operator, also expressed using square brackets.
Example
lst[0]

10

lst[1]

20

Pair

Any way of bundling two values together into one can be considered as a
pair, Lists are a common method to do so. Therefore List can be called
as Pairs. Example

lst[(0, 10), (1, 20)]

Index Position value


12
3. How will you access the multi-item. Explain with example.
The class or structure construct to represent multi-part of objects
where each part is named.
Pseudo code
class Person:
creation( )
firstName := “ ”
lastName := “ ”
id := “ ”
email := “ ”

Person Class name (multipart data representation)


creation( ) function belonging to the new data type
first Name
last Name
id variable belonging to the new data type
email

Let main( ) contains


p1 := Person( ) Statement creates the object.
firstName := a field called firstName with value Padmashir
“Padmashri”
lastName := “Baskar” a field called lastName with value Baskar
id:= “994-222-1234” a field called id value 994-222-1234
email := a field called email with value
[email protected] [email protected]
--Output of firstName: Padmashri
The class construct defines the form for multi-part objects that
represent person. Person is referred to as a class or type, while p1 is
13
referred to as an object or an instance. A class as bundled data and the
functions that work on that data.

3. SCOPING
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 the same rogram.
2. Why scope should be used for variable. State the reason.

Scope should be used for variable because every part of the program can
access the variable.
3. What is Mapping?

 The process of binding a variable name with an object is called mapping.


 = (equal to sign) is used in programming languages to map the
variable and object.

4. What do you mean by Namespaces?

Namespaces are containers for mapping names of variables to


objects. (name := object)
Example

a := 5

5. How Python represents the private and protected Access Specifiers?

Python prescribes a convention of prefixing the name of the


variable/method with single or double underscore to emulate the
behavior of protected and private access specifiers.

14
3 Marks

1. Define Local scope with an example.

 Local scope refer to variable defined in current function.

 A function will first look up for a variable name in its local scope.

 Only if it does not find it there, the outer scopes are


checked. Example
Disp( ):
a := 7
print a
Disp( )

Output

2. Define Global scope with an example.

 A variable which is declared outside of all the functions in a


program is known as Global variable.
 Global variable can be accessed inside or outside of all the functions in a
program.

Example
a := 10
Disp( ):
a := 7
print a
Disp( )
print a
Output
7
10

15
3. Define Enclosed scope with an example.

 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.


Example
Disp( ):

a:=10

Disp1( ):

print a

Disp1( )

print a

Disp( )

Output

10

10

4. Why access control is required?


 Access control is a security technique that regulates who
or what can view or use resources in a computing
environment.
 It is a fundamental concept in security that minimizes risk to the
object.
 Access control is a selective restriction of access to data.
 Access control is private, protected, public.

16
5. Identify the scope of the variables in the following pseudo code
and write its Output
color:= ‘Red’
mycolor( ):
b:= ‘Blue’
myfavcolor( ):
g:= ‘Green’
print color, b,
g myfavcolor( )
print color, b
mycolor(
) print
color
Ans:
Output
Red Blue Green
Red Blue
Red
Scope of the variables
Variables Scope
color:= ‘Red’ Global Scope
b:= ‘Blue’ Enclosed Scope
g:= ‘Green’ Local Scope
5 Marks

1. Explain the types of scopes for variable or LEGB rule with example.

LEGB rule is used to decide the order in which the scopes are to be
searched for scope resolution.

17
Local Scope

Enclosed Scope

Global Scope

Built-in Scope

Local Scope

 Local scope refer to variable defined in current function.

 A function will first look up for a variable name in its local scope.

 Only if it does not find it there, the outer scopes are Checked. Example

Disp( ):
a := 7
print a
Disp( )
Output
Global Scope 7

 A variable which is declared outside of all the functions in a


program is known as Global variable.
 Global variable can be accessed inside or outside of all the functions in a
program. a := 10
Example
Disp( ):
a := 7
print a
Disp( )
print a
Output
7
10

18
Enclosed Scope

 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. Example Disp( ):


a:=10
Disp1( ):
print a
Disp1( )
print a
Disp( )

Output
10
10

19
Built-in-Scope

The built-in scope has all the names that are pre-loaded into the
program scope when we start the compiler or interpreter.
Library files
associated
Built in/ module scope
with the
Disp( ):
Disp1( ): software.

print a
Disp1( )
print a
Disp( )

2. Write any Five Characteristics of Modules.


 Modules contain instructions, processing, logic, and data.
 Modules can be separately compiled and stored in a library.
 Modules can be included in a program.
 Module segments can be used by invoking a name and some
parameters.
 Module segments can be used by other modules.
3. Write any five benefits in using modular programming.
 Modular programming allows many programmers to collaborate on
the same application
 Less code to be written.
 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.
 The same code can be used in many applications.
 The scoping of variables can easily be controlled.

20
4. ALGORITHMIC STRATEGIES
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 procedure for solving a given problem.

2. Define Pseudo code.

 Pseudo code is a methodology that allows the programmer to represent the


implementation of an algorithm.
 It has no syntax like programming languages and thus can’t be compiled or
interpreted by the computer.
3. Who is an Algorist?
 A person skilled in the design of algorithms are called as Algorist.
 An algorithmic artist.
4. What is Sorting?
 Sorting is defined as an arrangement of data in a ascending or descending order.
 Sorting techniques are used to Bubble Sort, Selection Sort, Insertion Sort.
5. What is searching? Write its types.
 Searching Algorithms are designed to check for an element or retrieve an
element form any data structure where it is stored.
 Linear Search
 Binary Search
3 Marks
1. List the characteristics of an algorithm.

Input Simplicity
Output Unambiguous
Finiteness Feasibility
Definiteness Portable
Effectiveness Independent
Correctness

21
2. Discuss about Algorithmic complexity and its types.
 Algorithmic complexity is concerned about running time and storage space
required by the algorithm. f(n) – n as the size of input data.
Time Complexity
 The Time complexity of an algorithm is given by the number of steps
taken by the algorithm to complete the process.
Space Complexity
 Space complexity of an algorithm is the amount of memory required to
run to its completion.

3. What are the factors that influence time and space complexity.
 Time Factor is measured by counting the number of key operations like
comparisons in the sorting algorithm.
 Space Factor is measured by the maximum memory space required by
the algorithm.
 Algorithmic complexity is concerned about running time and storage space
required by the algorithm. f(n) – n as the size of input data.

3. Write a note on Asymptotic notation.


 Asymptotic Notations are languages that uses meaningful statements
about time and space complexity.
 Big 𝚶 - Big Oh is used to describe the upper bound (worst case) of a
asymptotic function - O(n log n)
 Big 𝛀 - Big Omega is the reverse Big Ο. It is used to describe the lower
bound (best case) of a asymptotic function - 𝛀(n log n)
 Big 𝚯 - Big Theta is used to describe the lower bound = upper bound
(best case and worst case) of a asymptotic function - 𝚯(n log n)

4. What do you understand by Dynamic programming?

 Dynamic programming is an algorithmic design method is 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. The
problem can be divided into smaller sub-problems.
 Results can be re-used to complete the process.
22
 Dynamic programming approaches are used to find the solution in optimized
way.

5 Marks
1. Explain the characteristics of an algorithm.

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.

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.

Feasibility Should be feasible with the available resources.

An algorithm should be generic, independent and able to handle


Portable
all range of inputs.

An algorithm should have step-by-step directions, which should be


Independent
independent of any programming code.

2. Discuss about Linear Search algorithm.


Linear Search
 Linear search also called sequential search is a sequential method for
finding a particular value in a list.
 The search element with each element is found or the list exhausted.
 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 current
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.
23
3. If no match is found display the search element not found.

Index 0 1 2 3 4
values 10 12 20 25 30
Example 1
Input:
values[ ] = {10, 12, 20, 25, 30}
target = 25

Output: 3
Example 2
Input:
values[ ] = {10, 12, 20, 25, 30}
target = 50
Output:
-1

24
3. What is Binary Search? Discuss with example.
 Binary Search also called half-interval search algorithm.
 It finds the position of a search element with a sorted array.
 It can be done as divide and conquer search algorithm .

Pseudo code
1. Start with the middle element:
middle value = number of elements in array/2.
2. If not, then compare the middle element with the search value,
3. 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, and go to step 1.
4. 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 step1.
5. when a match is found, display success message with the index of the
element matched.
6. If no match is found for all comparisons, then display unsuccessful message.
Example
 List of elements in an array must be sorted first for Binary Search.
 The search element is 60.

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

mid= low + (high – low)/2

 Here it is, 0 + (9-0)/2 = 4.5 (fractional part ignored)

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

low = mid + 1 // low=5


mid= low + (high – low)/2
mid =5 + (9-5)/2 = 7 is a mid value
Which is not match with search element.
60=60

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

high = mid - 1 // high =6


mid= low + (high – low)/2
mid = 5 + (6 – 5)/2 = 5.5 (fractional part ignored)

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

 The search element 60 is found at location or index 5.

4. Explain the Bubble sort algorithm with example.


 Bubble sort is a simple sorting algorithm.

 It compares each pair of adjacent elements and swaps them If they are in

the unsorted order.

 This comparison and passed to be continued until no swaps are needed.

26
Pseudo code
1. Start with the first element 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 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 in reached.

Example
An array with values {15, 11, 16, 12, 14, 13}

15 > 11
15 11 16 12 14 13
So interchange

15 < 16
15 11 16 12 14 13
No swapping

16 > 12
11 15 16 12 14 13
So interchange

16 > 14
So interchange 11 15 12 16 14 13

16 > 13
11 15 12 14 16 13
So interchange

11 15 12 14 13 16

 The final iteration will give the sorted array.

 At the end of all the iterations we will get the sorted values in an array

11 12 13 14 15 16

27
5. Explain the concept of Dynamic programming with suitable Example.
 Dynamic programming is an algorithmic design method is 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. The
problem can be divided into smaller sub-problems.
 Results can be re-used to complete the process.
 Dynamic programming approaches are used to find the solution in optimized
way.

Steps to do Dynamic Programming


 The 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.

Example: Fibonacci Iterative Algorithm


 Fibonacci series Initialize f0 = 0, f1 = 1.

Step 1: Print the initial values of Fibonacci f0 and f1 // f0,f1 = 1

Step 2: Calculate Fibonacci fib ← f0 + f1 // fib =2

Step 3: Assign f0 ←f1, f1←fib // f0 = 1 , f1 = 2

Step 4: Print the next consecutive value of Fibonacci fib // fib = 3

Step 5: Go to step 2 and repeat until the specified number of terms generated.

Example: If we generate Fibonacci series upto10 digits,

The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55

28

You might also like