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

New_Unit 2

Uploaded by

anaghasalunke44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

New_Unit 2

Uploaded by

anaghasalunke44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 264

SNJB’s Late Sau. K. B. J.

College of Engineering

SE Computer
Course Name :Principles of Programming Language
Course Code: 210255
Course InCharge: Kainjan M. Sanghavi

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Unit 2
Structuring the Data, Computations and Program
● Elementary Data Types : Primitive data Types, Character String types, User Defined Ordinal Types,
Array types, Associative Arrays, Record Types, Union Types, Pointer and reference Type.
● Expression and Assignment Statements: Arithmetic expression, Overloaded Operators, Type
conversions, Relational and Boolean Expressions, Short Circuit Evaluation, Assignment Statements,
Mixed mode Assignment.
● Statement level Control Statements: Selection Statements, Iterative Statements, Unconditional
Branching.
● Subprograms: Fundamentals of Sub Programs, Design Issues for Subprograms, Local referencing
Environments, Parameter passing methods. Abstract Data Types and Encapsulation Construct: Design
issues for Abstraction, Parameterized Abstract Data types, Encapsulation Constructs, Naming
Encapsulations
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering

Topic Book To Refer

Elementary Data Types : Primitive data Sebesta R., "Concepts of Programming


Languages", 4th Edition, Pearson
Types, Character String types, User
Education, ISBN-
Defined Ordinal Types, Array types, 81-7808-161-X.
Associative Arrays, Record Types, Union Page No : 267 - 323
Types, Pointer and reference Type.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering

Topic Book To Refer

Expression and Assignment Sebesta R., "Concepts of Programming


Languages", 4th Edition, Pearson
Statements: Arithmetic expression,
Education, ISBN-
Overloaded Operators, Type conversions, 81-7808-161-X.
Relational and Boolean Expressions, Short Page No : 330-355
Circuit Evaluation, Assignment
Statements, Mixed mode Assignment.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering

Topic Book To Refer

Statement level Control Statements: Sebesta R., "Concepts of Programming


Languages", 4th Edition, Pearson
Selection Statements, Iterative
Education, ISBN-
Statements, Unconditional Branching. 81-7808-161-X.
Page No : 362-390

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering

Topic Book To Refer

Subprograms: Fundamentals of Sub Sebesta R., "Concepts of Programming


Languages", 4th Edition, Pearson
Programs, Design Issues for Subprograms,
Education, ISBN-
Local referencing Environments, 81-7808-161-X.
Parameter passing methods. Page No : 402-436

Abstract Data Types and Encapsulation Sebesta R., "Concepts of Programming


Languages", 4th Edition, Pearson
Construct: Design issues for Abstraction,
Education, ISBN-
Parameterized Abstract Data types, 81-7808-161-X.
Encapsulation Constructs, Naming Page No : 492, 508-521
Encapsulations

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Data type: A data type defines a


collection of data values and
a set of predefined operations on
those values

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Elementary Data Types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Primitive Data Types

● Primitive data types are those that are not defined in terms of other data types
● These are not built from other types
● These are atomic and cannot be decomposed further
● Some of the data types are merely reflections of the hardware - for eq. Integer
types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Primitive Data Types


● Early PLs had only numeric primitive types, and still play a central role among
the collections of types supported by contemporary languages.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Numerical Data Types …Integer

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Numerical Data Types …Floating Point

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Numerical Data Types …Floating Point


Newer Machines Use IEEE (The Institute of Electrical and Electronics Engineers)
floating-point formats: (a) Single precision, (b) Double precision

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Numerical Data Types …Floating Point

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Numerical Data Types …Decimal


Define a variable with a fixed-precision and decimal point;
for example, a monetary value such as a bank balance.
● Advantage
A decimal descriptor for the integer length of the decimal
○ Accuracy
variable
● Disadvantages:
For example, code d : Decimal [4]; to specify a length of 4.
○ Limited range
Also the number of decimal places for the decimal variable
○ Wastes memory
can be specified; for example, code d : Decimal [4,3]; to
specify that the variable is to be to three decimal places.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Boolean Types

Advantage:
Readability

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character Types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types


● Character string type is one in which the values consist of sequences of characters

● Design issues with the string types

○ Should strings be simply a special kind of character array or a

primitive type?

○ Should strings have static or dynamic length?

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types …. String Operations

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types.. String Length Options

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types


● C and C++
○ not primitive
○ use char arrays and a library of functions that provide operations
● Java : String class (not arrays of char)
○ objects are immutable
○ StringBuffer is a class for changeable string objects
○ String length options
● Static – Python, Java’s String class, C++ standard class library, Ruby’s built-in String
class, and the .NET class library in C# and F#.
● Limited dynamic length – C and C++ ( up to a max length indicated by a null character)
● Dynamic –Perl, JavaScript

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types …Implementation


● Static length - Compile-time descriptor is required with three field

● Limited dynamic length - may need a run-time descriptor for storing length (but not

in C and C++ because the end of a string is marked with the null character)

● Dynamic length - need complex storage management. Length of string is not fixed ,

hence storage grows or shrinks dynamically

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types …Implementation

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types …Implementation


Dynamic length allocation by three approaches:

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types …Implementation

Dynamic length allocation by three approaches:

● First approach :
○ Using linked list
○ Disadvantage - Extra storage for links and complexity of operations
● Second approach :
○ Store as array of pointers to individual characters allocated in a heap.
○ Disadvantage- Still uses extra memory

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Character String Types …Implementation

● Third approach:
○ To store complete strings in adjacent storage cells
○ When a string grows and adjacent storage is not available, a new area of memory
is found that can store the complete new string and the old part is moved to this
area, and the memory cells for the old string are deallocated.
○ This results in faster string operations and requires less storage
○ Disadvantage : = Allocation / deallocation process is slower.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

User Defined Ordinal Types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

An ordinal type is one in


which the range of
possible values can be
easily associated with
the set of positive
integers

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types
● All possible values, which are named constants, are provided in the definition
● C# example
enum days {mon, tue, wed, thu, fri, sat, sun};
● The enumeration constants are typically implicitly assigned the integer values, 0, 1, …, but
can be explicitly assigned any integer literal in the type’s definition
Design issues

● Is an enumeration constant allowed to appear in more than one type definition, and if so,
how is the type of an occurrence of that constant checked?
● Are enumeration values coerced to integer?
● Any other type coerced to an enumeration type?

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types
● In languages that do not have enumeration types, programmers usually simulate them with
integer values.
● E.g. Fortran 77, use 0 to represent blue and 1 to represent red:

INTEGER RED, BLUE

DATA RED, BLUE/0,1/

● Problem:
○ There is no type checking when they are used.
○ It would be legal to add two together. Or they can be assigned any integer value thus
destroying the relationship with the colors.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types-Design
● In C++, we could have

enum colors {red, blue, green, yellow, black};

○ colors myColor = blue, yourColor = red;


● The enumeration values are coerced to int when they are put in integer context.

E.g. myColor++ would assign green to myColor.

● In Java, all enumeration types are implicitly subclasses of the predefined class Enum. They
can have instance data fields, constructors and methods.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types-Design
Java Example
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Monday");

dayNames.add("Friday");
days = dayNames.elements();
while (days.hasMoreElements())
System.out.println(days.nextElement());

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types-Design
● C# enumeration types are like those of C++ except that they are never coerced to integer.
● Operations are restricted to those that make sense.
● The range of values is restricted to that of the particular enumeration type.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types- Evaluation

● Aid to readability, e.g., no need to code a color as a number


● Aid to reliability, e.g., compiler can check: operations (don’t allow colors to be added)
● No enumeration variable can be assigned a value outside its defined range,
○ e.g. if the colors type has 10 enumeration constants and uses 0 .. 9 as its internal
values, no number greater than 9 can be assigned to a colors type variable.
● Ada, C#, and Java 5.0 provide better support for enumeration than C++ because
enumeration type variables in these languages are not coerced into integer types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Enumeration Types- Evaluation


● C treats enumeration variables like integer variables; it does not provide either of the two
advantages.
● C++ is better. Numeric values can be assigned to enumeration type variables only if they are
cast to the type of the assigned variable. Numeric values are checked to determine in they are in
the range of the internal values. However if the user uses a wide range of explicitly assigned
values, this checking is not effective.
○ E.g. enum colors {red = 1, blue = 100, green = 100000}
○ A value assigned to a variable of colors type will only be checked to determine whether it
is in the range of 1..100000.
● Java 5.0, C# and Ada are better, as variables are never coerced to integer types

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

An ordinal type is one in


which the range of
possible values can be
easily associated with
the set of positive
integers

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subrange Type
An ordered contiguous subsequence of an Ada’s design
ordinal type type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
● Not a new type, but a restricted subtype Weekdays is Days range Mon..Fri;
existing type subtype Index is Integer range 1..100;
Day1: Days;
Example: 12..18 is a subrange of
Day2: Weekday;
integer type
Day2 := Day1; //legal if Day1 is not set to Sat or
Introduced by Pascal and included in Sun
Ada

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Subrange Type -Evaluation
● Aid to readability
○ Make it clear to the readers that variables of subrange can store only
certain range of values
● Reliability
○ Assigning a value to a subrange variable that is outside the specified
range is detected as an error.

Implementation of User-Defined Ordinal Types


● Enumeration types are implemented as integers
● Subrange types are implemented like the parent types with code inserted (by the
compiler) to restrict assignments to subrange variables

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Array Type
An array is an aggregate of homogeneous data elements in which an individual
element is identified by its position in the aggregate, relative to the first
element.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Array Type- Design Issues


● What types are legal for subscripts?
● Are subscripting expressions in element references range checked?
● When are subscript ranges bound?
● When does allocation take place?
● Are ragged or rectangular multi dimensioned arrays allowed, or both?
● Can arrays be initialized when they have their storage allocated?
● Are any kind of slices allowed?

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Array and Indexes


● Indexing (or subscripting) is a mapping from indices to element
○ array_name (index_value_list) -> element
● Index Syntax
○ FORTRAN, PL/I, Ada use parentheses , Sum-:= Sum +B(I);
○ Ada explicitly uses parentheses to show uniformity between array references and
function calls because both are mappings
○ Most other languages use brackets
○ E.g. List(27) direct reference to the List array’s element with the subscript 27.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Array and Indexes

Language Index Type

FORTRAN , C, Java Integer

PASCAL Any Ordinal Type


(Integer, Boolean, Enumeration,
Character)

Ada Integer Or Enumeration


Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Array and Indexes


● C, C++, Perl, and Fortran do not specify range checking
● Java, ML, C# specify range checking

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subscript Bindings and Array Categories


● Binding is usually static
● Subscript value ranges are dynamically bound
● Lower bound are implicit
● In C based languages- lower bound of all index ranges is fixed at 0;
● Fortran 95 defaults to 1
● In some other languages, ranges must be completely specified by the programmer
● Array occurs in 5 categories

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Flip ClassRoom Activity Memory Allocation :


Stack and Heap Gap Analysis

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Memory Allocation : Stack and Heap Gap Analysis

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Memory Allocation : using Stack Gap Analysis

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Memory Allocation : using Heap Gap Analysis

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Categories of Arrays

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Categories of Arrays

● Static: subscript ranges are statically bound and storage allocation is static
(before run‐ time)
● Advantage: efficiency (no dynamic allocation/deallocation required)
● Example: In C and C++ arrays that include the static modifier are static
○ static int myarray[3] = {2, 3, 4};
● int static_array[7];

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subscript Bindings and Array Categories fixed stack‐dynamic


● subscript ranges are statically bound, but the allocation is done at declaration time
● Advantage: space efficiency
● Example: arrays without static modifier are fixed stack ‐dynamic
● int array[3] = {2, 3, 4};
● E.g. void foo()
{
int fixed_stack_dynamic_array[7];
/* ... */
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subscript Bindings and Array Categories Stack‐dynamic


● Stack‐dynamic: subscript ranges are dynamically bound and the storage
allocation is dynamic (done at run‐ time)
● Advantage: flexibility (the size of an array need not be known until the array is to
be used)
void foo(int n)
● Example: In Ada, you can use stack‐dynamic arrays as {
int stack_dynamic_array[n];
Get(List_Len);
declare List: array (1..List_Len) of Integer /* ... */ }

begin ... end;

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subscript Bindings and Array Categories fixed heap_dynamic_array


● similar to fixed stack‐ dynamic: storage binding is dynamic but fixed after
allocation (i.e., binding is done when requested & storage is allocated from heap,
not stack)
● Example: In C/C++, using malloc/free to allocate/deallocate memory from the
heap
● Java has fixed heap dynamic arrays int *
● C# includes a second array class ArrayList that fixed_heap_dynamic_arr
provides fixed heap‐dynamic ay = malloc(7 *
sizeof(int));

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subscript Bindings and Array Categories heap_dynamic_array


● Binding of subscript ranges and storage allocation is dynamic and can change
any number of times
● Advantage: flexibility (arrays can grow or shrink during program execution)
● Examples: Perl, JavaScript, Python, and Ruby support heap‐dynamic arrays
● Perl: @states = (“Idaho",“Washington",“Oregon");
● Python: a = [1.25, 233, 3.141519, 0, ‐1]

void foo(int n) {
int * heap_dynamic_array = malloc(n * sizeof(int));
}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Static int static_array[7];

void foo()
fixed stack‐dynamic
{ int fixed_stack_dynamic_array[7]; }

void foo(int n)
Stack‐dynamic
{ int stack_dynamic_array[n];}

int * fixed_heap_dynamic_array = malloc(7 * sizeof(int));


fixed heap_dynamic_array

void foo(int n)
heap_dynamic_array
{ int * heap_dynamic_array = malloc(n * sizeof(int)); }

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Subscript Bindings and Array Categories

int a[5];

void f() { int a[7];}

void f(int n) { int a[n];}

int * f = malloc(7 * sizeof(int));

void f(int n) { int * a = malloc(n *


sizeof(int)); }

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Array Initialization
Some language allow initialization at the time of storage allocation

● Fortran
List (3) Data List /0, 5, 5/ // List is initialized to the values
● C, C++, Java, C# example
int list [] = {4, 5, 7, 83}
● Character strings in C and C++
char name [] = “freddie”; // eight elements, including last element as null
character
● Arrays of strings in C and C++
char *names [] = {“Bob”, “Jake”, “Joe”];
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Array Initialization
● Some language allow initialization at the time of storage allocation

● Java initialization of String objects


String[] names = {“Bob”, “Jake”, “Joe”};
● Ada positions for the values can be specified:
List : array (1..5) of Integer := (1, 3, 5, 7, 9);
Bunch : array (1..5) of Integer:= (1 => 3, 3 => 4, others => 0);
Note: the array value is (3, 0, 4, 0, 0)
● Concatenation. One array can be appended to another array using the & operator provided that they are of the same type.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Array Operations
Language Array Operation

C-based No Operations , only through methods

C#, Perl Array Assignments

Ada Assignment, Concatenation(&), Comparison

Python Concatenation(+), Element


Membership(in), Comparison(==, is)

FORTRAN Matrix Multiplication, Transpose

APL(Most powerful) +.* ( (First multiply then Add)

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Rectangular and Jagged Arrays

Language supported: Language supported:


● Fortran ● Java
● Ada ● C
● C# ● C++
● C#
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Slice

● A slice is some substructure of an array; nothing more than a


referencing mechanism
● Slices are only useful in languages that have array operations

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Slice

● Fortran Declaration:
○ Vector(3:6) Four element from third to sixth
● Python Declaration
○ A =[10,20,30,40,50,60]
■ A[1:4] [10,20,30]
■ A[:5] [10,20,30,40,50]
■ A[4:] [50,60]
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Compile-Time Descriptors

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array

● An associative array is an unordered collection of data elements


that are indexed by an equal number of values called keys
● Each element here has a pair of key and value.
● Also known as Hash tables
○ Index by key (part of data) rather than value
○ Store both key and value (take more space)
○ Best when access is by data rather than index

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array

Design Issues

● What is the form of references to elements?


● Is the size static or dynamic?

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array - Perl


The reference a particular value you do:
%lookup =
$lookup{"dave"}
("dave", 1234,
new elements by assignments to new keys.
“peter", 3456,
$lookup{"adam"} = 3845
"andrew", 6789);

new assignments to old keys also:

# change dave's code

$lookup{"dave"} = 7634;

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array

● In the case of non-associative arrays, the indices never need to be


stored. However, in an associative array the user defined keys must
be stored in the structure. So each elements of an associative array
is in fact a pair of entities, a key and a value.
● Associative arrays are supported by Perl, Python, Ruby, and by the
standard class libraries of Java, C++, and C#.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array

● In Perl, associative arrays are often called hashes, because in the


implementation their elements are stored and retrieved with
hash functions.
● The each space for Perl hashes is distinct.
● Each hash variable must begin with a percentage sign (%).

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array

● Hashes can be set to literal values with the assignment statement

%salaries = (“Gagan” => 7500, “Pavan” =>5700, “Meenu” =>5575,


“Chetan” => 4785);

● A new element can be added : $ salaries{“rina”=>8500}


● An element can be removed: delete $salaries {“Gagan”}
● An entire hash can be empty : @salaries = ( );

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array
● The size of a Perl hash is dynamic.
● That is, it grows when a new element is added, and shrink when an
element is delete, and also when it is emptied by assignment of the
empty literal.
● The exists operator returns true or false, depending on whether its
operand key is an element in hash.
● For example,

If (exists $salaries {“Shalu”})…


Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Associative Array
● The size of a Perl hash is dynamic.
● That is, it grows when a new element is added, and shrink when an
element is delete, and also when it is emptied by assignment of the
empty literal.
● The exists operator returns true or false, depending on whether its
operand key is an element in hash.
● For example,

If (exists $salaries {“Shalu”})…


Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Implementing Associative Array


● Perl uses a hash function for fast lookups but is optimized for fast
reorganization
○ Uses a 32 bit hash value for each entry but only a few bits are used for small
arrays
○ To double the array size use one more bit and move half the existing
entries
● PHP also uses a hash function but stores arrays in a linked list for easy traversal
○ An array with both associative and numeric indices can develop gaps in the
numeric sequence
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Record Type

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Record Type

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Definition of Records in COBOL


COBOL uses level numbers to show nested records; others use recursive definition

01 EMP-REC.

02 EMP-NAME.

05 FIRST PIC X(20).

05 MID PIC X(10).

05 LAST PIC X(20).

02 HOURLY-RATE PIC 99V99.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Definition of Records in Ada


COBOL uses level numbers to show nested records; others use recursive definition
Record structures are indicated in an orthogonal way
type Emp_Rec_Type is record
First: String (1..20);
Mid: String (1..10);
Last: String (1..20);
Hourly_Rate: Float;
end record;
Emp_Rec: Emp_Rec_Type;
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

References to Records
● Record field references

1. COBOL : field_name OF record_name_1 OF ... OF record_name_n

2. Others (dot notation) :record_name_1.record_name_2. ... record_name_n.field_name

● Fully qualified references must include all record names


● Elliptical references allow leaving out record names as long as the reference is unambiguous,
● for example in COBOL

FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are elliptical references to the
employee’s first name

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

References to Records
struct { fully qualified reference: lists all

int age; intermediate names as in

struct { person.name.first

char *first; elliptical: may omit some of them if


unambiguous (COBOL,PL/1) as in

char *last; first of person

} name;
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Operations on Records

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Operations on Records

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Implementation of Record Type

Offset address relative to the beginning of


the records is associated with each field

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Union
● A union is a type whose variables are allowed to store
different type values at different times during
execution
● Design issues
○ Should type checking be required?
○ Should unions be embedded in records?

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Discriminated vs. Free Unions


● Fortran, C, and C++ provide union constructs in which
there is no language support for type checking; the union in
these languages is called free union
● Type checking of unions require that each union include a
type indicator called a discriminant
● Supported by Ada

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Ada Union Types


type Shape is (Circle, Triangle, Rectangle); Declare Variable
type Colors is (Red, Green, Blue);
type Figure (Form: Shape) is record
Figure_1: Figure;
Filled: Boolean; Figure_2:Figure(Form => Triangle)
Color: Colors;
case Form is
when Circle => Diameter:
Figure_1:= (filled=>True,
Float; color=Blue,
when Triangle =>
Form=>Rectangle
Leftside,
Rightside: Integer; Side1=>12
Angle: Float;
Side2=>3
when Rectangle => Side1,
Side2: Integer; )
end case; Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Ada Union Type Illustrated

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Pointer and reference type


● A pointer type variable has a range of values that consists of
memory addresses and a special value, nil
● Provide the power of indirect addressing
● Provide a way to manage dynamic memory
● A pointer can be used to access a location in the area where
storage is dynamically created (usually called a heap)

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Design Issues of Pointers

● What are the scope of and lifetime of a pointer variable?


● What is the lifetime of a heap-dynamic variable?
● Are pointers restricted as to the type of value to which they can
point?
● Are pointers used for dynamic storage management, indirect
addressing, or both?
● Should the language support pointer types, reference types, or both?
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Pointer Operations

● Two fundamental operations: assignment and dereferencing


● Assignment is used to set a pointer variable’s value to some useful address
● Dereferencing yields the value stored at the location represented by the
pointer’s value
● Dereferencing can be explicit or implicit
● C++ uses an explicit operation via *
j = *ptr
sets j to the value located at ptr
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Pointer Assignment Illustrated

The
assignment
operation
j = *ptr

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Dangling Pointer
Dangling pointers (dangerous)
A pointer pointing to data that does not exist anymore is called a
dangling pointer.

d is a dangling pointer.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Lost Heap dynamic Variable


● An allocated heap-dynamic variable that is no longer
accessible to the user program (often called garbage)
● Pointer p1 is set to point to a newly created heap-dynamic
variable
● Pointer p1 is later set to point to another newly created
heap-dynamic variable
● The process of losing heap-dynamic variables is called
memory leakage

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Lost Heap dynamic Variable

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Pointer Arithmetic in C and C++

float stuff[100];
float *p;
p = stuff;

*(p+5) is equivalent to stuff[5] and p[5]


*(p+i) is equivalent to stuff[i] and p[i]

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Reference Type
● C++ includes a special kind of pointer type called a reference type
that is used primarily for formal parameters
○ Advantages of both pass-by-reference and pass-by-value
● Java extends C++’s reference variables and allows them to
replace pointers entirely
○ References are references to objects, rather than being
addresses
● C# includes both the references of Java and the pointers of C++

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

int result = 0;
int &ref_result = result; result and
. . . ref_result are
ref_result = 100;
Cout<<result; //100 aliases.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Pointer Vs Reference

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Unit 2
Structuring the Computations
● Expression and Assignment Statements:
● Arithmetic expression,
● Overloaded Operators,
● Type conversions,
● Relational and Boolean Expressions,
● Short Circuit Evaluation, Assignment Statements,
● Mixed mode Assignment.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Introduction

■ Expressions are the fundamental means of specifying


computations in a programming language.
■ To understand expression evaluation, need to be familiar
with the orders of operator and operand evaluation.
■ The purpose of assignment variable is to change the value of
variable.

Department of Computer Engineering


105
SNJB’s Late Sau. K. B. J. College of Engineering
Arithmetic Expressions
Airthmetic Expression
■ Arithmetic evaluation was one of the motivations for the development of
the first programming languages.

■ Arithmetic expressions consist of operators, operands, parentheses,


and function calls.

■ Operators can be:


⚪ A unary operator has one operand.
⚪ A binary operator has two operands.
⚪ A ternary operator has three operands.

Department of Computer Engineering


106
SNJB’s Late Sau. K. B. J. College of Engineering
Unary Arithmetic Operators in C/C++ and Java
■ Unary Plus ( +A ):
⚪ Examples: +num, +num/5, num1 * +num2
⚪ Has no effect on its operand in C/C++.
⚪ In Java, it causes an implicit conversion of a char, short, or
byte operand to int type; otherwise, it has no effect on its
operand.

■ Unary Minus ( -A ):
⚪ Examples: -num, -num/5, num1 * -num2
Department of Computer Engineering
107
SNJB’s Late Sau. K. B. J. College of Engineering
Unary Arithmetic Operators in C/C++ and Java (cont.)
■ The pre-increment is specified as follows: (++a)
⚪ It says to add 1 to the current value of the variable and then to use the new value (if
necessary).
■ The post-increment is specified as follows: (a++)
⚪ It says to use the current value of the variable (if necessary) and then add 1 to it.
■ The pre-decrement is specified as follows: (--a)
⚪ It says to subtract 1 from the current value of the variable and then to use the
new value (if necessary).
■ The post-decrement is specified as follows: (a--)
⚪ It says to use the current value of the variable (if necessary) and then subtract 1 from it.

Department of Computer Engineering


108
SNJB’s Late Sau. K. B. J. College of Engineering
Binary Arithmetic Operators in C/C++ and Java
Operation Operator Example Operand Result

Addition + A+B Both integers Integer


------------------- ------------------
One operand is not integer Double precision floating-point

Subtraction - A–B Both integers Integer


---------------------------- -----------------------
One operand is not integer Double precision floating-point

Multiplication * A*B Both integers Integer


------------------------------ -------------------------
One operand is not integer Double precision floating-point

Division / A/B Both integers Integer


------------------------------ -------------------------
One operand is not integer Double precision floating-point

Modulus % A%B Both integers Integer


(Remainder)

Department of Computer Engineering


109
SNJB’s Late Sau. K. B. J. College of Engineering
Ternary Operator in C/C++ and Java
A ternary operator “ ?: ” has three operands.

average = (count==0)? 0 : sum/count;

⚪ Evaluates as if written like:

if (count == 0) average = 0;
else average = sum/count;

Department of Computer Engineering


110
SNJB’s Late Sau. K. B. J. College of Engineering
Arithmetic Expressions: Operator Precedence Rules
■ The operator precedence rules for expression evaluation define the order in
which “adjacent” operators of different precedence levels are evaluated.
■ Typical precedence levels:
⚪ parentheses.
⚪ unary operators.
⚪ ** (the exponential operator, if the language supports it).
⚪ *, /, %
⚪ +, -

■ APL has a single level of precedence .


Department of Computer Engineering
111
SNJB’s Late Sau. K. B. J. College of Engineering
Arithmetic Expressions: Operator Associativity Rule
■ The operator associativity rules for expression evaluation define the
order in which adjacent operators with the same precedence level are
evaluated.

■ Typical associativity rules:


⚪ Left to right, except **, which is right to left.

■ APL is different; all operators have equal precedence and all operators
associate right to left.

■ Precedence and associativity rules can be overridden with parentheses.


Department of Computer Engineering
112
SNJB’s Late Sau. K. B. J. College of Engineering
Precedence Highest *, /, not

+, –, &, mod

– (unary)

=, /=, < , <=, >=, > a+b * c+d


and
((a + (b * c)1)2 + d)3
Lowest or, xor

Associativity Left to right

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Precedence Highest *, /, not
a. a * b – 1 + c
+, –, &, mod
b. a * (b – 1) / c mod d
– (unary)
c. (a – b) / c & (d * e / a – 3)
=, /=, < , <=, >=, >
d. -a or c = d and e
and
e. a > b xor c or d <= 17
Lowest or, xor
f. -a + b
Associativity Left to right

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
int fun(int *i) {

*i += 5;

return 4; operands are evaluated left to right :

} operands are evaluated right to left.

void main() {

int x = 3;

x = x + fun(&x);

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Arithmetic Expressions :Conditional Expressions
■ Conditional Expressions:
⚪ C-based languages (e.g., C, C++).
⚪ An example:
average = (count == 0)? 0 : sum/count;

⚪ Evaluates as if written like:


if (count == 0) average = 0;
else average = sum/count;
Department of Computer Engineering
116
SNJB’s Late Sau. K. B. J. College of Engineering
Operand Evaluation Order: Functional Side Effects
■ Functional side effects:
⚪ A side effect of a function occurs when a function changes either:
■ one of its parameters or
■ a global variable.

■ Assume fun(x) changes parameter x:


⚪ y = fun(x) + x;
⚪ y = x + fun(x);

Department of Computer Engineering


117
SNJB’s Late Sau. K. B. J. College of Engineering
Functional Side Effect: Example (2 of 2)
int a = 5; int a = 5;
int fun1() { int fun1() {
a = 17; a = 17;
return 3; return 3;
} }
void main() { void main() {
a = fun1() + a; a = a + fun1();
cout << a << endl; cout << a << endl;
} }

// 20 is printed // 8 is printed
Department of Computer Engineering
118
SNJB’s Late Sau. K. B. J. College of Engineering
Overloaded Operators
■ Operator Overloading is accomplished by defining functions that
have the same name as the operator being overloaded.
■ Some are common (e.g., +, -, *, … for int and float).

■ C++, FORTRAN 95 and Ada allow user-defined overloaded


operators.

■ Java does not permit operator overloading.

Department of Computer Engineering


119
SNJB’s Late Sau. K. B. J. College of Engineering
Overloaded Operators - division operator issue

■ avg= sum/count

■ Avg is floating point but sum and count are integer

■ The result gives integer value for Avg

Department of Computer Engineering


120
SNJB’s Late Sau. K. B. J. College of Engineering
Overloaded Operators - division operator solution
■ Pascal: two operators

○ div: integer solution

○ / : floating point solution

■ Javascript does not have integer airthmaeic operators

○ Numbers in JavaScript are "double-precision 64-bit format IEEE 754


values".

■ In PHP , a floating point value is produced.

Department of Computer Engineering


121
SNJB’s Late Sau. K. B. J. College of Engineering
Overloaded Operators
■ It is harmful.

○ User defined operator overloading some one can define + for


multiplication.

■ C++ has a few operators that cannot be overloaded.

○ Structure member operator(.)

○ Scope resolution operator(::)

Department of Computer Engineering


122
SNJB’s Late Sau. K. B. J. College of Engineering
Type Conversions
■ Type conversions are either:
⚪ A narrowing conversion is one that converts an object to a type that
cannot include all of the values of the original type e.g., float to int.
■ May lose data.
⚪ A widening conversion is one in which an object is converted to a
type that can include at least approximations to all of the values of
the original type e.g., int to float.
■ Generally safe.

Department of Computer Engineering


123
SNJB’s Late Sau. K. B. J. College of Engineering
Type Conversions (cont.)
■ Type conversions may be:
⚪ Implicit (coercion).
⚪ Explicit (such as casting in C).
■ A mixed-mode expression is one that has operands of different types.
■ A coercion is an implicit type conversion.
■ In most languages, all numeric types are coerced in expressions, using
widening conversions.
■ In Java, byte and short are coerced to int whenever an operation is applied.

Department of Computer Engineering


124
SNJB’s Late Sau. K. B. J. College of Engineering
Explicit Type Conversions
■ Explicit Type Conversions:
⚪ Called casting in C-based language.
⚪ Examples:
■ C conversion (cast)

int a, b;
float x;
x = (float)a/(float)b;
Department of Computer Engineering
125
SNJB’s Late Sau. K. B. J. College of Engineering
Type Conversions:Errors in Expressions
■ Causes:
⚪ Errors resulting from narrowing conversions.
⚪ Errors resulting from limitations of computer arithmetic:
■ The result of an operation cannot be represented in the memory cell where it
must be stored.
■ Overflow Or Underflow: depending on result is too large or too small
⚪ Some languages (Ada, C++, Java) provide an exception handling mechanism that allows the
programmer to handle conditions such as divide by 0.
⚪ Often ignored by the run-time system.
⚪ Sometimes known as exceptions.

Department of Computer Engineering


126
SNJB’s Late Sau. K. B. J. College of Engineering
Relational and Boolean Expressions
■ Relational operators in various languages:
⚪ Ada: =, /=, >, <, >=, <=
⚪ Java: ==, !=, >, <, >=, <=
■ Relational operators always have lower precedence than arithmetic operators.
■ Relational Expressions:
⚪ Use relational operators and operands of various types.
⚪ Evaluate to some Boolean representation.
■ Boolean Expressions:
⚪ Operands are Boolean and the result is Boolean.
⚪ C/C++ operators: &&, ||, !

Department of Computer Engineering


127
SNJB’s Late Sau. K. B. J. College of Engineering
Relational and Boolean Expressions: No Boolean Type in C
■ C has no Boolean type, it uses int type with 0 for false and
nonzero for true.

Department of Computer Engineering


128
SNJB’s Late Sau. K. B. J. College of Engineering
Short-Circuit Evaluation
■ A short-circuit evaluation of an expression is one in which the result is determined without evaluating all of
the operands and/or operators.

■ Types:

1. In Arithmetic Expressions:

■ Ex.: (13*a) * (b/13–1)


If a is zero, there is no need to evaluate (b/13-1).

2. In logical Expressions:

■ Ex.: The value of (a >= 0) and (b < 10) is independent of the second relational
expression if a < 0.

Department of Computer Engineering


129
SNJB’s Late Sau. K. B. J. College of Engineering
Short-Circuit Evaluation (cont.)
■ Lack of short circuit evaluation can cause problems:
Index = 1;
while ((Index < listlen) && (list[Index] !=
key))
Index = Index + 1;

If the expression doesn’t have short-circuit, then both operands


to “&&” are evaluated.
■ C, C++, and Java: use short-circuit evaluation for the usual
Boolean operators (&& and ||).
Department of Computer Engineering
130
SNJB’s Late Sau. K. B. J. College of Engineering
Short-Circuit Evaluation (cont.)
■ Short-circuit evaluation exposes the problem of side effects in
expressions:
if ((a > b) || (b++/3))

If (a<=b), the second expression which increments b is not


evaluated.

■ Ada has short-circuit logical operators: and then and or else


if (index <= listlen) and then (list(index) /= key)

Department of Computer Engineering


131
SNJB’s Late Sau. K. B. J. College of Engineering
Assignment Statements
■ The general syntax:
<target_var> <assign_operator> <expression>
■ The assignment operator:
= FORTRAN, BASIC, PL/I, C, C++, Java.
:= ALGOLs, Pascal, Ada.
■ Simple assignment:
⚪ a = b;
⚪ a = b = c;
■ Suppose a, b, and c are integers.
■ In C, the integer value of c is assigned to b, which is in turn assigned to a
(multiple targets).
Department of Computer Engineering
132
SNJB’s Late Sau. K. B. J. College of Engineering
Assignment statements
■ Multiple targets:
Sum, Total = 0 (PL/I)
Sum = Total = 0 (C)
■ Conditional targets:
⚪ Perl allows it, for example:
flag ? count1 : count2 = 0;
⚪ Which is equivalent to:
if (flag) count1 = 0; else count2 = 0;
■ Compound assignment operators:
a += b; // a = a + b;

Department of Computer Engineering


133
SNJB’s Late Sau. K. B. J. College of Engineering
Assignment statements (cont.)
■ Unary assignment operators:
⚪ count++;
⚪ ++count;
⚪ sum = ++count; 🡺 count incremented then assigned to sum
⚪ sum = count++; 🡺 count assigned to sum then incremented

■ Assignment as an expression:
⚪ In C, C++, and Java the assignment statement produces a result and can
be used as operands.
while ((ch = getchar()) != EOF) { … }

ch = getchar() is carried out; the result (assigned to ch) is used as a


conditional value for the while statement.

Department of Computer Engineering


134
SNJB’s Late Sau. K. B. J. College of Engineering
Mixed-Mode Assignment
■ Assignment statements can also be mixed-mode, for example:
int a, b;
float c;
c = a / b;

■ In Pascal, integer variables can be assigned to real variables, but real


variables cannot be assigned to integers

■ In Java, only widening assignment coercions are done.

■ In Ada, there is no assignment coercion.


Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Unit 2
Statement level Control Structures:
● Selection Statements,
● Iterative Statements,
● Unconditional Branching.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Levels of Control Flow

■ Within expressions (Part 1)


■ Among program units (Part 2)
■ Among program statements (Part 3)

Department of Computer Engineering 1-137


SNJB’s Late Sau. K. B. J. College of Engineering

Control Statements: Evolution

• FORTRAN I control statements were based directly on IBM


704 hardware
• Much research and argument in the 1960s about the issue
• One important result: It was proven that all algorithms
represented by flowcharts can be coded with only two-way
selection and pretest logical loops

Department of Computer Engineering 1-138


SNJB’s Late Sau. K. B. J. College of Engineering
Control Structure
• A control structure is a control statement and the statements
whose execution it controls
• Design question
– Should a control structure have multiple entries?

Department of Computer Engineering 1-139


SNJB’s Late Sau. K. B. J. College of Engineering
Selection Statements

• A selection statement provides the means of choosing


between two or more paths of execution
• Two general categories:
– Two-way selectors
– Multiple-way selectors

Department of Computer Engineering 1-140


SNJB’s Late Sau. K. B. J. College of Engineering
Two-Way Selection Statements
• General form:
if control_expression
then clause
else clause
• Design Issues:
– What is the form and type of the control expression?
– How are the then and else clauses specified?
– How should the meaning of nested selectors be specified?
Department of Computer Engineering 1-141
SNJB’s Late Sau. K. B. J. College of Engineering
The Control Expression

• If the then reserved word or some other syntactic


marker is not used to introduce the then clause, the
control expression is placed in parentheses
• In C89, C99, Python, and C++, the control expression can be
arithmetic
• In languages such as Ada, Java, Ruby, and C#, the control
expression must be Boolean

Department of Computer Engineering 1-142


SNJB’s Late Sau. K. B. J. College of Engineering
Clause Form
• In many contemporary languages, the then and else clauses can be
single statements or compound statements
• In Perl, all clauses must be delimited by braces (they must be
compound)
• In Fortran 95, Ada, and Ruby, clauses are statement sequences
• Python uses indentation to define clauses
if x > y :
x = y
print "case 1"

Department of Computer Engineering 1-143


SNJB’s Late Sau. K. B. J. College of Engineering
Nesting Selectors
• Java example
if (sum == 0)
if (count == 0)
result = 0;
else result = 1;
• Which if gets the else?
• Java's static semantics rule: else matches with the
nearest if
Department of Computer Engineering 1-144
SNJB’s Late Sau. K. B. J. College of Engineering
Nesting Selectors (continued)
• To force an alternative semantics, compound statements may be used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;
• The above solution is used in C, C++, and C#
• Perl requires that all then and else clauses to be compound

Department of Computer Engineering 1-145


SNJB’s Late Sau. K. B. J. College of Engineering
Nesting Selectors (continued)
• Statement sequences as clauses: Ruby
if sum == 0 then
if count == 0 then
result = 0
else
result = 1
end
end
Department of Computer Engineering 1-146
SNJB’s Late Sau. K. B. J. College of Engineering
Nesting Selectors (continued)

• Python
if sum == 0 :
if count == 0 :
result = 0
else :
result = 1

Department of Computer Engineering 1-147


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection Statements
• Allow the selection of one of any number of statements or
statement groups
• Design Issues:
1. What is the form and type of the control expression?
2. How are the selectable segments specified?
3. Is execution flow through the structure restricted to include just
a single selectable segment?
4. How are case values specified?
5. What is done about unrepresented expression values?

Department of Computer Engineering 1-148


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples
Design choices for C’s switch statement
1. Control expression can be only an integer type
2. Selectable segments can be statement sequences, blocks, or
compound statements
3. Any number of segments can be executed in one execution of the
construct (there is no implicit branch at the end of selectable
segments)
4. default clause is for unrepresented values (if there is no default, the
whole statement does nothing)
Department of Computer Engineering 1-149
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples

• C, C++, and Java


switch (expression) {
case const_expr_1: stmt_1;

case const_expr_n: stmt_n;
[default: stmt_n+1]
}

Department
Copyright © 2009 Addison-Wesley. All rights reserved. of Computer Engineering 1-150
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples C, C++, Java

switch (index) {
case 1:
Without the break-
case 3: odd+=1; statement control
sumodd+=index; continues to the next
break;
case 2:
alternative.
case 4: even+=1;
sumeven+=index;
break;
default:cout << “Error in switch,
index = “ << index; break;
}
Department of Computer Engineering 1-151
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples c#
switch (value) {
case -1: Every selectable segment must
Negatives++; end with an explicit
break; unconditional branch
case 0: statement: either a break, which
Zeros++; transfers control out of the
goto case 1; switch construct, or a goto,
case 1: which can transfer control to
Positives++; one of the selectable
break; segments (or virtually anywhere
default: else).
Console.WriteLine(“Error in switch \n”);
Break; }
Department of Computer Engineering 1-152
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples
• Ada design choices:
1. Expression can be any ordinal type
2. Segments can be single or compound
3. Only one segment can be executed per execution of the construct
4. Unrepresented values are not allowed
• Constant List Forms:
1. A list of constants
2. Can include:
- Subranges
- Boolean OR operators (|)

Department of Computer Engineering 1-153


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples Ada
case x of
when North => x:=East;
when East => x:=South;
when South => x:=West;
when West => x:=North;
end;

Department of Computer Engineering 1-154


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples Pascal
type direction=(North,East,South,West);
var x:direction;

case x of
North: x:=East;
East: x:=South;
South: x:=West;
West: x:=North
end;

Department of Computer Engineering 1-155


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples Ruby
Case
when Boolean-expression then expression

when Boolean-expression then expression

[else expression]
end

Department of Computer Engineering 1-156


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples : two forms of Ruby
1. One form uses when conditions
leap = case
when year % 400 == 0 then true
when year % 100 == 0 then false
else year % 4 == 0
end
2. The other uses a case value and when values
case in_val
when -1 then neg_count++
when 0 then zero_count++
when 1 then pos_count++
else puts "Error – in_val is out of range"
end

Department of Computer Engineering 1-157


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection Using if
• Multiple Selectors can appear as direct extensions to two-way
selectors, using else-if clauses, for example in Python:
if count < 10 :
bag1 = True
elif count < 100 :
bag2 = True
elif count < 1000 :
bag3 = True

Department of Computer Engineering 1-158


SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection Using if
• The Python example can be written as a Ruby case
case
when count < 10 then bag1 = true
when count < 100 then bag2 = true
when count < 1000 then bag3 = true
end

Department of Computer Engineering 1-159


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements

• The repeated execution of a statement or


compound statement is accomplished either by
iteration or recursion
• General design issues for iteration control
statements:
1. How is iteration controlled?
2. Where is the control mechanism in the loop?

Department of Computer Engineering 1-160


SNJB’s Late Sau. K. B. J. College of Engineering
Counter-Controlled Loops

• A counting iterative statement has a loop variable, and a


means of specifying the initial and terminal, and stepsize
values
• Design Issues:
1. What are the type and scope of the loop variable?
2. Should it be legal for the loop variable or loop parameters to be
changed in the loop body, and if so, does the change affect loop control?
3. Should the loop parameters be evaluated only once, or once for
every iteration?

Department of Computer Engineering 1-161


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples
• FORTRAN 95 syntax
DO label var = start, finish [, stepsize]
• Stepsize is 1 by default
• Parameters can be expressions
• Design choices:
1. Loop variable must be INTEGER
2. The loop variable cannot be changed in the loop, but the parameters can;
because they are evaluated only once, it does not affect loop control
3. Loop parameters are evaluated only once

Department of Computer Engineering 1-162


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples
• FORTRAN 95 : a second form:
[name:] Do variable = initial, terminal [,stepsize]

End Do [name]

- Cannot branch into either of Fortran’s Do statements

Department of Computer Engineering 1-163


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples

• Design choices:
○ Type of the loop variable is that of the discrete range (A discrete
range is a sub-range of an integer or enumeration type).
○ Loop variable does not exist outside the loop
○ The loop variable cannot be changed in the loop, but the
discrete range can; it does not affect loop control
○ The discrete range is evaluated just once
• Cannot branch into the loop body

Department of Computer Engineering 1-164


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples
• Ada
for var in [reverse] discrete_range loop
...
end loop

Count: Float := 1.35

For Count in 1..10 loop


sum:=sum+Count;
End loop;

Department of Computer Engineering 1-165


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples
• C-based languages
for ([expr_1] ; [expr_2] ; [expr_3]) statement
• The expressions can be whole statements, or even statement
sequences, with the statements separated by commas
• The value of a multiple-statement expression is the value of the last
statement in the expression
• If the second expression is absent, it is an infinite loop

Department of Computer Engineering 1-166


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples

• Design choices:
■ There is no explicit loop variable
■ Everything can be changed in the loop
■ The first expression is evaluated once, but the other two are
evaluated with each iteration

Department of Computer Engineering 1-167


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples

• C++ differs from C in two ways:


1. The control expression can also be Boolean
2. The initial expression can include variable
definitions (scope is from the definition to the end of
the loop body)
• Java and C#
– Differs from C++ in that the control expression must
be Boolean
Department of Computer Engineering 1-168
SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Examples Python
for loop_variable in object:
- loop body
[else:
- else clause]

● The object is often a range, which is either a list of values in brackets ([2, 4,
6]), or a call to the range function (range(5)), which returns 0, 1, 2, 3, 4
● The loop variable takes on the values specified in the given range, one
for each iteration
● The else clause, which is optional, is executed if the loop terminates
normally

Department of Computer Engineering 1-169


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Logically-Controlled Loops
• Repetition control is based on a Boolean
expression
• Design issues:
– Pretest or posttest?
– Should the logically controlled loop be a special case of
the counting loop statement or a separate statement?

Department of Computer Engineering 1-170


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Logically-Controlled Loops: Examples
• C and C++ have both pretest and posttest forms, in which
the control expression can be arithmetic:
• Java is like C and C++, except the control expression
must be Boolean (and the body can only be entered at the
beginning -- Java has no goto

Department of Computer Engineering 1-171


SNJB’s Late Sau. K. B. J. College of Engineering

while (ctrl_expr)
loop body

do
loop body

while (ctrl_expr)

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: Logically-Controlled Loops: Examples

• Ada has a pretest version, but no posttest


• FORTRAN 95 has neither
• Perl and Ruby have two pretest logical loops, while
and until. Perl also has two posttest loops

Department of Computer Engineering 1-173


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: User-Located Loop Control Mechanisms

• Sometimes it is convenient for the programmers to decide a


location for loop control (other than top or bottom of the loop)
• Simple design for single loops (e.g., break)

• Design issues for nested loops


1. Should the conditional be part of the exit?

2. Should control be transferable out of more than one loop?

Department of Computer Engineering 1-174


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: User-Located Loop Control Mechanisms

OuterLoop:
for (row = 0; row < numRows; row++)
for (col = 0; col < numCols; col++) {
sum += mat[row][col];
if (sum > 1000.0)
break outerLoop;

Department of Computer Engineering 1-175


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: User-Located Loop Control Mechanisms

while (sum < 1000)


{
getnext(value);
if (value < 0) break;
sum += value;
}

Department of Computer Engineering 1-176


SNJB’s Late Sau. K. B. J. College of Engineering
Iterative Statements: User-Located Loop Control Mechanisms
break and continue
• C , C++, Python, Ruby, and C# have unconditional unlabeled exits
(break)
• Java and Perl have unconditional labeled exits (break in Java, last in
Perl)
• C, C++, and Python have an unlabeled control statement, continue, that
skips the remainder of the current iteration, but does not exit the loop
• Java and Perl have labeled versions of continue

Department of Computer Engineering 1-177


SNJB’s Late Sau. K. B. J. College of Engineering
Unconditional Branching

• Transfers execution control to a specified place in the program


• Represented one of the most heated debates in 1960’s and 1970’s
• Major concern:
○ Readability
○ Some languages do not support goto statement (e.g., Java)
○ C# offers goto statement (can be used in switch statements)
○ Loop exit statements are restricted and somewhat camouflaged
goto’s

Department of Computer Engineering 1-178


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Unit 2
Structuring the Data, Computations and Program
● Elementary Data Types : Primitive data Types, Character String types, User Defined Ordinal Types,
Array types, Associative Arrays, Record Types, Union Types, Pointer and reference Type.
● Expression and Assignment Statements: Arithmetic expression, Overloaded Operators, Type
conversions, Relational and Boolean Expressions, Short Circuit Evaluation, Assignment Statements,
Mixed mode Assignment.
● Statement level Control Structures: Selection Statements, Iterative Statements, Unconditional
Branching.
● Subprograms: Fundamentals of SubPrograms, Design Issues for Subprograms, Local referencing
Environments, Parameter passing methods.
● Abstract Data Types and Encapsulation Construct: Design issues for Abstraction, Parameterized
Abstract Data types, Encapsulation Constructs, Naming Encapsulations

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

• Introduction
• Fundamentals of Subprograms
• Design Issues for Subprograms
• Local Referencing Environments
• Parameter-Passing Methods

Department of Computer Engineering 1-188


SNJB’s Late Sau. K. B. J. College of Engineering
Introduction

Department of Computer Engineering 1-189


SNJB’s Late Sau. K. B. J. College of Engineering
Introduction
• Two fundamental abstraction facilities
– Process abstraction
• Emphasized from early days

– Data abstraction
• Emphasized in the1980s

Department of Computer Engineering 1-190


SNJB’s Late Sau. K. B. J. College of Engineering
Fundamentals of Subprograms

Department of Computer Engineering 1-191


SNJB’s Late Sau. K. B. J. College of Engineering
Fundamentals of Subprograms
• Each subprogram has a single entry point

• The calling program is suspended during execution


of the called subprogram
• Control always returns to the caller when the called
subprogram’s execution terminates
Department of Computer Engineering 1-192
SNJB’s Late Sau. K. B. J. College of Engineering
Basic Definitions
• A subprogram definition describes the interface to and the
actions of the subprogram abstraction
• A subprogram call is an explicit request that the subprogram
be executed
• A subprogram header is the first part of the definition,
including the name, the kind of subprogram, and the formal
parameters
Department of Computer Engineering 1-193
SNJB’s Late Sau. K. B. J. College of Engineering
Basic Definitions

• The parameter profile (aka signature) of a subprogram is


the number, order, and types of its parameters
• The protocol is a subprogram’s parameter profile and, if it
is a function, its return type

Department of Computer Engineering 1-194


SNJB’s Late Sau. K. B. J. College of Engineering
Basic Definitions

Department of Computer Engineering 1-195


SNJB’s Late Sau. K. B. J. College of Engineering
Basic Definitions (continued)
• Function declarations in C and C++ are often called
prototypes
• A subprogram declaration provides the protocol, but not
the body, of the subprogram

Department of Computer Engineering 1-196


SNJB’s Late Sau. K. B. J. College of Engineering
Basic Definitions (continued)

• A formal parameter is a dummy variable listed in the


subprogram header and used in the subprogram
• An actual parameter represents a value or address used
in the subprogram call statement

Department of Computer Engineering 1-197


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering 1-198


SNJB’s Late Sau. K. B. J. College of Engineering
Actual/Formal Parameter Correspondence
• Positional
– The binding of actual parameters to formal parameters
is by position: the first actual parameter is bound to
the first formal parameter and so forth
– Safe and effective

Department of Computer Engineering 1-199


SNJB’s Late Sau. K. B. J. College of Engineering
Actual/Formal Parameter Correspondence
Positional

Department of Computer Engineering 1-200


SNJB’s Late Sau. K. B. J. College of Engineering
Actual/Formal Parameter Correspondence

• Keyword
– The name of the formal parameter to which an actual
parameter is to be bound is specified with the actual
parameter
– Parameters can appear in any order

Department of Computer Engineering 1-201


SNJB’s Late Sau. K. B. J. College of Engineering
Actual/Formal Parameter Correspondence

• Keyword
– The name of the formal parameter to which an actual
parameter is to be bound is specified with the actual
parameter
– Parameters can appear in any order

Department of Computer Engineering 1-202


SNJB’s Late Sau. K. B. J. College of Engineering
Actual/Formal Parameter Correspondence
Keyword

Department of Computer Engineering 1-203


SNJB’s Late Sau. K. B. J. College of Engineering
Formal Parameter Default Values

• In certain languages (e.g., C++, Ada), formal


parameters can have default values (if not actual
parameter is passed)
– In C++, default parameters must appear last because
parameters are positionally associated

Department of Computer Engineering 1-204


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering 1-205


SNJB’s Late Sau. K. B. J. College of Engineering
Formal Parameter Default Values

• C# methods can accept a variable number of


parameters as long as they are of the same type

Department of Computer Engineering 1-206


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering 1-207


SNJB’s Late Sau. K. B. J. College of Engineering
Procedures and Functions :two categories of subprograms

● Procedures are collection of statements that define


parameterized computations
● Functions structurally resemble procedures but are
semantically modeled on mathematical functions
○ They are expected to produce no side effects
○ In practice, program functions have side effects

Department of Computer Engineering 1-208


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering 1-209


SNJB’s Late Sau. K. B. J. College of Engineering
Design Issues for Subprograms
• What parameter passing methods are provided?
• Are parameter types checked?
• Are local variables static or dynamic?
• Can subprogram definitions appear in other subprogram
definitions?
• Can subprograms be overloaded?
• Can subprogram be generic?

Department of Computer Engineering 1-210


SNJB’s Late Sau. K. B. J. College of Engineering
Local Referencing Environments
Local Data / Variables
• Variables that are defined inside subprograms are called
local variables.
• Local variables can be either static or stack dynamic
• “bound to storage when the program begins execution and
are unbound when execution terminates.”

Department of Computer Engineering 1-211


SNJB’s Late Sau. K. B. J. College of Engineering
Local Referencing Environments
• The local referencing environment defines the collection of
variables and their associated values that are currently visible
and accessible within a specific block or function.
• It serves as a mapping between variable names and their
respective memory locations.

Department of Computer Engineering 1-212


SNJB’s Late Sau. K. B. J. College of Engineering
Benefits of Local Referencing Environments
1. Data Encapsulation: Local data and local referencing environment promote data encapsulation,

where variables are confined to specific blocks. This prevents unintended access or

modification of data from unrelated parts of the program.

2. Reduced Scope Conflicts: By limiting the visibility of local data to their specific blocks, the risk

of naming conflicts with other variables in different parts of the program is reduced.

3. Memory Efficiency: Local data is stored on the stack, which is typically more memory-efficient

than global data stored in the heap. Local variables are automatically deallocated when they

go out of scope, freeing up memory.


Department of Computer Engineering 1-213
SNJB’s Late Sau. K. B. J. College of Engineering
Local Referencing Environments
Advantages of using stack dynamic variables:
● Support for recursion.
● Storage for locals is shared among some subprograms.
Disadvantages:
● Allocation/deallocation time.
● Indirect addressing “only determined during execution.”
● Subprograms cannot be history sensitive “can’t retain data values of local
var between calls.”
Department of Computer Engineering 1-214
SNJB’s Late Sau. K. B. J. College of Engineering
Local Referencing Environments
Advantages of using static vars:
• Static local vars can be accessed faster because there is no indirection.
• No run-time overhead for allocation and deallocation.
• Allow subprograms to be history sensitive.
Disadvantages:
• Inability to support recursion.
• Their storage can’t be shared with the local vars of other inactive
subprograms.
Department of Computer Engineering 1-215
SNJB’s Late Sau. K. B. J. College of Engineering
Parameter Passing Methods
• Ways in which parameters are transmitted to and/or
from called subprograms
– Pass-by-value
– Pass-by-result
– Pass-by-value-result
– Pass-by-reference
– Pass-by-name
Department of Computer Engineering 1-216
SNJB’s Late Sau. K. B. J. College of Engineering
Models of Parameter Passing

Department of Computer Engineering 1-217


Pass By Value
• Make a copy of the value
• Send the copy to the function
• Result NOT transmitted back
void test(int A)
{ A++; } //2
A B
void main()
// --- 5
{
1
(entry -5 5
int B=5; //1
test(B); ) 5
// 6
cout << B;//3 2// --- 5
}
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Value (In Mode)
• The value of the actual parameter is used to initialize
the corresponding formal parameter
– Normally implemented by copying
– Can be implemented by transmitting an access path but not
recommended (enforcing write protection is not easy)
– When copies are used, additional storage is required
– Storage and copy operations can be costly

Department of Computer Engineering 1-219


Pass By Result
• No input value
• Send the copy to the function
• Result transmitted back on return

void test(int A)
{ A++; } //2
A B
void main() // --- 5
{ int B=5; //1 1
(entry -? 5
test(B); ) 5
// ?+1
cout << B;//3
2// ---
} ?+1
3 -
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Result (Out Mode)
• When a parameter is passed by result, no value is transmitted to the
subprogram;
• the corresponding formal parameter acts as a local variable;
• its value is transmitted to caller’s actual parameter when control is
returned to the caller
– Require extra storage location and copy operation
• Potential problem: sub(p1, p1); whichever formal parameter is
copied back will represent the current value of p1

Department of Computer Engineering 1-221


Pass By Value Result
• Copy of input value
• Use the copy in the function
• Result transmitted back on return
void test(int A)
{A++;} //2 A B
void main() // --- 5
{ int B=5; //1 1
(entry -5 5
test(B); )
cout << B;//3 // 6 5
} 2// --- 6
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Value-Result (inout Mode)
• A combination of pass-by-value and pass-by-result
• Sometimes called pass-by-copy
• Formal parameters have local storage
• Disadvantages:
– Those of pass-by-result
– Those of pass-by-value

Department of Computer Engineering 1-223


Ada Example for Pass-by Value, Pass by Result and Pass-By- Result

with Ada.Text_IO; use Ada.Text_IO;


O/ 12 0 30
procedure Hello is P
procedure DiffModes(A : in Integer; O/ 12 100 60
B : out Integer; P
C : in out Integer) is
begin
Put_Line(Integer'Image(A));
DiffModes(X,Y,Z) DiffModes(A,B,C)
Put_Line(Integer'Image(B));
Put_Line(Integer'Image(C)); 12 12
//X
B:= 100;
C:= C*2; //Y 44 100 100
end DiffModes;
//Z 30 60 60 30
X:Integer := 12;
Y:Integer := 44;
Z:Integer := 30;
begin
Put_Line("Hello, world!");
DiffModes(X,Y,Z);
Put_Line(Integer'Image(X));
Put_Line(Integer'Image(Y));
Put_Line(Integer'Image(Z));
end Hello;
Pass By Reference
• Send address of original
• Use pointer inside function
• No need to do explicit return

void test(int A)
A B
{A++;} //2 // --- 5
void main() 1
(entry -*B 5
{ int B=5; //1 )
test(*B); // *B 6
cout << B;//3 2// --- 6
} 3 -
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Reference (Inout Mode)
• Pass an access path
• Also called pass-by-sharing
• Passing process is efficient (no copying and no duplicated
storage)
• Disadvantages
– Slower accesses (compared to pass-by-value) to formal parameters
– Potentials for unwanted side effects
– Unwanted aliases (access broadened)
Department of Computer Engineering 1-227
Pass By Name
• Conceptual model is to substitute
name of the actual parameter for the
formal parameter
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Name (Inout Mode)
• By textual substitution
• Formals are bound to an access method at the time of the
call, but actual binding to a value or address takes place at
the time of a reference or assignment
• Allows flexibility in late binding

Department of Computer Engineering 1-229


SNJB’s Late Sau. K. B. J. College of Engineering
Implementing Parameter-Passing Methods
• In most language parameter communication takes place thru the
run-time stack
• Pass-by-reference are the simplest to implement; only an
address is placed in the stack
• A subtle but fatal error can occur with pass-by-reference and
• pass-by-value-result: a formal parameter corresponding to a
constant can mistakenly be changed

Department of Computer Engineering 1-230


SNJB’s Late Sau. K. B. J. College of Engineering
Parameter Passing Methods of Major Languages
• Fortran
– Always used the in-out semantics model
– Before Fortran 77: pass-by-reference
Fortran 77 and later: scalar variables are often passed by value-result
• C
– Pass-by-value
– Pass-by-reference is achieved by using pointers as parameters

Department of Computer Engineering 1-231


SNJB’s Late Sau. K. B. J. College of Engineering
Parameter Passing Methods of Major Languages

• C++
– A special pointer type called reference type for pass-by-reference

• Java
– All parameters are passed by value
– Object parameters are passed by reference

Department of Computer Engineering 1-232


SNJB’s Late Sau. K. B. J. College of Engineering
Parameter Passing Methods of Major Languages (continued)

Ada
– Three semantics modes of parameter transmission:
in, out, in out; in is the default mode
– Formal parameters declared
■ out can be assigned but not referenced;
■ those declared in can be referenced but not assigned;
■ in out parameters can be referenced and assigned

Department of Computer Engineering 1-233


SNJB’s Late Sau. K. B. J. College of Engineering
Parameter Passing Methods of Major Languages (continued)
• C#
– Default method: pass-by-value
– Pass-by-reference is specified by preceding both a formal
parameter and its actual parameter with ref
– Pass-by-result is specified by out

• PHP: very similar to C#

Department of Computer Engineering 1-234


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering 1-235


SNJB’s Late Sau. K. B. J. College of Engineering
Call by Value- When to use?

When we don’t want to modify the actual parameters, then


we can use pass by value method. Even though you can also use
it when the method returning some value.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Call by Address- When to use?

call by address is a suitable mechanism for modifying the


actual parameters. We will be using this type of code more
frequently in our programs

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Call by Reference- When not to use?

● C++ allows call by reference and the code of that function will be copied at the
place where it is being called.
● It is not advisable to use call by reference more frequently. You can use call by
reference for small functions like one or two lines of function or the function like
swap, you can use call by reference.
● But don’t use it for heavy functions which are having loops and are having
complex logic.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
SubProgram Names as Parameters
It is sometimes convenient to pass subprogram names
as parameters i.e Functions as parameters
● Issues:
1. Are parameter types checked?
2. What is the correct referencing environment for a
subprogram that was sent as a
parameter?
Department of Computer Engineering 1-239
SNJB’s Late Sau. K. B. J. College of Engineering
SubProgram Names as Parameters…Referencing Environment

1. Shallow binding: The environment of the call


statement that enacts the passed subprogram - Most
natural for dynamic-scoped languages
2. Deep binding: The environment of the definition of
the passed subprogram - Most natural for static-scoped
languages
3. Ad hoc binding: The environment of the call statement
that passed the subprogram
Department of Computer Engineering 1-240
SNJB’s Late Sau. K. B. J. College of Engineering
SubProgram Names as Parameters
Example function sub1( )
{ var x;
● In C,C++ these are this is illustrated by function pointers, function sub2( )
In C# by delegates. { alert(x); // Creates a dialog box };
● Consider the execution of sub2 when it is called in sub4. function sub3( )
○ Shallow Binding: the referencing environment of that { var x;
x = 3;
execution is that of sub4, so the reference to x in sub2 is
//subprogram name sub2 as parameter to sub4.
bound to the local x in sub4, and the output of the program sub4(sub2);
is 4. };
○ Deep Binding: the referencing environment of sub2’s function sub4(subx )
{ var x; x = 4;
execution is that of sub1, so the reference to x in sub2 is
sub2( );
bound to the local x in sub1 and the output is 1. };
○ Ad hoc: the binding is to the local x in sub3, and the output x = 1;
is 3. sub3( );
};

Department of Computer Engineering 1-241


SNJB’s Late Sau. K. B. J. College of Engineering
Abstract Data Type and Encapsulation Constructs
● Design issues for Abstraction,
● Parameterized Abstract Data types,
● Encapsulation Constructs,
● Naming Encapsulations

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The Concept of Abstraction
● An abstraction is a view or representation of an entity that includes only the
most significant attributes
● The concept of abstraction is fundamental in programming (and computer
science)
● Nearly all programming languages support process abstraction with
subprograms
● Nearly all programming languages designed since 1980 support data
abstraction
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Introduction to Data Abstraction
● An abstract data type is an enclosure that includes only the
○ data representation of one specific data type and
○ the subprograms that provide the operations for that type
● An instance of an abstract data type is called an object.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Floating-Point as an Abstract Data Type
● The type name, double, real, float, …
○ specifies the data representation
○ specifies valid operations
○ hides the implementation of the data representation
○ hides the implementation of the operations

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
User-Defined Abstract Data Types
● An abstract data type is a user-defined data type that satisfies the
following two conditions: –
○ The representation of, and operations on, objects of the type are
defined in a single syntactic unit
○ The representation of objects of the type is hidden from the program
units that use these objects, so the only operations possible are those
provided in the type's definition

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
User-Defined Abstract Data Types
● Advantage of the first condition
○ Program organization, modifiability (everything associated with a data
structure is together), and separate compilation
● Advantage the second condition
○ Reliability--by hiding the data representations, user code cannot
directly access objects of the type or depend on the representation,
allowing the representation to be changed without affecting user code

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Language Requirements for ADT
● A syntactic unit in which to encapsulate the type definition
● A method of making type names and subprogram headers visible to
clients, while hiding actual definitions
● Some primitive operations must be built into the language processor

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Language Examples- Abstract Data Types in C++
● Based on C struct type and Simula 67 classes
● The class is the encapsulation device
● All of the class instances of a class share a single copy of the member
functions
● Each instance of a class has its own copy of the class data members
● Instances can be static, stack dynamic, or heap dynamic

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Language Examples- Abstract Data Types in C++
● Information Hiding –
○ Private clause for hidden entities
○ Public clause for interface entities
○ Protected clause for inheritance

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Parameterized Abstract Data Types

● Parameterized ADTs allow designing an ADT that can store any type elements
(among other things) – only an issue for static typed languages
● Also known as generic classes
● C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Parameterized Abstract Data Types -C++

class Stack {
Classes can be somewhat …
Stack (int size)
generic by writing
{
parameterized constructor stk_ptr = new int [size];
functions max_len = size - 1;
top = -1;
};

}
Stack stk(100);
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Parameterized Abstract Data Types -C++
template class<T>
class Stack {
int size; //Number of available elements to implement the stack
int tos; //Index of the element on top of the stack
T* S; //An array of integers used to implement the stack
Public:
Stack(int sz=100):size(sz),tos(-1){S=new T[size];}
~Stack () {if (S) delete [] S;}
bool empty(void){return tos<0;}
bool full(void){return tos>=size-1;}

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Parameterized Abstract Data Types -C++
void push (T v)
{
if (full()) throw StackException(“full”);
S[++tos]=v;
}
void pop () . . Stack S;
{
if (empty()) throw StackException(“empty”);
S.push(15);
tos--;
}
T top (void)
{
if (empty()) throw StackException(“empty”);
return S[tos];
}
};

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Encapsulation Constructs

● Large programs have two special needs:


○ Some means of organization, other than simply division into subprograms
○ Some means of partial compilation (compilation units that are smaller than
the whole program)
● Obvious solution: a grouping of subprograms that are logically related into a
unit that can be separately compiled (compilation units) Such collections are
called encapsulation

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Encapsulation Constructs :Nested Subprograms

● Organizing programs by nesting subprogram definitions inside the logically larger


subprograms that use them
● Nested subprograms are supported in Ada, Fortran 95, Python, and Ruby

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Encapsulation Constructs :Encapsulation in C

● Files containing one or more subprograms can be independently compiled The


interface is placed in a header file
● Problem: the linker does not check types between a header and associated
implementation
● #include preprocessor specification – used to include header files in applications

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Encapsulation Constructs :Encapsulation in C++

● Can define header and code files, similar to those of C


● Or, classes can be used for encapsulation
○ The class is used as the interface (prototypes)
○ The member definitions are defined in a separate file
● Friends provide a way to grant access to private members of a class

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Encapsulation Constructs :Encapsulation in Ada Packages

● Ada specification packages can include any number of data and subprogram
declarations
● Ada packages can be compiled separately
● A package’s specification and body parts can be compiled separately

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Naming Encapsulations

● Large programs define many global names need a way to divide into logical
groupings
● A naming encapsulation is used to create a new scope for names

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Naming Encapsulations : C++ Namespaces

● Can place each library in its own namespace and qualify names used outside with
the namespace
● C# also includes namespaces

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Naming Encapsulations : Java Packages

● Packages can contain more than one class definition; classes in a package are
partial friends
● Clients of a package can use fully qualified name or use the import declaration

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Naming Encapsulations : Ada Packages

● Packages are defined in hierarchies which correspond to file hierarchies


● Visibility from a program unit is gained with the with clause

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Summary

● The concept of ADTs and their use in program design was a milestone in the development of
languages
● Two primary features of ADTs are the packaging of data with their associated operations and
information hiding
● Ada provides packages that simulate ADTs
● C++ data abstraction is provided by classes
● Java’s data abstraction is similar to C++
● Ada, C++, Java 5.0, and C# 2005 support parameterized ADTs
● C++, C#, Java, Ada, and Ruby provide naming encapsulations

Department of Computer Engineering

You might also like