Unit_III

41
Unit III Sequence control Sequence control determines the sequence of the program, in which program is executed. This involves two aspects:- #control of the order of execution of operations both primitive and user defined. Primarily, sequence control is defend at four levels: Expression sequence control Statement sequence control Subprogram sequence control Declarative programming 1. Expression sequence control – From the basic building blocks for statement and express how data are manipulated and changed by a program. Properties such as precedence rules and parentheses, determine how expression become evaluated. 1

Transcript of Unit_III

Page 1: Unit_III

Unit IIISequence control

Sequence control determines the sequence of the program, in which program is executed.

This involves two aspects:-#control of the order of execution of operations both primitive and user defined.

Primarily, sequence control is defend at four levels: Expression sequence control Statement sequence control Subprogram sequence control Declarative programming

1. Expression sequence control – From the basic building blocks for statement and express how data are manipulated and changed by a program. Properties such as precedence rules and parentheses, determine how expression become evaluated.

2. Statement sequence control – Statements or groups of statements such as conditional and iteration statement, determine how control flaws from one segment of a program to another.

3- Declarative programming (in prolog)-Declarative programming is an execution model that does not depend on statement, but nevertheless causes execution

1

Page 2: Unit_III

to proceed, though a program prolog is the example for this.

4- Subprogram sequence control – Subprograms, such as subprograms calls and Co-routines, from a way to transfer control from one segment of a program to another.

Sequence control is of two type – 1- Explicit sequence control (by programmer)2- Implicit sequence control,(defined by language it self )

Implicit Vs explicit sequence control – Implicit sequence control is defined by the language. Basically in implicit sequence control statement are executed in a row. In explicit sequence control, control is explicit.

For Example:- we can use go to statement that transfer control from one location to another location.

Sequence control for expressions: -Expressions are evaluated using assignment.

1- Priorities of operators (highest priority first) Operator class operator Asthmatic operators *, /, +, - ,relational operation <, <= , >, >=, = , # logical operation not, and, or

2

Page 3: Unit_III

Operators of higher priority are applied before operators of lower priority.

2- Left-to-right evolution- Operators of the same priority are evaluated from the left to right. Arithmetic expressions are evaluated from left to right using the rules of precedence:

eg- 18-7-5 = (18-7)-5 = 11-5 = 6#Not equal to 18-(7-5) = 18-2 =16 wrong ans.

3. Parentheses- An expression enclosed in parentheses is evaluated before being applied as an argument. In combination with priorities and left-to-right evaluation parentheses are only needed where the standard evaluation order is not desired. For example- 18-(7-5) = 18-2

= 16

Tree-structure representation-

Tree from the simple expression – : (a+b)x (c-a)

3

Page 4: Unit_III

In arithmetic expression tree, leaves are used to represent operands and root in used for main operation of expression. The nodes between roots and leaves are used for intermediate operations.

Example: -1 Evaluate the following expression- A-(C/5 *2) + (D *5 % 4)

4

Page 5: Unit_III

Example 2. Tree representation of quadratic formula –Consider the following formula for computing root of the quadratic equation.

In a high-level language such as FORTRAN –The formula for one of the roots can be coded as a single expression almost directory-

The tree representation clarifies the control structure of the expression:-

5

Page 6: Unit_III

Expression Tree:-The structure of an expression may be represented by an expression tree. An expression tree is a recursive data structure. Which are defined as –

Elementary tree :- An elementary tree consist of a single node for an elementary operand.

Composite tree :- The root node (top of the three) represents an operator and each operand is represent by a sub tree.

6

Page 7: Unit_III

SYNTAX FOR EXPRESSION: -For syntax purpose of expression, we need three notations. These are:- Prefix notation (Polish prefix Notation) Postfix Notation (Suffix or reverse Polish Notation) Infix Notation.

1. Prefix notation :- In function calls we write function name first then arguments like f (X,Y).Here f is used for function while x & y is used for arguments. This technique can also be used for expression purpose. This notation is called prefix notation.Example- +ab is used in place of expression (a+b).

2. Postfix Notation :- In Postfix symbol, we write operands first

the corresponding operators. Example-

ab+ is used in place of expression (a+b).

3. Infix Notation :- In, Infix Notation, first we write operand then corresponding operators and finally operands.Normally we use Infix Notation.Example:- a+b

SEMANTICS FOR EXPRESSION:-

Semantics determines the order of expressions in which they are evaluated:Corresponding semantics for each syntax is given by :-1. Prefix Evaluation 2. Postfix Evaluation3. Infix Evaluation

7

Page 8: Unit_III

1. Prefix Evaluation :- Let P is the given expression then it is executed in following manner-

If the next item in P is an operator then put into the stack. Set the arguments count to be the numbers of operands needed by the operator.

If next item of P is an operand then push on to the stack.

If the top n entries in the stack are operands needed for top n-ary operator , we can apply the top operator to these operands. Replace the operator and n-operands by result.

2. Postfix Evaluation :- Let P is the given expression then it is executed in following manner: If the next item of P is an operand, place it on the stack. If the next item of P is an n-ary operator, then it’s n arguments must be the top n items on the stack. Replace these n items by the result.

3. Infix Evaluation :-Let P is the given expression then it is executed in following manner: As infix notation is suitable for binary operations, A language can not use only infix notation. Therefore, we can use mixture of infix with prefix or postfix. But to evaluate mixture it is very complex task. When more then one infix operator appears in an expression, parentheses are used at the right place.

8

Page 9: Unit_III

Sequence control for statements :-(Sequence control between statement) :-

Program consists of multiple statements. There are few types of statements.(Sequence control is different for both the types).1. Basic statement 2. Compound statement }3. Conditional Statement } Under the structured sequence control

1. Basic statement : The result for any program are determined by its basic statement that apply operations to data objects. Basic statements include assignment statements, subprogram calls and input-output statements.Normally basic statement are written in a single line. Few basic statements are –

Assignment statement

Input statement

Go to statement

Break statement etc.

1. Assignment statement –

The Primary purpose of an assignment is to assign to the L-value of a data object (i.e., to its memory location) the R-value (i.e., the data object value) of some expression.Assignment is the central operation define for every elementary data type.

9

Page 10: Unit_III

A : = B In Pascal, AdaA = B In C, Fortran, PL/I, Prolog, MLMOVE B to A In COBOLA B In APL(SETQ A B) In LISP

For Example-

int i, *p;p = &i;*p = 7

We have: i is declared as an integer ; p is declared as a pointer to an integer; p is set to point to i ,

i.e., L-value is converted to an R-value (& i) and this R- value stored as the R-value of p;

p’s R-value is converted to be an L-value (*p); it is the L-value of i, so R-value set to 7.

2. Input statement- To give the input at run time, we can use input statement. In c-programming we have –

Scanef (“%d”, & a); Here a is the variable and value of a is assigned to run time.

3. Goto statement –

Goto statement is explicit sequence control statement. It transfer the control from one location to another location.

10

Page 11: Unit_III

4. Break statement –

Whenever break is executed , control comes out from the block;

2.COMPOUND STSTEMENT – Compound statement is the sequence of statement that may be treated as a single statement in the construction of larger statements.

A compound statement is written as :

begin... Sequence of statements (one or more)end

in c it is written simply as {...}Within the compound statement, statements are written in the

order in which they are to be executed.Thus compound statement is the basic structure for

representing the composition of statements.

Source Destination Begin .........................................................................End

A compound statement is implemented in a conventional computer by placing the blocks of executable code representing each constituent statement in sequence in memory. The order in which they appear in memory determines the order in which they are executed.

3.CONDITIONAL STATEMENT – A conditional statement is one that expresses alternation of two or more statements, or optional execution of a single statement;

11

Page 12: Unit_III

The choice of alternative is controlled by a test on some condition, usually written as an expression involving relational and Boolean operations. The most common forms of conditional statements are the if and case statements.

Some similar statements are –

- if statement- for statement- while statement- Do loop

$$ Subprogram sequence control-A subprogram is an abstract operation defined by the programmer. Two views of subprograms are important –

At the program design level At the language design level

In parameters

Subprogram

In/out Localvariables Read/ Global parameters Modifies variables Statements

Out parameters

Generic view of subprogram

Some more general subprogram control structure are :

12

Page 13: Unit_III

(a) Subprograms can not be recursive(b) Explicit call statements are required (c) Subprograms must execute completely at each call(d) Immediate transfer of control at point of call(e) Single execution sequence

There are two types of sequence control in subprograms.These are –

(a) Simple Call-Return subprograms.(b) Recursive Calls subprograms.

(a) Simple Call-Return subprograms-

Simple call return support the following properties-

- No recursive call (no recursive subprograms)- Explicit call statements are required.- Subprogram must be execute completely at each call.- Control must be transferred immediately at the point of

call.- There must be a single execution sequence.

Implementation-

To understand the implementation of the simple call-return control structure, it is important to build a more complete model of what it means to say that a program is being executed.For expressions and statement sequence, we think of each as represented by a block of executable code at run time. Execution of the expression or statement sequence means simply execution of the code, using a hardware and software interpreter but for subprograms, we need more:

13

Page 14: Unit_III

1. There is a distinction between subprogram definition and subprogram activation.

2. An activation is implemented as two parts: A code segment containing the executable code and constants, and an activation record containing local data, parameters and various other data items.

3. The code segment is invariant during execution.4. The activation record is created each time the subprogram is

call, and it is destroyed when the subprogram returns.

Call

Return

There are two important pointers are required to implements:Sequence control of the sub program is determined with the help of CIP and CEP.

Current-instruction pointer (CIP)

We consider that at any point during execution there are some instructions are executed in a code segment. This instruction is called current instruction and we need a pointer to point the current instruction, is called current instruction pointer.

14

Page 15: Unit_III

Current Environment pointer (CEP)

Because all activations of same sub program contains same code segments and different activation records. Therefore CIP is not enough, we need one more pointer it is called CEP. It points to current activation record of a subprogram.

The only difference between a recursive call and an ordinary call is that the recursive calls create a second activation of the subprogram during the lifetime of the first activation. If the second activation leads to another recursive call, then three activations may exist simultaneously, and so on.For Example-When A calls B, life times can’t overlap, The lifetime of A completely includes that of B.

In the same way of recursive call, new activation record of A could just be added to the stack containing the older activation record of A.

Conventionally, computer hardware provides central stag organization, but it is generally somewhat more coastally to implement then the simple call return structure without recursion. Only sub programs that are actually called recursively need the central stag implementation.

[[Advances in Language Design]]$$ Exceptions and Exception Handlers : An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

An exception is a hardware detected run-time error or unusual condition detected by software.Examples-

Arithmetic overflow End-of-file on input Wrong type for input data User define conditions

15

Page 16: Unit_III

Exception Handler (What is an Exception Handler?):-

Code executed when exception occurs. May need a different handler for each type of exception.

Exceptions Handling :- Exceptions are exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. The condition is called an exception. When an error occurs with in a method, the method creates an object and hands it of to the runtime system. The object, called an exception object, contains information about the error; creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system attempts to find some thing to handle it. The set of possible “some things” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.

16

Page 17: Unit_III

The run time system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through call stack in the reverse ordered in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.

Thus, exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special function called handlers. Because an exception handler is invoked without an explicit call, it ordinarily does not require a name or parameters.The definition of an exception handler typically contains only-

A set declarations of local variables (if any), and A sequence of executable statements.

17

Page 18: Unit_III

$$ COROUTINES: -Co-routines are subprograms that can return control to the caller before completion of execution. When a coroutine receives control from another subprogram, it executes partially and then is suspended when it returns control. At a later point, the calling program may resume execution of the coroutine from the point at which execution was previously suspended.

For Example-

If A calls subprograms B as a coroutine, B executes awhile and returns control to A, just as any ordinary subprogram would do.When A again passes control to B via a resume B, B again executes awhile and returns control to A, Just as an ordinary subprogram. However, the situation is similar when viewed from subprogram B. B, in the middle of the execution, resume execution of A. A executes awhile and returns control to B. B continues execution awhile and return control to A. A continues execution awhile and returns control to B. From subprogram B, A appears much like an ordinary subprogram.

18

Page 19: Unit_III

The name coroutine derives from this symmetry, the two programs appear more as equals-two subprograms swapping control back and forth as each executes, with neither clearly controlling the other. “Coroutines are execution context that exist concurrently, but that execute one at a time and that transfer control to each other explicitly, by name.”

$$ SCHEDULED SUBPROGRAMSThe concept of subprogram scheduling results from relaxation of the assumption that execution of a sub program should always be initiated immediately upon its call. One may think of an ordinary subprogram call statement as specifying that the called subprogram is to be scheduled for execution immediately, without completing execution of the calling program. Completion of execution of the calling program is rescheduled to occur immediately on termination of the subprogram. The exception-handling control structure may be viewed also as means of subprogram scheduling.Generalizing further, other subprogram scheduling techniques are possible:

1. Schedule subprograms to be executed before or after other subprograms, as, for example:-

call B after A, Which would schedule execution of subprogram B after execution of subprogram A is completed.

2. Schedule subprograms to be executed when an arbitrary Boolean expression becomes true, as, for example:

19

Page 20: Unit_III

Call b when X = 5 and Z > 0B is called whenever the value of Z and X are changed to satisfy the given conditions.

3. Schedule subprograms on the basis of a simulated time scale, as, for Example:

call B at time = 25 Such scheduling allows a general interleaving of subprogram calls scheduled form different sources.

4. Schedule subprograms according to a priority designation, as, for example:

Call B with priority 7Which would active B when no other subprogram with higher priority has been scheduled.11/16/2010 9:40:50 Pmpratt/pg-383/9.1.3

Concurrent execution: - The Principal mechanism for installing parallel execution in a programming language is to create a construct that allows for parallel execution.The end statement performs this task:Satatement1 and statement2 and…and statement nAnd has the semantics that each of the various statement i execute in parallel; the statement following the and statement does not begin until all the parallel statements terminate. It provides the full parallel power we need for parallel execution.For Example:-If an operating system consists of a task to read from a terminal, a task to write to a screen and a process to execute a user program, we could specify this operating system as:

Call Read Process andCall Write Process and

Call Execute user program;

20

Page 21: Unit_III

Pratt/pg-294/7.2

$$Data Control Referencing Environments

Attributes of data control:- The data-control features of a programming language are those parts concerned with the accessibility of data at different points during program execution. The data-control features of a language determine how data may be provided to each operation, and how a result of one operation may be saved and retrieved for later use as an operand by a subsequent operation.For Example:A Pascal program contains:

X := Y + 2 * ZSimple inspection indicates three operations in sequence: a multiplication, an addition, and an assignment. One operand of the multiplication is clearly the number 2, but the other operands are marked only by the identifiers X, Y and Z and these obviously are not the operands but only designate the operands in some manner.

Names and Referencing Environments: -There are two ways to make a data object available as an operand for an operation.

1. Direct transmission:- A data object computed at one point as the result of an operation may be directly transmitted to another operation as an operand.Example-The result of multiplication is transmitted directly as an operand of the addition operation.

X := Y + 2 * Z

2. Referencing through a named data object :-

21

Page 22: Unit_III

A data object may be given a name when it is created, and the name may then be used to designate it as an operand of an operation.

Direct transmission is used for data control within expressions, but most data control of outside of expression evolves the use of names and the referencing of names. The problem of the meaning of names forms the central concern in data control.

Program elements that may be named are as follows:

1. Variables names2. Formal parameters names3. Subprograms names4. Names for defined types5. Names for defined constants6. Statement labels (names for statements)7. Exception names8. Names for primitive operations, e.g., +, *, SQRT.9. Names for literal constants, e.g., 17, 3.25.

Associations and Referencing Environment: - Associations: Data control is concerned in large part with the binding of identifiers to particular data objects and subprogram. Such a binding is termed an association and may be represented as a pair consisting of the identifier and its associated data object or subprogram.During the execution of a program, we observe the following:

1. At the beginning of execution of the main program, identifier associations bind each variable name declared in the main

22

Page 23: Unit_III

program to a particular data object and bind each subprogram name invoked in the main program to a particular subprogram definition.

2. As the main program executes, it invokes referencing operations to determine the particular data object or subprogram associated with an identifier.

For Example: A := B+ FN (C)

In this, four referencing operations are required to retrieve the data object associated with names A, B, and C and the subprogram associated with the name FN.3. When each new subprogram is called, a new set of associations

is created for that subprogram.4. As the subprogram executes, it invokes referencing operations

to determine the particular data object or subprogram associated with each identifier.

5. When the subprogram returns control to the main program, its associations are destroyed (or become inactive).

6. When control returns to the main program, execution continues as before using the associations originally setup at the start of the execution.

Referencing Environment: - Each program or subprogram has a set of identifiers associations available for use in referencing during its execution. This set of identifier associations is termed the referencing environment of the subprogram (or program). The referencing environment of a sub program is ordinarily invariant during its execution. It is set up when the subprogram activation is created and it remains unchanged during the lifetime of the activation.The referencing environment of a subprogram may have several components:1. Local referencing environment (or simply local environment).2. Nonlocal referencing environment.

23

Page 24: Unit_III

3. Global referencing environment.4. Predefined referencing environment

$$ Static and Dynamic Scope: Scope is an important concept in programming languages. The scope of a variable in a program is the lines of code in the program where the variable can be accessed.Two different type of scope have been used in programming languages:

Static ScopeAnd

Dynamic ScopeStatic Scope:

In this the compiler can determine when binding will be created and destroyed. It is Based on programming text. To connect a name reference to variable, you must find the declaration. Search process: Search declarations, first locally, then in increasingly larger enclosing scopes, until one is found for the given name. Enclosing static scopes are called its static and ancestors; the nearest static ancestor is called a static parent. Variables can be hidden from a until by heaving a “closer” variable with the same name. C++ and Ada allow access to these “hidden” variables. In Ada : unit.name In C++ : class_name : : name Dynamic Scope: Bindings cannot always be resolved by examining the program because they are dependent on calling sequences. Dynamic Scope is:

24

Page 25: Unit_III

Based on calling sequences of program units, not their textual layout. References to variables are connected to declarations by searching back through the chain of subprogram calls that forced execution to this point. Dynamic scope rules are usually encountered interpreted languages. Such languages do not normally have type checking at compile time because type determination is not always possible when dynamic scope rules are in effect. Bindings between names and objects depend on the flow of control at runtime.-------------------------------------------------------------------------

Most modern programming languages such as Pascal, C++ and Java use Static Scope. Some languages such as APL, SNOBOL4 and early versions of LISP use Dynamic Scope.

Static Scoping

Advantages Read ability Locality of reasoning Less run-time overhead

Disadvantages Some loss of flexibility

Dynamic Scoping\

Advantages Some extra convenience

25

Page 26: Unit_III

Disadvantages Loss of readability Unpredictable behavior (no locality of reasoning) More run-time overhead

$$ Local data and local referencing environment: -Local

environment of a subprogram consists various identifiers declared in the subprogram variable names, parameters, and subprogram names. For local environments, static and dynamic scope rules are easily made consistent. $$ Shared data: -

A data object that is strictly local is used by operations only within a single local referencing environment, e.g., within a single subprogram. Data object, however, often are shared among several subprograms, so that operations in each of the subprograms may use the data. A data object may be transmitted as an explicit parameter between subprograms but there are numerous occasions in which use of explicit parameters is cumbersome.

Sharing of data object through nonlocal environments is an important alternative to the use of direct sharing through parameter transmission.

Four basic approaches to nonlocal environment are in use in programming languages:

Explicit common environments and implicit nonlocal environments based on

Dynamic scope, Static Scope and Inheritance

Explicit Common Environment :-

26

Page 27: Unit_III

A common environment set up explicitly for the sharing of data objects is the most straightforward method for data sharing. A set of data objects that are to be shared among a set of subprograms is allocated storage in a separate named block. Each program contains a declaration that explicitly names the shared block. The data objects with in the block are than visible within the sub program and may be referenced by name in the usual way. Such a shared block is known by various names:COMMON block in FORTRAN;In Ada it is Form of a package;In C single Variables tagged extern are shared in this way

Specification: A common environment is identical to a local environment for a subprogram except that it is not part of any single subprogram. It may contain definitions of variable, constants, and types, but no subprograms or formal parameters.

Implementation: In FORTRAN and C, each subprogram using the common environment must also include declarations for each shared variable so that the compiler knows the relevant declarations. In Ada, the compiler is expected to retrieved the declaration for the common environment from a library or another part of the program text when a with statement is encountered during compilation of a subprogram.

$$ Parameter Passing Mechanism:

When a subprogram transfers control to another subprogram, there must be an association of the actual parameter of the calling program with the formal of the called program.Two approaches are often used: The actual parameter may be evaluated and the value passed to the formal parameter or

27

Page 28: Unit_III

The actual data object may be passed to the formal parameter. Parameter passing method differ on whether parameters are used to transmit data to the subprogram (in mode parameters), from the subprogram back to the caller (out mode parameter) or both ( inout more parameters ). Differing interpretations of what a parameter stands for lead to different parameters passing methods. Does an actual parameter P(A[j]) represent its value, its location , or the program text (A[j]) itself? Some possible interpretations are as follows:

Call by value. Pass the value of A[j] Call by reference. Pass the location of A[j] Call by name. Pass the text A[j] itself, avoiding “name

clashes”.So, parameter passing can be implemented in several ways, including:

call-by-value call-by-reference call-by-name

call-by-value-result call-by-result-and call-by-constant value

28