1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D....

58
1 COSC3306: COSC3306: Programming Programming Paradigms Paradigms Lecture 4: Imperative Lecture 4: Imperative Programming Programming Specifications Specifications Haibin Zhu, Ph.D. Haibin Zhu, Ph.D. Computer Science Computer Science Nipissing University Nipissing University (C) 2003 (C) 2003

Transcript of 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D....

Page 1: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

11

COSC3306:COSC3306:Programming ParadigmsProgramming Paradigms

Lecture 4: ImperativeLecture 4: ImperativeProgramming SpecificationsProgramming Specifications

Haibin Zhu, Ph.D.Haibin Zhu, Ph.D.Computer ScienceComputer ScienceNipissing University Nipissing University

(C) 2003(C) 2003

Page 2: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

22

ContentsContents

TaxonomyTaxonomy

Design Principles Design Principles

Control FlowsControl Flows

Execution stepsExecution steps

Undesirable CharacteristicsUndesirable Characteristics

Desirable CharacteristicsDesirable Characteristics

Page 3: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

33

Taxonomy Taxonomy

Control-driven or control-flow Control-driven or control-flow architectures:architectures:

– Reduced Instruction Set Computers (RISC).Reduced Instruction Set Computers (RISC).– Complex Instruction Set Computers (CISC).Complex Instruction Set Computers (CISC).– High-level Language Architectures (HLL).High-level Language Architectures (HLL).

Data-driven or data-flow architectures.Data-driven or data-flow architectures.

Demand-driven or reduction Demand-driven or reduction architectures.architectures.

Page 4: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

44

TaxonomyTaxonomyIn control-driven or control-flow architectures, In control-driven or control-flow architectures, – The flow of computation is determined by the instruction The flow of computation is determined by the instruction

sequence, and data are gathered as an instruction sequence, and data are gathered as an instruction needs them.needs them.

In a data-driven or data-flow architectures, In a data-driven or data-flow architectures, – It is controlled by the readiness or the availability of It is controlled by the readiness or the availability of

data.data.

In demand-driven or reduction architectures, In demand-driven or reduction architectures, – An instruction is enabled for execution when its results An instruction is enabled for execution when its results

are required as operands for another instruction that has are required as operands for another instruction that has already been enabled for execution.already been enabled for execution.

Page 5: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

55

Properties of an imperative Properties of an imperative languagelanguage

In general, a programming language that is In general, a programming language that is characterized by the following three properties is characterized by the following three properties is called an imperative language, since its primary called an imperative language, since its primary feature is a sequence of statements that feature is a sequence of statements that represent commands.represent commands.– The sequential execution of instructions,The sequential execution of instructions,– The use of variables representing memory location The use of variables representing memory location

values, andvalues, and– The use of assignment statements to change the The use of assignment statements to change the

values of variables and to allow the program to values of variables and to allow the program to operate on these memory location values.operate on these memory location values.

Page 6: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

66

Design PrinciplesDesign Principles

Imperative programming languages Imperative programming languages describe how a given sequence of describe how a given sequence of operations computes the result of a given operations computes the result of a given problem.problem.

In the imperative approach we are more In the imperative approach we are more concerned with how to formulate the concerned with how to formulate the solution in terms of our primitive solution in terms of our primitive operations.operations.

Page 7: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

77

Three categories of actionThree categories of action

Computational actions such as arithmetic Computational actions such as arithmetic operations.operations.

Control-flow actions such as comparisons Control-flow actions such as comparisons and looping statements.and looping statements.

Input-output actions such as read and Input-output actions such as read and write operations.write operations.

Page 8: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

88

Memory locationMemory location

Imperative actions all have access to a common Imperative actions all have access to a common storage which consists of an arbitrary number of storage which consists of an arbitrary number of memory locations. Each memory location can be memory locations. Each memory location can be characterized by a state as the following:characterized by a state as the following:– It may contain a data, meaning that the location is It may contain a data, meaning that the location is

allocated and containing data. allocated and containing data. – It may be undefined, meaning that the location is It may be undefined, meaning that the location is

allocated but not yet containing data.allocated but not yet containing data.– It may be unused, meaning that the location is not It may be unused, meaning that the location is not

allocated.allocated.

Page 9: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

99

Stable dataStable data

Data stored in memory locations are Data stored in memory locations are stable. In other words, data contained in a stable. In other words, data contained in a memory location remains undisturbed and memory location remains undisturbed and available for inspection until that memory available for inspection until that memory location is deallocated or has a new data location is deallocated or has a new data stored on it. An imperative action works by stored on it. An imperative action works by making changes in memory. making changes in memory.

Page 10: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1010

Possible changesPossible changes

Store data in a location. This action stores data Store data in a location. This action stores data in a memory location.in a memory location.Deallocate a memory location. This action Deallocate a memory location. This action changes the state of memory location to unused. changes the state of memory location to unused. Allocate a memory location. This action finds an Allocate a memory location. This action finds an unused memory location and changes its status unused memory location and changes its status to allocated. to allocated. Retrieve a memory location. This action yields Retrieve a memory location. This action yields the data currently contained in a memory the data currently contained in a memory location. location.

Page 11: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1111

VariablesVariables

A major component of a computer system A major component of a computer system is the memory which is comprised of a is the memory which is comprised of a large number of memory cells (locations).large number of memory cells (locations).

The memory is where the data can be The memory is where the data can be stored. stored.

The memory cells must be named. The memory cells must be named.

Page 12: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1212

Functions of variable declarationFunctions of variable declaration

In variable declaration we consider the memory In variable declaration we consider the memory locations in which the values of interest reside. The locations in which the values of interest reside. The variable declaration performs three functions as the variable declaration performs three functions as the following:following:– It allocates an area of memory of a specified size.It allocates an area of memory of a specified size.– It attaches a symbolic name to the allocated area of It attaches a symbolic name to the allocated area of

memory. This is called binding a name to memory memory. This is called binding a name to memory locations. locations.

– It initializes the contents of the memory locations if there It initializes the contents of the memory locations if there is any initialization. is any initialization.

These are three important functions of variable These are three important functions of variable declarations in most imperative programming declarations in most imperative programming languages.languages.

Page 13: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1313

Data TypesData TypesThe data type used in programming languages can The data type used in programming languages can be classified into either of two categories.be classified into either of two categories.– Scalar data type which is the simplest possible data types.Scalar data type which is the simplest possible data types.– Structured data type, in which consist of some combination Structured data type, in which consist of some combination

of scalar data types. of scalar data types.

Any data type has three associated components.Any data type has three associated components.– Type name which is the identifier used to designate the Type name which is the identifier used to designate the

type in declaration.type in declaration.– A set of constants of that type which is a symbol for a A set of constants of that type which is a symbol for a

value that may be assigned to a variable of compatible value that may be assigned to a variable of compatible type. type.

– A set of operations upon that type which are used to A set of operations upon that type which are used to construct expressions for the type. construct expressions for the type.

Page 14: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1414

Type EquivalenceType Equivalence

An important question in the application of An important question in the application of type to type checking is type equivalence, type to type checking is type equivalence, meaning that meaning that when are two types the when are two types the samesame? ?

This question can be answered in three This question can be answered in three different ways as the following.different ways as the following.

Page 15: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1515

Structural EquivalenceStructural Equivalence

Two data types are the same if they have the Two data types are the same if they have the same structure, meaning that they are built in same structure, meaning that they are built in exactly the same way using the same type exactly the same way using the same type constructors from the same simple types. In constructors from the same simple types. In other words, two sets are the same if they other words, two sets are the same if they contain the same values. For example, the contain the same values. For example, the types types t1t1 and and t2t2 defined as following are defined as following are structurally equivalent, if we were only structurally equivalent, if we were only concerned about the size of the index set.concerned about the size of the index set.

– t1 t1 array [1 . . 11] of integer; array [1 . . 11] of integer;– t2 t2 array [0 . . 10] of integer; array [0 . . 10] of integer;

Page 16: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1616

Name EquivalenceName EquivalenceTwo named types are equivalent if they have Two named types are equivalent if they have the same name. This is a stronger condition the same name. This is a stronger condition than structural equivalence, because a name than structural equivalence, because a name can refer only to a single type declaration. can refer only to a single type declaration. Name equivalence is adopted in Ada language. Name equivalence is adopted in Ada language. For example, the types For example, the types array1array1 and and array2array2 defined as follows are name equivalence; as defined as follows are name equivalence; as are are ageage and and integerinteger. .

– type array1 is array (1 . . 10) of INTEGER;type array1 is array (1 . . 10) of INTEGER;– type array2 is new array1;type array2 is new array1;– type age is new INTEGER;type age is new INTEGER;

In Ada, the keyword In Ada, the keyword newnew enforces the name enforces the name equivalence. equivalence.

Page 17: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1717

Declaration EquivalenceDeclaration Equivalence

Two type names that goes back to the Two type names that goes back to the same original structure declaration by a same original structure declaration by a series of redeclarations are considered to series of redeclarations are considered to be equivalent types. Modula-2 supports be equivalent types. Modula-2 supports declaration equivalence, where in C declaration equivalence, where in C language a mixture of structural and language a mixture of structural and declaration equivalence is used. declaration equivalence is used.

Page 18: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1818

An exampleAn example

For example, in the following declarations For example, in the following declarations name1name1, , name2name2, and , and name3name3 are all declaration are all declaration equivalent, but not name equivalent.equivalent, but not name equivalent.

– typetype– name1 name1 array[1 . . 10] of integer; array[1 . . 10] of integer;– name2 name2 name1; name1;– name3 name3 name2; name2;

Similarly, in the following Modula-2 declaration Similarly, in the following Modula-2 declaration x and y are declaration equivalent variables. x and y are declaration equivalent variables.

– VARVAR x, y : ARRAY[1 . . 10] of INTEGER;x, y : ARRAY[1 . . 10] of INTEGER;

Page 19: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

1919

Assignment StatementsAssignment Statements

The notion that every value computed must be assigned The notion that every value computed must be assigned to a memory location is performed by an assignment to a memory location is performed by an assignment statement. For example, the following assignment statement. For example, the following assignment statement is a typical action in which it changes the value statement is a typical action in which it changes the value of a variable (memory location value) known as of a variable (memory location value) known as classclass. .

class class 10; 10;The assignment symbol “The assignment symbol “” appears between the right ” appears between the right and left sides. This assignment statement sets and left sides. This assignment statement sets classclass to to 10 and the old value of 10 and the old value of classclass is discarded. is discarded. A similar example is the following assignment statementA similar example is the following assignment statement

class class 4 45;5;where the value 9 of the expression 4where the value 9 of the expression 45 is assigned as 5 is assigned as the value of the value of classclass variable by ignoring the old value of variable by ignoring the old value of variable. variable.

Page 20: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2020

Operand EvaluationOperand Evaluation

An important design characteristic is the order of An important design characteristic is the order of evaluation of operands in expressions. evaluation of operands in expressions. For example, in the following expressionFor example, in the following expression

A A 10; 10;B B A A 10; 10;

the value of B is computed by taking the content the value of B is computed by taking the content of a memory location associated with variable A, of a memory location associated with variable A, thus B takes the value as 20. If an operand is a thus B takes the value as 20. If an operand is a parenthesized expression, then all operators it parenthesized expression, then all operators it contains must be evaluated before its value to contains must be evaluated before its value to be used as an operand.be used as an operand.

Page 21: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2121

Another exampleAnother example

For example, in the evaluation of the following For example, in the evaluation of the following expressionexpression

A A 10; 10;B B 20; 20;C C (A (A B) B) 10; 10;

the value of C is computed by evaluating the the value of C is computed by evaluating the value of the subexpression (Avalue of the subexpression (AB), in which two B), in which two operands A and B and one operator “operands A and B and one operator “” are ” are involved. Thus C takes the value 30involved. Thus C takes the value 3010 as the 10 as the computed value.computed value.

Page 22: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2222

Side EffectsSide Effects

The important issue in imperative programming The important issue in imperative programming language design is the side effects from the language design is the side effects from the evaluation of the expressions. If neither of the evaluation of the expressions. If neither of the operands of an operator has side effects then operands of an operator has side effects then operand evaluation order is irrelevant.operand evaluation order is irrelevant.For example, there is no side effects associated For example, there is no side effects associated with the evaluation of the following with the evaluation of the following subexpressions of the expression. subexpressions of the expression.

A A 10; 10;B B 20; 20;C C (A (A 5) 5) (B (B 10); 10);

Page 23: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2323

An exampleAn example

In contrast, sometimes the evaluation of an In contrast, sometimes the evaluation of an operand has side effects.operand has side effects.For example, the following C expression For example, the following C expression illustrates the situation where the stored value of illustrates the situation where the stored value of A in memory to be increased by 10 first, and the A in memory to be increased by 10 first, and the second subexpression then taking this new second subexpression then taking this new stored value as its value.stored value as its value.In this example, the side effect of the evaluation In this example, the side effect of the evaluation of the first subexpression causes the value of B of the first subexpression causes the value of B to be evaluated to 50. to be evaluated to 50.

A A 10; 10;B B (A (A A A 10) + (A 10) + (A 10); 10);

Page 24: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2424

To be continuedTo be continued

Control constructsControl constructs

Functions and ProceduresFunctions and Procedures

Control FlowsControl Flows

Execution StepsExecution Steps

Undesirable Characteristics Undesirable Characteristics

Desirable Characteristics Desirable Characteristics

Page 25: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2525

Selection ConstructsSelection Constructs

An array data structure supports random access to a An array data structure supports random access to a sequence of elements of the same type. sequence of elements of the same type. Random access means that elements can be selected Random access means that elements can be selected by their position in the data structure. An assignmentby their position in the data structure. An assignment

x x A[i]; A[i];assigns to x the value of the assigns to x the value of the iith element of array A. The th element of array A. The assignmentassignment

A[i] A[i] x; x;changes the value of changes the value of iith element of array A to x.th element of array A to x.Occasionally an algorithm will contain a series of Occasionally an algorithm will contain a series of decisions in which a variable or expression is tested decisions in which a variable or expression is tested separately for each of the constant integral values it may separately for each of the constant integral values it may assume, and different actions must be takes. assume, and different actions must be takes.

Page 26: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2626

ExamplesExamples

One way of making such an effect is by One way of making such an effect is by using a list of if statements such as:using a list of if statements such as:

ifif (condition1)(condition1) action1;action1;ifif (condition2)(condition2) action2;action2;......ifif (conditionN)(conditionN) actionN;actionN;

Page 27: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2727

ExamplesExamples

For example, consider the following codeFor example, consider the following code

ifif A A B B

Sum Sum Sum Sum A; A;

Acount Acount Acount Acount 1; 1;

ifif B B A A

Sum Sum Sum Sum B; B;

Bcount Bcount Bcount Bcount 1; 1;

Page 28: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2828

AlternativesAlternativesAn alternative is the An alternative is the switchswitch multi-selection structure to handle such decision multi-selection structure to handle such decision making.making.

switchswitch (expression)(expression){{case 1:case 1: action1;action1;

break;break;case 2:case 2: action2;action2;

break;break;......case N:case N: actionN;actionN;

break;break;default:default: actionX;actionX;

break;break;}}

Page 29: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

2929

Basic issuesBasic issues

Selection structures vary from language to Selection structures vary from language to language, but they tend to agree on the language, but they tend to agree on the following issues.following issues.– Case selections can appear in any order.Case selections can appear in any order.– Case selections are not required to be Case selections are not required to be

consecutive, meaning that it is valid to have consecutive, meaning that it is valid to have case-1 and case-4 without case-2 and case-3. case-1 and case-4 without case-2 and case-3.

– Case selections must be distinct with regard Case selections must be distinct with regard to actions of each case; otherwise we need to to actions of each case; otherwise we need to combine the actions to avoid any conflict.combine the actions to avoid any conflict.

Page 30: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3030

Conditional ConstructsConditional Constructs

A conditional statement as the following formA conditional statement as the following formifif expressionexpression thenthen statement1statement1 elseelse

statement2statement2control flows through statement1 or statement2 if control flows through statement1 or statement2 if expression is true or false, respectively. A variant of this expression is true or false, respectively. A variant of this conditional statement isconditional statement is

ifif expressionexpressionthenthen statementstatementwith no else component. In this form, the with no else component. In this form, the statementstatement is is executed only if expression is true. The conditionals can executed only if expression is true. The conditionals can be nested as the following general form. be nested as the following general form.

ifif expression1expression1 then then statement1statement1elseelse ifif expression2expression2 then then statement2statement2

elseelse ifif expression3expression3 then thenstatement3statement3

elseelse . . .. . .

Page 31: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3131

Looping ConstructsLooping Constructs

A program in an imperative programming A program in an imperative programming language usually performs its task by executing language usually performs its task by executing a sequence of elementary steps repeatedly.a sequence of elementary steps repeatedly.– Looping constructs can be classified into two Looping constructs can be classified into two

categories as the following:categories as the following:– Definite iteration loops in which the number of Definite iteration loops in which the number of

iterations is predetermined when control flows through iterations is predetermined when control flows through construct.construct.

Indefinite iteration loops in which the number of Indefinite iteration loops in which the number of iterations is not known when control flows iterations is not known when control flows through construct. through construct.

Page 32: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3232

Looping ConstructsLooping Constructs

In other words, the looping constructs are In other words, the looping constructs are divided depending upon whether or not we can divided depending upon whether or not we can predict the number of times the loop will be predict the number of times the loop will be executed. The syntax for indefinite iteration executed. The syntax for indefinite iteration construct is as the followingconstruct is as the following

whilewhile conditional-expressionconditional-expressiondodo statementstatement

where the control flows through the execution of where the control flows through the execution of the the statementstatement which is called the body of the which is called the body of the construct as soon as the construct as soon as the conditional-expressionconditional-expression is evaluated to true. is evaluated to true.

Page 33: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3333

Looping ConstructsLooping Constructs

In the following the loop is executed with In the following the loop is executed with indexindex taking the values 0, 1, 2, … , 9 in order to taking the values 0, 1, 2, … , 9 in order to initialize the corresponding array element with initialize the corresponding array element with zero.zero.

index index 0; 0;whilewhile (index (index 10) 10)

{{A[index] A[index] 0; 0;index index index index 1; 1;}}

Page 34: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3434

Looping ConstructsLooping Constructs

The syntax for definite iteration construct is as the The syntax for definite iteration construct is as the followingfollowing

forfor (expression1;(expression1; expression2;expression2;expression3)expression3)

body-of-loop;body-of-loop;where control flows through the execution of the body-of-where control flows through the execution of the body-of-loop depending upon the value of the expression2. For loop depending upon the value of the expression2. For example, in the followingexample, in the following

forfor (index (index 0; 0; index index 10; 10; indexindex))A[index] A[index] 0; 0;

the assignment A[index] the assignment A[index] 0; is executed with 0; is executed with indexindex taking the values 0, 1, 2, … , 9 on successive taking the values 0, 1, 2, … , 9 on successive executions.executions.

Page 35: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3535

UnionsUnions

We can construct a union of two types, in which We can construct a union of two types, in which can be formed by taking the set theoretic union can be formed by taking the set theoretic union of their sets of values. Union type come in two of their sets of values. Union type come in two varieties.varieties.– Discriminated Unions:Discriminated Unions: If a tag or discriminator is If a tag or discriminator is

added to each element field to distinguish which type added to each element field to distinguish which type the element is. the element is.

– Undiscriminated Unions:Undiscriminated Unions: It lack the tag, and It lack the tag, and assumptions must be made about the type of any assumptions must be made about the type of any particular element.particular element.

A language adopted discriminated and A language adopted discriminated and undiscriminated union is Modula-2, and C is a undiscriminated union is Modula-2, and C is a language adopted undiscriminated union.language adopted undiscriminated union.

Page 36: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3636

Functions and ProceduresFunctions and Procedures

Despite their distinct roles as operators and actions, Despite their distinct roles as operators and actions, functions and procedures are very similar to each other. functions and procedures are very similar to each other. The only difference between them is that functions return The only difference between them is that functions return a result and procedures do not. No wonder one a result and procedures do not. No wonder one language such as C calls them both as functions and language such as C calls them both as functions and another language such as Modula-2 calls them both another language such as Modula-2 calls them both procedures. In general, a procedure or function procedures. In general, a procedure or function declaration defines the components as:declaration defines the components as:– A name for the declared procedure or function.A name for the declared procedure or function.– The formal parameters which are placeholders for input and The formal parameters which are placeholders for input and

output.output.– A body consisting of local declarations and statements.A body consisting of local declarations and statements.– An optional result type to address the data type of the returned An optional result type to address the data type of the returned

result.result.

Page 37: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3737

Control FlowControl Flow

Statement-Oriented Statement-Oriented Block-Oriented Block-Oriented – Localize changesLocalize changes– Correct assumptions at the beginning and the Correct assumptions at the beginning and the

endend– No need to concern about conflicts namesNo need to concern about conflicts names– Facilitate organization of a programFacilitate organization of a program– Explicit control information to descendant Explicit control information to descendant

blocksblocks

Page 38: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3838

Figure 6.1 Control flows through a sequence of statements

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 39: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

3939

Figure 6.2 Control flows through a block

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 40: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4040

Execution Steps for Imperative Execution Steps for Imperative ProgrammingProgramming

An imperative program goes through An imperative program goes through several stages in order to be executed. several stages in order to be executed. – Compilation-linking-loading-executionCompilation-linking-loading-execution

Compilation:Compilation: This process translates the This process translates the program into a program into a relocatable object coderelocatable object code, , meaning that the program and all meaning that the program and all individual subprograms are translated into individual subprograms are translated into an intermediate code compatible with the an intermediate code compatible with the computer system. computer system.

Page 41: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4141

Execution Steps for Imperative Execution Steps for Imperative ProgrammingProgramming

Linking:Linking: This process incorporates the necessary This process incorporates the necessary libraries into the program. These libraries libraries into the program. These libraries associated with subprograms are already associated with subprograms are already programmed, debugged and compiled. The goal of programmed, debugged and compiled. The goal of linking process is to obtain a relocatable object linking process is to obtain a relocatable object code containing of all parts of the program including code containing of all parts of the program including all library references satisfied. all library references satisfied. Loading:Loading: This is the process that a relocatable This is the process that a relocatable code is placed in memory for execution. This code is placed in memory for execution. This process requires converting relocatable object code process requires converting relocatable object code to absolute format for execution. to absolute format for execution. Execution:Execution: This is the process that the control This is the process that the control flows through the execution of the statements of the flows through the execution of the statements of the program. program.

Page 42: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4242

Figure 6.3 The Compile-Link-Load-Execute steps of program execution

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 43: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4343

Undesirable Characteristics for Undesirable Characteristics for Imperative ProgrammingImperative Programming

Difficulty in ReasoningDifficulty in Reasoning– The correctness of a program depends on the The correctness of a program depends on the

contents of each and every memory location. contents of each and every memory location.

Referential TransparencyReferential Transparency

Side EffectsSide Effects

Indiscriminate AccessIndiscriminate Access

Vulnerability AccessVulnerability Access

No Overlapping DefinitionsNo Overlapping Definitions

Page 44: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4444

Referential TransparencyReferential Transparency

A system is referentially transparent if the meaning of the A system is referentially transparent if the meaning of the whole can be determined solely from the meaning of its whole can be determined solely from the meaning of its components.components.For example, in a mathematical expression such as For example, in a mathematical expression such as F(x)F(x)G(x), we may substitute another function H for F, if G(x), we may substitute another function H for F, if we know that it produces the same values as F.we know that it produces the same values as F.In imperative programming languages we are not In imperative programming languages we are not assured of this, because the meaning of the expression assured of this, because the meaning of the expression depends on the history of computation of the depends on the history of computation of the subexpressions.subexpressions.Indeed, if F or G change the value of their parameter or Indeed, if F or G change the value of their parameter or modify some global variables, we are not even certain modify some global variables, we are not even certain that F(x)that F(x)G(x) G(x) G(x) G(x)F(x). F(x).

Page 45: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4545

Side EffectsSide Effects

Imperative programming supports imperative operations Imperative programming supports imperative operations that are performed not to obtain a value but rather for that are performed not to obtain a value but rather for some side effect on the computations.some side effect on the computations.For example, operators like For example, operators like or or in C language have in C language have side effects, meaning that besides returning a value they side effects, meaning that besides returning a value they also modify an underlying variable.also modify an underlying variable.Side effects can be convenient but they can also cause Side effects can be convenient but they can also cause trouble, because the actions of retrieving the value and trouble, because the actions of retrieving the value and updating the variable might not happen at the same time, updating the variable might not happen at the same time, one at the time of expression evaluation and one at the one at the time of expression evaluation and one at the termination of the execution.termination of the execution.

Page 46: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4646

Side EffectsSide Effects

Consider Consider – class_list[indexclass_list[index] ] class_list[index class_list[index] ]

0; 0;

In this statement, the intent is to store zero In this statement, the intent is to store zero at the two consecutive positions in array.at the two consecutive positions in array.

But depending on when index is updated, But depending on when index is updated, a position in array could be skipped and a position in array could be skipped and index might be increased only by 1. index might be increased only by 1. (sideeffect2.cpp)(sideeffect2.cpp)

Page 47: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4747

Indiscriminate AccessIndiscriminate Access

The problem of indiscriminate access is The problem of indiscriminate access is that, programmers can not prevent that, programmers can not prevent inadvertent access to variables or data inadvertent access to variables or data structures. structures.

For example, suppose we want to provide For example, suppose we want to provide a stack to be used in an Algol program. a stack to be used in an Algol program. We would probably design the program as We would probably design the program as the following.the following.

Page 48: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4848

An example of AlgolAn example of Algolbeginbegin

integerinteger arrayarray S[1:100];S[1:100];integerinteger TOP;TOP;procedureprocedure PUSH(x);PUSH(x);

integerinteger x;x;beginbeginTOP TOP TOP TOP1;1;S[TOP]S[TOP]x;x;

end;end;procedureprocedure POP(x);POP(x);

integerinteger x;x;beginbeginPOP POP S[TOP]; S[TOP];TOP TOP TOP TOP1;1;

end;end;TOP TOP 0;0;. . . . . . uses of PUSH and POPuses of PUSH and POP . . . . . .

end;end;

Page 49: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

4949

ExplanationExplanation

In this case, the variable S which is the stack In this case, the variable S which is the stack must be declared in the same block as PUSH must be declared in the same block as PUSH and POP so that it is visible from the bodies of and POP so that it is visible from the bodies of PUSH and POP procedures.PUSH and POP procedures.In addition, for the PUSH and POP procedures In addition, for the PUSH and POP procedures to be visible to their users, they must be to be visible to their users, they must be declared in a block that contains all users. In this declared in a block that contains all users. In this example, there is no guarantee that all users of example, there is no guarantee that all users of the stack go through the PUSH and POP the stack go through the PUSH and POP procedures in order to manipulate the data procedures in order to manipulate the data structure. structure.

Page 50: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5050

Vulnerability AccessVulnerability AccessThe problem of vulnerability access is that, under certain The problem of vulnerability access is that, under certain circumstances it is impossible to preserve access to a variable. circumstances it is impossible to preserve access to a variable. Consider a very large Algol program. Consider a very large Algol program.

beginbeginintegerinteger x;x;. . . . . . . . many lines of codemany lines of codebeginbegin

. . . . . . . . many lines of codemany lines of codex x x x 1; 1;. . . . . . . . many lines of codemany lines of code

end;end;. . . . . . . . many lines of codemany lines of code

end;end;

In this example, we are supposing that there are so many lines In this example, we are supposing that there are so many lines of code between the definition and use of x variable. Let’s of code between the definition and use of x variable. Let’s further suppose that in the process of maintaining this program further suppose that in the process of maintaining this program we decide that we need a new local variable in the inner block.we decide that we need a new local variable in the inner block.

Page 51: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5151

Change a little bitChange a little bitIf we pick x without realizing that it was already used in that block, it results If we pick x without realizing that it was already used in that block, it results the following program.the following program.

beginbeginintegerinteger x;x;. . . . . . . . many lines of codemany lines of codebeginbegin

real x;real x;. . . . . . . . many lines of codemany lines of codex x x x 1; 1;. . . . . . . . many lines of codemany lines of code

end;end;. . . . . . . . many lines of codemany lines of codeend;end;

In this case, with this modification access to the outer declaration of integer In this case, with this modification access to the outer declaration of integer x has been blocked and the statement x x has been blocked and the statement x x x 1 now refers to the new real 1 now refers to the new real variable x. In other words, the new declaration of x has been interposed variable x. In other words, the new declaration of x has been interposed between the original definition of x and its use. Thus, the problem of between the original definition of x and its use. Thus, the problem of vulnerability access is the inability to preserve access to a variable. vulnerability access is the inability to preserve access to a variable.

Page 52: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5252

No Overlapping DefinitionsNo Overlapping Definitions

The problem of no overlapping definitions The problem of no overlapping definitions is the inability to control shared access to is the inability to control shared access to variables. variables.

As a consequence, it creates both a As a consequence, it creates both a maintenance and security problem. maintenance and security problem.

Page 53: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5353

Figure 6.4 Overlapping structures in a program

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 54: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5454

Desirable Characteristics for Desirable Characteristics for Imperative ProgrammingImperative Programming

Some of the issues involved in good Some of the issues involved in good programming can be outlined.programming can be outlined.No Implicit InheritanceNo Implicit Inheritance– The default should not be to extend the scope of a The default should not be to extend the scope of a

variable to inner block. variable to inner block.

Distinguish Access to Data StructuresDistinguish Access to Data Structures– It should be possible to distinguish different data It should be possible to distinguish different data

types of access. types of access.

Decoupling DeclarationsDecoupling Declarations– Declaration of definition, name access and allocation Declaration of definition, name access and allocation

should be decoupled. should be decoupled.

Page 55: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5555

Desirable Characteristics for Desirable Characteristics for Imperative ProgrammingImperative Programming

Natural Form for ExpressionsNatural Form for Expressions– Write expressions as you might make them Write expressions as you might make them

understanding.understanding. if (!(block_id<block_1)||!(block_id>=block_2)) if (!(block_id<block_1)||!(block_id>=block_2))

oror

if ( (block_id>=block_1)|| (block_id<block_2)) if ( (block_id>=block_1)|| (block_id<block_2))

Which is better?Which is better?

Page 56: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5656

Parenthesize to Resolve Parenthesize to Resolve AmbiguityAmbiguity

Parentheses specify grouping and can be Parentheses specify grouping and can be used to make the intention more clear used to make the intention more clear even when they are not required.even when they are not required.– if (*&MASK ==BITS)if (*&MASK ==BITS)– if (*&(MASK ==BITS))if (*&(MASK ==BITS))

– if ((*&MASK) ==BITS)if ((*&MASK) ==BITS)– if (MASK ==BITS)if (MASK ==BITS)

Page 57: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5757

Break up Complex ExpressionsBreak up Complex Expressions

– The statement is more easy to understand The statement is more easy to understand when is broken into several pieces.when is broken into several pieces.

*ptra+=(*ptrb = (2*index<(index_1-index_2)?*ptra+=(*ptrb = (2*index<(index_1-index_2)?

array1[index++]:array2[index--])array1[index++]:array2[index--])

If (2*index<(index_1-index_2)If (2*index<(index_1-index_2)*ptrb=array1[index++];*ptrb=array1[index++];elseelse*ptrb=array2[index--];*ptrb=array2[index--];*ptra+=*ptrb;*ptra+=*ptrb;

Page 58: 1 COSC3306: Programming Paradigms Lecture 4: Imperative Programming Specifications Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

5858

SummarySummary

TaxonomyTaxonomy

Design Principles Design Principles

Control constructsControl constructs

Execution stepsExecution steps

Undesirable CharacteristicsUndesirable Characteristics

Desirable CharacteristicsDesirable Characteristics