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

PPL_Unit_2_ppt

Unit II covers the structuring of data, computations, and programming concepts, including elementary data types, expressions, control statements, subprograms, and abstract data types. It details various primitive data types across programming languages, such as numeric, boolean, character, and string types, along with their representations and design issues. The document also discusses user-defined ordinal types, arrays, and their initialization and design considerations.

Uploaded by

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

PPL_Unit_2_ppt

Unit II covers the structuring of data, computations, and programming concepts, including elementary data types, expressions, control statements, subprograms, and abstract data types. It details various primitive data types across programming languages, such as numeric, boolean, character, and string types, along with their representations and design issues. The document also discusses user-defined ordinal types, arrays, and their initialization and design considerations.

Uploaded by

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

Structuring the Data,

Computations and Program


Unit II
Unit II
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.
Primitive data Types
• Data types that are not defined in terms of other types are called primitive data types.
• To specify the structured types, the primitive data types of a language are used, along with one or
more type constructors.

• Nearly all programming languages provide a set of primitive data types.

• There are 8 primitive data types in Java: byte, char, short, int, long, float, double and Boolean

• In C, there are 4 types Basic (int, float, char, double).

• In python there are 4 primitive data types integer, floating, Boolean, string.
Primitive data Types (Cont’d)

Fig 2.1 : Primitive Datatype in C


Primitive data Types (Cont’d)
Primitive data Types (Cont’d)
1. Numeric Types
a) Integer
b) Floating point
c) Complex
d) Decimal

2. Boolean Types

3. Character Types
Numeric Types : Integer
• The most common primitive numeric data type is integer

• Java includes four signed integer sizes: byte, short, int, and long.

• Some languages, for example, C++ and C#, include unsigned integer types, which are simply
types for integer values without signs. Unsigned types are often used for binary data.

• A signed integer value is represented in a computer by a string of bits, with one of the bits
(typically the leftmost) representing the sign.

• A negative integer could be stored in sign-magnitude notation, in which the sign bit is set to
indicate negative and the remainder of the bit string represents the absolute value of the
number.
Numeric Types : Integer
• Signed Magnitude representation
The value of the whole numbers can be determined by the sign
used before it. If the number has ‘+’ sign or no sign it will be considered as
positive. If the number has ‘–’ sign it will be considered as negative.

Example:
+43 or 43 is a positive number
–43 is a negative number

In signed binary representation, the left most bit is considered as sign bit.

If this bit is 0, it is a positive number and if it 1, it is a negative number.


Therefore a signed binary number has 8 bits, only 7 bits used for storing values
(magnitude) and the 1 bit is used for sign.
Numeric Types : Integer
• 1’s Complement representation
This is an easier approach to represent signed numbers. This is for negative numbers
only i.e. the number whose MSB is 1.

Step 1: Convert given Decimal number into Binary

Step 2: Check if the binary number contains 8 bits, if less


add 0 at the left most bit, to make it as 8 bits.

Step 3: Invert all bits (i.e. Change 1 as 0 and 0 as 1)


Numeric Types : Integer
• 2’s Complement representation
The 2’s-complement method to store negative number is
as follows:

Step 1: Invert all the bits in the binary sequence


(i.e., change every 0 to1 and every 1 to 0 ie.,1’s complement)

Step 2: Add 1 to the result to the Least Significant Bit (LSB).


Numeric Types : Integer
Numeric Types : Floating-point
• Floating-point values are represented as fractions and exponents, a form that is borrowed from scientific notation.

• Most languages include two floating-point types, often called float and double.

• The float type is the standard size, usually being stored in four bytes of memory.

• The double type is provided for situations where larger fractional parts and/or a larger range of exponents is needed.

• The collection of values that can be represented by a floating-point type is defined in terms of precision and range.

• Precision is the accuracy of the fractional part of a value, measured as the number of bits.

• Range is a combination of the range of fractions and, more important, the range of exponents.
Numeric Types : Floating-point
• IEEE Floating-Point Standard 754 format
Older computers used a variety of different representations for floating-point values.
However, most newer machines use the IEEE Floating-Point Standard 754 format.

IEEE floating point representation for binary real numbers consists of three parts (Single/Double
precision).

1.Sign

2. Mantissa/Fraction/significand

3. Exponent
Numeric Types : Floating-point
Numeric Types : Complex
• Some programming languages support a complex data type—for example,
Fortran and Python.

• Complex values are represented as ordered pairs of floating-point values.

• In Python, the imaginary part of a complex literal is specified by following it with


a j or J—for example, (7 + 3j)
Numeric Types : Decimal
• Decimal data types store a fixed number of decimal digits, with the decimal point at a fixed position in the
value.

• The decimal module provides support for fast correctly-rounded decimal floating point arithmetic.

• Decimal(p, s) where,
• p – precision – the total number of digits
• s – scale - the number of digits in the fractional part

• Store a fixed number of decimal digits (coded) using BCD system.

• Advantage: accuracy

• Disadvantages: limited range, wastes memory

• E.g. Support Business system applications – Cobol. C# has a decimal data type
Boolean Types

• It is used to store only two possible values, either true or


false, represented by a single bit (1-bit information)

• It is generally associated with conditional statements.

• It is used to represent switches or flags in programs.

• The Boolean keyword is used with variables and methods.

• Its default value is false


Character Types
• Character data are stored in computers as numeric codings - used to declare the character-type variables and
methods.

• Traditionally, 8-bit code ASCII, which uses the values 0 to 127 to code 128 different characters.
• ISO 8859-1 is another 8-bit character code, but it allows 256 different characters.
• In 1991, the Unicode Consortium published the UCS-2 standard (Unicode), a 16-bit character set – (unsigned
16-bit Unicode characters.)

• Unicode includes the characters from most of the world’s natural languages. For example, Unicode includes the
Cyrillic alphabet, as used in Serbia, and the Thai digits - first 128 characters of Unicode are identical to those of
ASCII

• To provide the means of processing coding of single characters, most programming languages include a primitive
type for them

• Its default size is 2 byte in java.


Character Types
Character String Types
• The string type is used to store a sequence of characters (text).

• This is not a built-in type, but it behaves like one in its most basic usage. String values must be
surrounded by double quotes.

• C and C++ use char arrays to store character strings.

• Library functions that produce strings often supply the null character.

• char *str = "apples"; char str1[] = “apples”;


• str is an array of char elements, specifically apples0, where 0 is the null character.
Character String Types : Design Issues
• The two most important design issues that are specific to character string types are
the following:

• Should strings be a special kind of character array or a primitive type?

• Should strings have static or dynamic length?


Character String Types
• String Typical Operations

• Assignment

• Comparison (=, >, etc.)

• Concatenation or Catenation

• Substring reference

• Pattern matching
Character String Types
• Some of the most commonly used library functions for character strings in C and C++ are

• strcpy: copy strings

• strcat: catenates on given string onto another

• strcmp: lexicographically compares (the order of their codes) two strings o

• strlen: returns the number of characters, not counting the null –In Java, strings are supported as a
primitive type by String class
Character String Types
• strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in
string.h header file and in C++ it is present in cstring header file.
• strcpy(dest, src); dest: Pointer to the destination array where the content is to be copied.
src: string which will be copied.
Character String Types
Character String Types
Character String Types
Character String Types : String Length Options
There are several design choices regarding the length of string values:

1. Static length string : The length can be static and set when the string is created.
Such a string is called a static length string.
• E.g. the immutable objects of Java’s String class, as well as similar classes in the C++ standard
class library. Python, Ruby’s built-in String class, and the .NET class library available to C#
and F#.

2. Limited dynamic length strings : This option is to allow strings to have varying
length up to a declared and fixed maximum set by the variable’s definition

3. Dynamic length strings : This option is to allow strings to have varying length with
no maximum set.
• E.g. JavaScript, Perl, and the standard C++ library.
Character String Types : Evaluation
• String types are important to the writability of a language.

• The addition of strings as a primitive type to a language is not costly in terms of


either language or compiler complexity. Therefore, it is difficult to justify the
omission of primitive string types in some contemporary languages.

• Providing strings through a standard library is nearly as convenient as having them


as a primitive type.

• String operations such as simple pattern matching and concatenation are essential
and should be included for string type values.

• Dynamic length strings are obviously the most flexible, the overhead of their
implementation must be weighed against that additional flexibility.
Character String Types : Implementation
A descriptor for a static character string type, which is required only during
compilation, has three fields.
• The first field of every descriptor is the name of the type.
• In the case of static character strings, the second field is the type’s
length (in characters).
• The third field is the address of the first character.

Limited dynamic strings require a run-time descriptor to store both the


fixed maximum length and the current length

Dynamic length strings require a simpler run-time descriptor because


only the current length needs to be stored. Although we depict
descriptors as independent blocks of storage, in most cases, they are
stored in the symbol table.
Character String Types : Implementation
• Dynamic length requires more complex storage
management.

• The length of a string, and therefore the storage


to which it is bound , must grow and shrink
dynamically.

• There are three possible approaches to the dynamic


allocation problem:
Character String Types : Implementation
User-Defined Ordinal Types
• An ordinal type is one in which the range of possible values can be easily associated with
the set of positive integers.

• In Java, for example, the primitive ordinal types are integer, char, and boolean.

• There are two user-defined ordinal types that have been supported by programming
languages: enumeration and subrange.
User-Defined Ordinal Types : Enumeration
• An enumeration type is one in which all of the possible values, which are named constants,
are provided, or enumerated, in the definition.

• It provide a way of defining and grouping collections of named constants, which are
called enumeration constants.

• The enumeration constants are typically implicitly assigned the integer values, 0, 1, . . . . .

• It can be used for days of the


Week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) ,
Directions (NORTH, SOUTH, EAST, and WEST),
Season (SPRING, SUMMER, WINTER, and AUTUMN),
Colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK)
User-Defined Ordinal Types : Enumeration
• Design Issues

The design issues for enumeration types are as follows:

• 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 in the program checked?

• Are enumeration values coerced to integer?

• Are any other types coerced to an enumeration type?


User-Defined Ordinal Types : Enumeration
User-Defined Ordinal Types : Enumeration
User-Defined Ordinal Types : Enumeration
User-Defined Ordinal Types : Enumeration
User-Defined Ordinal Types : Enumeration
• Enumeration Evaluation

• Enumeration types can provide advantages in both readability and reliability.

• Readability is enhanced very directly: Named values are easily recognized, whereas coded values are not.

• Reliability: the enumeration types of Ada, C#, F#, and Java 5.0 provide two advantages
(1) No arithmetic operations are legal on enumeration types; this prevents adding days of the week
(2) No enumeration variable can be assigned a value outside its defined range

• C treats enumeration variables like integer variables, it does not provide either of these two advantages

• C++ is a little better. Numeric values can be assigned to enumeration type variables only if they are cast to the
type of the assigned variable.
enum colors {red = 1, blue = 1000, green = 100000}
User-Defined Ordinal Types : Subrange Types
• A subrange type is a contiguous subsequence of an ordinal type. For example, 12……18 is a
subrange of integer type. Subrange types were introduced by Pascal and are included in Ada.
• There are no design issues that are specific to subrange types.

• In Ada, subranges are included in the category of types called subtypes.


• type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
• subtype Weekdays is Days range Mon..Fri;
• subtype Index is Integer range 1……..100;

• Subrange types enhance readability by making it clear to readers that variables of subtypes can store
only certain ranges of values.

• Reliability is increased with subrange types, because assigning a value to a subrange variable that is
outside the specified range is detected as an error, either by the compiler (in the case of the assigned
value being a literal value) or by the run-time system (in the case of a variable or expression).
Array Types
• An array is a homogeneous aggregate of data elements in which an individual element is identified by its
position in the aggregate, relative to the first element.

• The individual data elements of an array are of the same type.

• References to individual array elements are specified using subscript expressions.

• If any of the subscript expressions in a reference include variables, then the reference will require an
additional run-time calculation to determine the address of the memory location being referenced.

• In many languages, such as C, C++, Java, Ada, and C#, all of the elements of an array are required to be of
the same type.

• In these languages, pointers and references are restricted to point to or reference a single type. So the objects or
data values being pointed to or referenced are also of a single type.
Array Types : Initialization of Array
Array Types : Design Issues
• The primary design issues specific to arrays are the following:

• What types are legal for subscripts?

• Are subscripting expressions in element references range checked?

• When are subscript ranges bound?

• When does array allocation take place?

• Are ragged or rectangular multi-dimensioned arrays allowed, or both?

• Can arrays be initialized when they have their storage allocated?

• What kinds of slices are allowed, if any?


Array Types : Rectangular and Jagged Arrays

A rectangular array is a multidimensional array in which all of


the rows have the same number of elements and all of the columns
have the same number of elements. Rectangular arrays model
rectangular tables exactly.

A jagged array is one in which the lengths of the rows need


not be the same. For example, a jagged matrix may consist of
three rows, one with 5 elements, one with 7 elements, and
one with 12 elements.
Array Types : Slices
• A slice of an array is some substructure of that array.

• It is important to realize that a slice is not a new data type. Rather, it is a mechanism for referencing part of
an array as a unit.

• Consider the following Python declarations:


Array Types : Slices
• The copyOfRange() method of the java.util.Arrays class accepts an array, two integers representing start
and end indexes and returns a slice of the given array which is in between the specified indexes.
Array Types : Slices
• Ruby supports slices with the slice method of its Array object, which can take three forms of parameters.

• A single integer expression parameter is interpreted as a subscript, in which case slice returns the element
with the given subscript.

• If slice is given two integer expression parameters, the first is interpreted as a beginning subscript and the
second is interpreted as the number of elements in the slice.
Array Types
• Subscript Bindings and Array Categories

• The binding of the subscript type to an array variable is usually static, but the
subscript value ranges are sometimes dynamically bound.

• There are five categories of arrays, based on the binding to subscript ranges, the
binding to storage, and from where the storage is allocated.

• The category names indicate the design choices of these three. In the first four of
these categories, once the subscript ranges are bound and the storage is allocated, they
remain fixed for the lifetime of the variable.
Array Types : Array Categories
1. A static array is one in which the subscript ranges are statically bound and storage
allocation is static (done before run time).

• Advantage – efficiency : No dynamic allocation or deallocation is required.

• Disadvantage - storage for the array is fixed for the entire execution time of the
program.

• E.g. Arrays declared in C and C++ functions that include the static modifier are
static.
static int myarray[3] = {2, 3, 4};
Array Types : Array Categories
2. A fixed stack-dynamic array is one in which the subscript ranges are statically
bound, but the allocation is done at declaration elaboration time during
execution.

• Advantage - space efficiency. A large array in one subprogram can use the
same space as a large array in a different subprogram

• Disadvantage - the required allocation and deallocation time.

• E.g. arrays without static modifier are fixed stack‐dynamic

int array[3] = {2, 3, 4};


Array Types : Array Categories
3. A stack-dynamic array is one in which both the subscript ranges and the storage
allocation are dynamically bound at (declaration)elaboration time.

• Once the subscript ranges are bound and the storage is allocated, however, they
remain fixed during the lifetime of the variable.

• Advantage – flexibility - The size of an array need not be known until the array is
about to be used.

• E.g. In Ada, you can use stack‐dynamic arrays as

Get(List_Len);
declare
List: array (1..List_Len) of Integer
begin
...
end;
Array Types : Array Categories
4. A fixed heap-dynamic array is similar to a fixed stack-dynamic array, in that the
subscript ranges and the storage binding are both fixed after storage is allocated.
• i.e. subscript ranges and storage bindings are done when the user program requests them
during execution, and the storage is allocated from the heap, rather than the stack.

• Advantage - flexibility—the array’s size always fits the problem.


• Disadvantage - allocation time from the heap, which is longer than allocation
time from the stack.

• E.g. In C/C++, using malloc/free to allocate/deallocate memory from the heap


• Java has fixed heap dynamic arrays
• C# includes a second array class ArrayList that provides fixed heap‐dynamic
Array Types : Array Categories
5. A heap-dynamic array is one in which the binding of subscript ranges and
storage allocation is dynamic and can change any number of times during
the array’s lifetime.

• Advantage - flexibility: Arrays can grow and shrink during program execution
as the need for space changes.
• Disadvantage - allocation and deallocation take longer and may happen many
times during execution of the program

• E.g.: Perl, JavaScript, Python, and Ruby support heap‐dynamic arrays


Perl: @states = (“Idaho", “Washington", “Oregon");
Python: a = [1.25, 233, 3.141519, 0, ‐1]
Array Types : Array Operations
• An array operation is one that operates on an array as a unit. The most common array
operations are assignment, catenation, comparison for equality and inequality,
and slices.

• The C-based languages do not provide any array operations, except through the
methods of Java, C++, and C#.

• Perl supports array assignments but does not support comparisons.

• Ada allows array assignments, including those where the right side is an aggregate
value rather than an array name. Ada also provides catenation, specified by the
ampersand (&).
Array Types : Array Operations
• Python’s arrays are called lists, although they have all the characteristics of
dynamic arrays. Python also has operations for array catenation (+) and element
membership (in).

• Ruby’s arrays are references to objects. when == operator is used between two
arrays, the result is true only if the two arrays have the same length and the
corresponding elements are equal. Ruby’s arrays can be catenated with an Array
method.

• F# includes many array operators in its Array module. Among these are
Array.append, Array.copy, and Array.length.
Array Types : Array Operations
• APL - most powerful array processing operations for vectors and matrices

• Arrays and their operations are the heart of APL

• the most powerful array-processing language ever devised

• Four basic arithmetic operations are defined for vectors (single-dimensioned


arrays) and matrices, as well as scalar operands.

• For example,
A + B is a valid expression, whether A and B are scalar variables,
vectors, or matrices.
Array Types : Implementation
Memory for Array

• For 1D arrays
• contiguous block of memory with equal amount of space for each element

• Two approaches for multi‐dimensional arrays


• Single block of contiguous memory for all elements
• Arrays must be rectangular
• Address of array is starting memory location

• Implement as arrays of arrays (Java)


• Jagged arrays are possible
• Array variable is a pointer (reference)
Array Types : Implementation
Array Types : Implementation
• Access function maps subscript expressions to an
address in the array
• For int myarray[5]; what address does myarray[3]
map to

• Access function for single ‐dimensioned arrays:


Array Types : Implementation
• Memory Allocation for 2D Array

• Two common ways to organize 2D arrays

• Row major order (by rows) – used in most languages

• Column major order (by columns) – used in Fortran


Array Types : Implementation
• Memory Allocation for 2D Array
Array Types : Implementation
• Locating an Element in a 2D Array

• Access Function of 2D Array


Array Types : Implementation
Associative Array

➢ An associative array is an unordered collection of data


elements that are indexed by an equal number of values
called keys.

➢ In the case of non-associative arrays, the indices never


need to be stored (because of their regularity).

➢ In an associative array, however, the user-defined keys


must be stored in the structure. So each element of an
associative array is in fact a pair of entities, a key and a
value.
Associative Array
➢ Perl also allows us to create arrays which are accessed by string.

➢ To define an associative array we use the usual parenthesis notation, but the array itself is
prefixed by a % sign. Suppose we want to create an array of people and their ages.

➢ It would look like this


Associative Array
➢ Data structure, which allows to use an arbitrary type of index instead of numerical, is called dictionary or
associative array. The corresponding data structure in Python is calleddict.

➢ Consider a simple example. Get the dictionary Capitals, where index is the name of the country, and the
value — the name of the capital of this country. Now for a row with the name of the country we can easily
idenify its capital.
Associative Array

➢ Associative array will have their index as string so that you can establish a strong
association between key and values. The associative arrays have names keys that is assigned
to them.

➢ To implement Associative Arrays in PHP, the code is as follows−


Record Types

➢ A record is an aggregate of data elements in which the individual elements are identified by
names and accessed through offsets from the beginning of thestructure.

➢ The fundamental difference between a record and an array is that record elements, or fields, are not
referenced by indices.

➢ Instead, the fields are named with identifiers, and references to the fields are made using these
identifiers.

➢ In C, C++, and C#, records are supported with the struct data type.

➢ In C++, structures are a minor variation on classes.


Record Types
➢ The COBOL form of a record declaration, which is part of the data division of a COBOL program, is illustrated
in the following example:

➢ The EMPLOYEE-RECORD record consists of the EMPLOYEE-NAME record and the HOURLY-RATE field.

➢ The numerals 01, 02, and 05 that begin the lines of the record declaration are level numbers, which indicate by their
relative values the hierarchical structure of the record.

➢ PICTURE clauses show the formats of the field storage locations, with X(20)specifying 20 alphanumeric
characters and 99V99 specifying four decimal digits with the decimal point in the middle.
Record Types
➢ Ada uses a different syntax for records; rather than using the level numbers of COBOL, record structures
are indicated in an orthogonal way by simply nesting record declarations inside record declarations.

➢ In Ada, records cannot be anonymous—they must be named types. Consider the followingAda declaration
Record Types
Definition of Records in C++
• Nested example (more similar to Ada)
Record Types
➢ In Java and C#, records can be defined as data classes, with nested records defined as nested
classes.

➢ Data members of such classes serve as the record fields.

➢ For example, consider the following declaration:

employee.name = "Freddie"
employee.hourlyRate = 13.20

These assignment statements create a table (record) named employee with two elements (fields)
named name and hourlyRate, both initialized.

Design Issues
• What is the syntactic form of references to the field?

• Are elliptical references allowed?


Record Types : References to Records
Records : Operations

• Assignment is very common if the types are identical

• Ada allows record comparison

• Ada records can be initialized with aggregate literals

• COBOL provides MOVE CORRESPONDING


• Copies a field of the source record to the corresponding field in the target record
Records : Evaluation

• Records are frequently valuable data types in programming languages. The design of
record types is straightforward, and their use is safe.

• Records are used when collection of data values is heterogeneous

• Access to array elements is much slower than access to record fields, because subscripts
are dynamic (field names are static)

• Dynamic subscripts could be used with record field access, but it would disallow type
checking and it would be much slower
Records : Implementation
Union Types
➢ A union is a type whose variables may store different type values at different times during program
execution

➢ Like Structures, union is a user defined data type. In union, all members share the same memory
location.

➢ Structures allocate enough space to store all their members, whereas unions can only hold one member
value at a time.

➢ How to define a union?


We use the union keyword to define unions. Here's an example:

code defines a derived type union car.


Union Types
➢ When a union is defined, it creates a user-defined type.
➢ However, no memory is allocated.
➢ To allocate memory for a given union type and work with it, we need to create variables.
➢ Here's how we create union variables.
Union Types
Union Types

Design Issues

➢ The problem of type checking union types, is the major design issue.

➢ The other fundamental question is how to syntactically represent a union.

➢ In some designs, unions are confined to be parts of record structures, but in others they are
not.

➢ So, the primary design issues that are particular to union types are the following:

• Should type checking be required? Note that any such type checking must be
dynamic.

• Should unions be embedded in records?


Union Types
Discriminated Versus Free Unions
➢ Fortran, C and C++ provide union constructs in which there is no language support for type checking. In C and C++,
the union construct is used to specify union structures and in Fortran Equivalence statement.

➢ The unions in these languages are called free unions, because programmers are allowed complete freedom from type
checking in their use.

➢ For example, consider the following C union:

• Type checking of unions requires that each union construct include a type
indicator.

• Such an indicator is called a tag, or discriminant, and a union with a discriminant


is called a discriminated union.

• The first language to provide discriminated unions was ALGOL 68.

• They are now supported by Ada, ML,Haskell, and F#.


Union Types
Example of Discriminated Union
Union Types
Ada Union Types
➢ The Ada design for discriminated unions, which is based on that of its predecessor language, Pascal.

➢ It allows the user to specify variables of a variant record type that will store only one of the possibletype
values in the variant
Union Types
Union Types
Unions in F#
➢ A union is declared in F# with a type statement using OR operators (|) to define thecomponents.
For example, we could have the following:

➢ In this example, intReal is the union type. IntValue and RealValue are constructors. Values of type
intReal can be created using the constructors as if they were a function, as in the followingexamples
Union Types
Unions in F#
➢ To display the type of the intReal union, the following function could be used:
Union : Evaluation

• Unions are potentially unsafe constructs in some languages.


• They are one of the reasons why C and C++ are not strongly typed: These languages do not
allow type checking of references to their unions.

• On the other hand, unions can be safely used, as in their design in ML, Haskell, and F#.

• Neither Java nor C# includes unions, which may be reflective of the growing concern for
safety in some programming languages.
Union : Implementation

• Unions are implemented by simply using the same address for every
possible variant.

• Sufficient storage for the largest variant is allocated.


Pointer and Reference Types

What are Pointers?


➢ A pointer is a variable whose value is the address of anothervariable.
➢ A pointer type is one in which the variables have a range of values that consists of memory addresses and
a special value, nil.
➢ Pointers are designed for two distinct kinds of uses.
1. pointers provide some of the power of indirect addressing.
2. pointers provide a way to manage dynamic storage.
➢ A pointer can be used to access a location in an area where storage is dynamically allocated called a heap.
➢ Variables that are dynamically allocated from the heap are called heap dynamic variables.
➢ Variables without names are called anonymous variables.
Pointer and Reference Types: Design Issues

The primary design issues particular to pointers are the following:

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

• What is the lifetime of a heap-dynamic variable (the value a pointer references)?

• 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?


Pointer and Reference Types: 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
o Dereferencing can be explicit or implicit
o C++ uses an explicit operation via *
o j = *ptr
o sets j to the value located at ptr
Pointer and Reference Types: Pointer Operations

• Languages that provide a pointer type usually include two fundamental pointer
operations:
1. assignment and
2. dereferencing

• The first operation sets a pointer variable’s value to some useful address.
• If pointer variables are used only to manage dynamic storage, then the
allocation mechanism, whether by operator or built-in subprogram, serves
to initialize the pointer variable.

• If pointers are used for indirect addressing to variables that are not heap
dynamic, then there must be an explicit operator or built-in subprogram
for fetching the address of a variable, which can then be assigned to the
pointer variable.
Pointer and Reference Types: Pointer Operations

• An occurrence of a pointer variable in an expression can be interpreted in two


distinct ways:-
1. It could be interpreted as a reference to the contents of the memory cell to
which it is bound, which in the case of a pointer is an address.
2. The pointer also could be interpreted as a reference to the value in the
memory cell pointed to by the memory cell to which the pointer variable is
bound. In this case, the pointer is interpreted as an indirect reference.

• The former case is a normal pointer reference; the latter is the result of
dereferencing the pointer. Dereferencing, which takes a reference through one
level of indirection, is the second fundamental pointer operation.
Pointer and Reference Types

➢ In C++, it is explicitly specified with the asterisk (*) as a prefix unary operator. Consider the
following example of dereferencing:
➢ If ptr is a pointer variable with the value 7080 and the cell whose address is 7080 has the value 206,

then the assignment

j = *ptr
sets j to 206. This process is shown in Figure
Pointer and Reference Types
Using Pointers in C++
➢ The asterisk you used to declare a pointer is the same asterisk that you use for multiplication.
➢ However, in this statement the asterisk is being used to designate a variable as a pointer.
➢ Following are the valid pointer declaration −

➢ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the
same, a long hexadecimal number that represents a memory address.

➢ The only difference between pointers of different data types is the data type of the variable or constant
that the pointer points to
Pointer and Reference Types
Using Pointers in C++
Pointer and Reference Types
Using Pointers in C++
When the code is compiled and executed, it produces
result something as follows −
Pointer and Reference Types
Dangling Pointers

➢ Dangling pointers in computer programming are pointers that


pointing to a memory location that has been deleted (or
freed).

➢ Dangling pointers arise during object destruction, when an object


that has an incoming reference is deleted or deallocated, without
modifying the value of the pointer, so that the pointer still points to
the memory location of the deallocated memory.

➢ The system may reallocate the previously freed memory,


unpredictable behavior may result as the memory may now contain
completely different data.
Pointer and Reference Types
Dangling Pointers
Pointer and Reference Types
Reference Types
References vs Pointers
➢ A pointer refers to an address in memory, while a reference refers to an object or a value in memory.

➢ References are often confused with pointers but three major differences between references and pointers are

1. You cannot have NULL references. You must always be able to assume that a reference is connected to
a legitimate piece of storage.
2. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers
canbe pointed to another object at any time.

3. A reference must be initialized when it is created. Pointers can be initialized at anytime.


Pointer and Reference Types
Reference Types
➢ Creating References in C++
➢ you can access the contents of the variable
through either the original variable name or the
reference. For example, suppose we have the
following example −

int i = 17;
We can declare reference variables for i as follows.
int& r = i;
Expressions and Assignment
Statements Reference Types

➢ Expressions are used to compute the mathematical calculations or it is used to apply some
conditionin programming languages

➢ Expression executions are dependent on priority and precedence rule.

➢ These rules are predefined and common to all languages.

➢ Assignment statements are used to assign the value of expression or use to assign some fix value to
variables.
Arithmetic Expressions
➢ Most of the characteristics of arithmetic expressions in programming languages were inherited from
conventions that had evolved in mathematics.
➢ In programming languages, arithmetic expressions consist of operators, operands, parentheses, and
function calls.

➢ An operator can be unary, meaning it has a single operand, binary, meaning it has two operands, or
ternary, meaning it has three operands.
[ Unary :- (i++), Binary: (a + b), Ternary: (a > b ? a : b) ]
➢ In most programming languages, binary operators are infix, which means they appear between their
operands. some operators that are prefix, which means they precede their operands.
[infix example, A + B * C ] [prefix example, + A * B C]
➢ The purpose of an arithmetic expression is to specify an arithmetic computation.
➢ An implementation of such a computation must cause two actions: fetching the operands, usually from
memory, and executing arithmetic operations on those operands
Arithmetic Expressions

Design Issues

• What are the operator precedence rules?

• What are the operator associativity rules?

• What is the order of operand evaluation?

• Are there restrictions on operand evaluation side effects?

• Does the language allow user-defined operator overloading?

• What type mixing is allowed in expressions?


Arithmetic Expressions: Operator Evaluation order
Precedence
➢ The value of an expression depends at least in part on the order of evaluation of the operators in the
expression.
➢ The operator precedence rules for expression evaluation partially define the order in which the operatorsof
different precedence levels are evaluated.

➢ The operator precedence rules for expressions are based on the hierarchy of operator priorities, as seen by the
language designer. The operator precedence rules of the common imperative languages are nearly all the
same, because they are based on those of mathematics.

➢ In these languages, exponentiation has the highest precedence, followed by multiplication and division on
the same level, followed by binary addition and subtraction on the same level.
Arithmetic Expressions: Operator Evaluation order
Precedence
➢ Precedence order. When two operators share an operand the operator with the higher precedence goes first.
For example, 1 + 2 * 3 is treated as 1 + (2 * 3),
whereas 1 * 2 + 3 is treated as (1 * 2) + 3
since multiplication has a higher precedence than addition.

The precedences of the arithmetic operators of Ruby and the C-based languages are as follows
Arithmetic Expressions: Operator Evaluation order
Associativity

➢ When an expression has two operators with the same precedence, the expression is evaluated
according to its associativity.
For example x = y = z = 17 is treated as x = (y = (z = 17)),
leaving all three variables with the value 17,
since the = operator has right-to-left associativity
On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3
since the / operator has left-to-right associativity.
Arithmetic Expressions: Operator Evaluation order
Parentheses
➢ Programmers can alter the precedence and associativity rules by placing parentheses in expressions.

➢ A parenthesized part of an expression has precedence over its adjacent unparenthesized parts.
For example, (A + B) * C
although multiplication has precedence over addition, in the expression the addition will be evaluated
first. Mathematically, this is perfectly natural

➢ Languages that allow parentheses in arithmetic expressions could dispense with all precedence rules and
simply associate all operators left to right or right to left.

➢ Disadvantage of this scheme is that it makes writing expressions more tedious, and it also seriously
compromises the readability of the code.
Arithmetic Expressions: Operator Evaluation order
Conditional Expressions

• if-then-else statements can be used to perform a conditional expression assignment.

• Ternary operator, ?: used to form conditional expressions


Arithmetic Expressions

Operand Evaluation Order

➢ Variables in expressions are evaluated by fetching their values from memory.

➢ Constants are sometimes evaluated the same way.

➢ In other cases, a constant may be part of the machine language instruction and not

require a memory fetch.

➢ If an operand is a parenthesized expression, all of the operators it contains must be


evaluated before its value can be used as an operand.
Overloaded Operators

➢ Arithmetic operators are often used for more than one purpose. For example, + usually is used to specify
integer addition and floating-point addition. Some languages—Java, for example—also use it for string
catenation. This multiple use of an operator is called operator overloading and is generally thought to be
acceptable, as long as neither readability nor reliability suffers.
➢ As an example of the possible dangers of overloading, consider the use of the ampersand (&) in C++. As a
binary operator, it specifies a bitwise logical AND operation.
➢ As a unary operator with a variable as its operand, the expression value is the address of that variable. In this
case, the ampersand is called the address-of operator.

For example, the execution of


x = &y;
causes the address of y to be placed in x.
What is Operator Overloading in C++?
➢ Have you ever wondered about this type of code – why
is z== 15 and s3== Abhigautam? This is because
operators have different meanings for different types

of operands.
➢ For an integer type, the + operator gives the sum of
two numbers, and for the string type it concatenates
(joins) them.

➢ So, operator overloading is all about giving new


meaning to an operator.
➢ But: 1) You cannot set new meaning to an operator
for a built-in type.
➢ C++ has a few operators that cannot be overloaded.
2)You cannot create new operators.
Among these are the class or structure member
operator (.) and the scope resolution operator (::).
Overloaded Operators

➢ Interestingly, operator overloading was one of the C++ features that was not copied into
Java.
➢ Java doesn't supports operator overloading because it's just a choice made by its
creators who wanted to keep the language more simple.
➢ Every operator has a good meaning with its arithmetic operation it performs.
➢ Operator overloading allows you to do something extra than what for it is
expected for.
➢ Java only allows arithmetic operations on elementary numeric types.
➢ If you allow a developer to do operator overloading they will come up with multiple
meanings for the same operator which will make the learning curve of any developer
hard and things more confusing and messy.
Type Conversions
➢ The process of converting the value of one data type (integer, string, float, etc.) to another data type is called
type conversion. Python has two types of type conversion.

• Implicit Type Conversion


• Explicit Type Conversion
➢ Implicit Type Conversion
Automatic conversion of a value from one data type to another by a programming language, without
the programmer specifically doing so, is called implicit type conversion.
It happens whenever a binary operator has two operands of different data types. Depending on the
operator, one of the operands is going to be converted to the data type of the other. It could be promoted or
demoted depending on the operator.

55 + 1.75
In this example, the integer value 55 is converted to a floating-point value of 55.0. It waspromoted.
Type Conversions
➢ Explicit Type Conversion
➢ Most languages have a method for the programmer to change or cast a value from one data type to
another; called explicit type conversion. Some languages support a cast operator.
➢ The cast operator is a unary operator; it only has one operand and the operand is to the right of the operator.
The operator is a set of parentheses surrounding the new data type. Other languages have functions that
perform explicit type conversion

➢ Floating-Point to Integer Type Conversion Example

C++ (int) 3.14


C# Convert.ToInt32(3.14)

Java Math.floor(3.14)

JavaScript Math.floor(3.14)

Python int(3.14)
Type Conversions
➢ A narrowing conversion converts a value to a type that cannot store even approximations of all of the values
of the original type. For example, converting a double to a float in Java is a narrowing conversion,
because the range of double is much larger than that of float.

➢ A widening conversion converts a value to a type that can include at least approximations of all of the values
of the original type. For example, converting an int to a float in Java is a widening conversion.

➢ Widening conversions are nearly always safe, meaning that the magnitude of the converted value is
maintained.

➢ Narrowing conversions are not always safe— sometimes the magnitude of the converted value is changed in
the process
Type Conversions
Relational Expressions
➢ A relational operator is an operator that compares the values of its twooperands.

➢ A relational expression has two operands and one relationaloperator.

➢ The value of a relational expression is Boolean, except when Boolean is not a type included
in the language.

➢ The relational operators are often overloaded for a variety of types.


➢ The operation that determines the truth or falsehood of a relational expression depends on the
operand types.
➢ It can be simple, as for integer operands, or complex, as for character string operands. Typically, the

types of the operands that can be used for relational operators are numeric types, strings, and ordinal
types.
Relational Expressions
Boolean Expressions
➢ Boolean expressions consist of Boolean variables, Boolean constants, relational
expressions, and Boolean operators.

➢ The operators usually include those for the AND, OR, and NOT operations, and
sometimes for exclusive OR and equivalence.

➢ Boolean operators usually take only Boolean operands (Boolean variables, Boolean
literals, or relational expressions) and produce Boolean values.
➢ In the mathematics of Boolean algebras, the OR and AND operators must have equal
precedence.
➢ In accordance with this, Ada’s AND and OR operators have equalprecedence.
➢ However, the C-based languages assign a higher precedence to AND thanOR.
Boolean Expressions
➢ A boolean expression is an expression that results in a boolean value, that is, in a value of either true or false.
➢ More complex boolean expressions can be built out of simpler expressions, using the following boolean
operators:

➢ The println statement will be executed if wet and cold are both true, or if poor and hungry are both true.
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.
For example, the value of the arithmetic expression
(13 * a) * (b / 13 - 1)

is independent of the value of (b / 13 - 1) if a is 0, because 0 * x = 0 for any x.So,


when a is 0, there is no need to evaluate (b / 13 - 1) or perform the second multiplication.
➢ However, in arithmetic expressions, this shortcut is not easily detected during execution, so it is
never taken.
Short-Circuit Evaluation
➢ Let's say itIsFriday is false. Because Java
short-circuits evaluation, it wouldn't bother
checking the value of itIsRaining—it knows
that either way the condition is false and we
won't print the invitation to board game night.

➢ What happens if "Becky" isn't in our friends


hash map? Since friends.get("Becky") is null,
when we try to call isFreeThisFriday() we'll
get a NullPointerException.
Assignment Statements
➢ Assignment operators are used to assigning value to a variable. The left side operand of the
assignment operator is a variable and right side operand of the assignment operator is a value.
➢ The value on the right side must be of the same data-type of the variable on the left side otherwise the
compiler will raise an error.

➢ “ = ” This is the simplest assignment operator.


This operator is used to assign the value on the right to the variable on theleft.

➢ “+=”: This operator is combination of ‘+’and ‘=’operators.


➢ This operator first adds the current value of the variable on left to the value on the right and thenassigns
the result to the variable on the left.
Assignment Statements
➢ “-=”This operator is combination of ‘-‘ and ‘=’operators.
➢ This operator first subtracts the current value of the variable on left from the value on the right andthen
assigns the result to the variable on the left.

➢ “*=”This operator is combination of ‘*’and ‘=’operators.


➢ This operator first multiplies the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left.
Assignment Statements

➢ “/=”This operator is combination of ‘/’and ‘=’operators.


➢ This operator first divides the current value of the variable on left by the value on the rightand

then assigns the result to the variable on the left.

➢ ALGOL 60 pioneered the use of := as the assignment operator, which avoids the confusionof
assignment with equality
Assignment Statements
➢ Compound Assignment Operators
➢ A compound assignment operator is a shorthand method of specifying a commonlyneeded
form of assignment.
➢ The form of assignment that can be abbreviated with this technique has the destination variable
also appearing as the first operand in the expression on the right side, as in

a = a + b

➢ The operators ++ for increment, and –– for decrement, can be used either in expressions or to
form stand-alone single-operator assignment statements.
Assignment Statements
➢ Compound Assignment Operators

➢ They can appear either as prefix


operators, meaning that they
precede the operands, or as postfix
operators, meaning that they follow
the operands.

➢ If the same operator is used as a


postfix operator, as in
Assignment Statements
➢ Compound Assignment Operators
Assignment Statements
➢ Assignment as an Expression
➢ For example, in C, it is common to write statements such as

➢ In this statement, the next character from the standard input file, usually the keyboard, is gottenwith
getchar and assigned to the variable ch.
➢ The result, or value assigned, is then compared with the constant EOF.
➢ If ch is not equal to EOF, the compound statement {...} is executed.
➢ Note that the assignment must be parenthesized—in the languages that support assignment as an expression,
the precedence of the assignment operator is lower than that of the relationaloperators.
➢ Without the parentheses, the new character would be compared with EOF first. Then, the result of that
comparison, either 0 or 1, would be assigned to ch.
Assignment Statements
➢ Multiple Assignments
➢ Several recent programming languages, including Perl, Ruby, and Lua, provide multiple-target,
multiple- source assignment statements.

For example, in Perl one can write

➢ The semantics is that 20 is assigned to $first, 40 is assigned to $second, and 60 is assigned to $third.

➢ If the values of two variables must be interchanged, this can be done with a single assignment, as
with
Assignment Statements
➢ Assignment in Functional Programming Languages

➢ All of the identifiers used in pure functional languages and some of them used in other functional languagesare
just names of values.

➢ As such, their values never change. For example, in ML, names are bound to values with the val declaration,
whose form is exemplified in the following:

➢ If cost appears on the left side of a subsequent val declaration, that declaration creates a new version ofthe
name cost, which has no relationship with the previous version, which is then hidden.
Mixed-Mode Assignment

The design question is: Does the type of the expression have to be the same as the type
of the variable being assigned, or can coercion be used in some cases of type mismatch?

➢ Assignment statements can also be mixed-mode,


for example
int a;
float b, c;

c = a / b;
➢ In Fortran, C, and C++, any numeric type value can be assigned to any
numeric type variable.

➢ In Java, only widening assignment coercions are done


➢ In Ada, there is no assignment coercion
Statement-Level Control Structures

➢ A control structure is a control statement and the statements whose execution itcontrols.

1. Selection Statements
2. Iterative Statements
3. Unconditional Branching

• Overall Design Question:


What control statements should a language have, beyond selection and
pretest logical loops?
Selection Statements
➢ A selection statement provides the means of choosing between two or more execution paths in a program.
Such statements are fundamental and essential parts of all programming languages.

➢ A selection statement selects among a set of statements depending on the value of a controlling expression.
The selection statements are the if statement and the switch statement, which are discussed in the following
sections.

➢ Selection statements fall into two general categories: two-way and n-


way, or multiple selection.
Two-Way Selection Statements
➢ Although the two-way selection statements of contemporary imperative languages are quite similar, there are
some variations in their designs.
➢ The general form of a two-way selector is as follows

➢Design Issues
Two-Way Selection Statements

➢ The Control Expression


➢ Control expressions are specified in parentheses if the then reserved word (or someother syntactic

marker) is not used to introduce the then clause.

➢ In those cases where the then reserved word (or alternative marker) is used, there is less need for
the parentheses, so they are often omitted, as in Ruby.

➢ In C89, which did not have a Boolean data type, arithmetic expressions were used as control
expressions.

➢ This can also be done in Python, C99, and C++.


Two-Way Selection Statements
➢ Clause Form
➢ In many contemporary languages, the then and else clauses appear as either singlestatements or
compound statements.

➢ Many languages use braces to form compound statements, which serve as the bodies of then and else
clauses.
➢ In Fortran 95, Ada, Python, and Ruby, the then and else clauses are statement sequences, rather than
compound statements.
➢ Python uses indentation to specify compound statements. For example,

➢ rather than then, a colon is used to introduce the then clause in Python.
Two-Way Selection Statements
➢ Nesting Selectors
➢ problem of syntactic ambiguity of a straightforward grammar for a two-way selector statement.
➢ That ambiguous grammar was as follows:.

➢ The issue was that when a selection statement is


nested in the then clause of a selection statement, it is
not clear to which if an else clause should be
associated.

➢ This problem is reflected in the semantics of selection


statements. Consider the following Java-like code:
Two-Way Selection Statements
➢ Nesting Selectors
➢ The crux of the problem in this example is that the else clause follows two
then clauses with no intervening else clause, and there is no syntactic
indicator to specify a matching of the else clause to one of the then clauses.

➢ If the alternative semantics were needed, it would be


Two-Way Selection Statements
➢ Nesting Selectors
➢ The first interpretation of the selector example at the beginning of this
section, in which the else clause is matched to the nested if, can be written
in Ruby as follows:

➢ Because the end reserved word closes the nested if, it is clear thatthe

else clause is matched to the inner then clause.

➢ The following statement, written in Python, is semantically equivalent to


the last Ruby statement above:
➢ If the line else: were indented to begin in the same column as the nested

if, the else clause would be matched with the inner if.
Two-Way Selection Statements

➢ Selector Expressions
➢ In the functional languages ML, F#, and LISP, the selector is not a statement; it is an expression that
results in a value.
➢ Therefore, it can appear anywhere any other expression can appear.
➢ Consider the following example selector written in F#:

➢ This creates the name y and sets it to either x or 2 * x, depending on whether x is greater than zero.
Multiple-Selection Statements
➢ The multiple-selection statement allows the selection of one of any number of statements or statement
groups.

➢ It is, therefore, a generalization of a selector.


➢ In fact, two-way selectors can be built with a multiple selector.
➢ The need to choose from among more than two control paths in a program is common.
➢ Although a multiple selector can be built from two-way selectors and gotos, the resulting structures are
cumbersome, unreliable, and difficult to write and read.
➢ Therefore, the need for a special structure is clear and that is multiple-selection statement.
Multiple-Selection Statements
➢ Examples of Multiple Selectors

➢ C provides the switch multiple-selection


statement to handle such decision making.
➢ The switch statement consists of a series of case
labels, an optional default case and statements to
execute for each case.

➢ break is used to exit the switch statement.


➢ default is used if the variable did not satisfy any
value of the listed cases.
➢ Here’s an example of a switch
statement in Java.
➢ Compiler generates a jump table for switch case
statement
➢ The switch variable/expression is evaluated once
➢ Switch statement looks up the evaluated
variable/expression in the jump table and directly
decides which code block to execute.
➢ If no match is found, then the code under default
case is executed
➢ Depending on the value of variable month, a
different message will be displayed in the standard
output.
➢ In this case, since the month=8, ‘August’ willbe
printed in standard output.
➢ Python Switch Case
Statement.

➢ One way out would be to implement


an if-elif-else ladder.
➢ Rather, we can use a dictionary to
map cases to their functionality.

➢ Here, we define a function week() to tell


us which day a certain day of the week is.
➢ A switcher is a dictionary that
performs this mapping.
Multiple-Selection Statements
➢ Multiple Selection Using if
➢ In particular, else-if sequences are replaced with a single special word, and the closing special word on the
nested if is dropped.
➢ The nested selector is then called an else-if clause.
➢ Consider the following Python selector statement (note that else-if is spelled elif in Python):
Iterative Statements
➢ An iterative statement is one that causes a statement or collection of statements to be executed zero,
one, or more times.
➢ An iterative statement is often called a loop. Every programming language has included some method
of repeating the execution of segments of code.

➢ Iteration is the very essence of the power of the computer.


➢ If some means of repetitive execution of a statement or collection of statements were not possible,
programmers would be required to state every action in sequence; useful programs would be huge and
inflexible and take unacceptably large amounts of time to write and mammoth amounts of memory to store.

➢ The primary categories are defined by how designers answered two basic design questions:
• How is the iteration controlled?
• Where should the control mechanism appear in the loop statement?
Iterative Statements

1. Counter-Controlled Loops
➢ A counting iterative control statement has a variable,
➢ The loop variable, in which the count value is maintained.
➢ It also includes some means of specifying the initial and terminal values of the loop
variable, and
➢ the difference between sequential loop variable values, often called the stepsize.

➢ The initial, terminal, and stepsize specifications of a loop are called the loop parameters.

➢ Design Issues
1. What are the type and scope of the loop variable?
2. What value does the loop variable have at the loop termination?
3. Should it be legal for the loop variable or loop parameters to be changed in the loop, and if
so, does the change affect loop control?
4. Should the loop parameters be evaluated only once, or once for every iteration?
Iterative Statements
➢ The for Statement of the C-Based Languages
➢ The general form of C’s for statement isrange, Integer.

➢ The loop body can be a single statement, a compound statement, or a null statement.
➢ The expressions in a for statement are often assignment statements.
➢ The first expression is for initialization and is evaluated only once, when the for statement execution begins.
➢ The second expression is the loop control and is evaluated before each execution of the loopbody.
➢ The last expression in the for is executed after each execution of the loop body. It is often used to incrementthe
loop counter.
Iterative Statements
➢ The for Statement of Python
➢ The general form of Python’s for is

➢ The loop variable is assigned the value in the object, which


is often a range, one for each execution of the loop body.
The else clause, when present, is executed if the loop
terminates normally.

➢ For most simple counting loops in Python, the range


function is used. range takes one, two, or three parameters.
Iterative Statements
➢ Counter-Controlled Loops in Functional Languages
➢ functional languages use a recursive function.
➢ The general form of an F# function for simulating counting loops, named for Loop in this case, is as follows

➢ In this function, the parameter loopBody is the function with the body of the loop and the parameter repsis
the number of repetitions.
➢ The reserved word rec appears before the name of the function to indicate that it is recursive.
Iterative Statements
➢ Logically Controlled Loops
➢ In many cases, collections of statements must be repeatedly executed, but the repetition control is
based on a Boolean expression rather than a counter. For these situations, a logically controlled
loop is convenient.
➢ Actually, logically controlled loops are more general than counter-controlled loops.
➢ Every counting loop can be built with a logical loop, but the reverse is not true.

➢ Also, recall that only selection and logical loops are essential to express the control structure of any
flowchart.
➢ Because they are much simpler than counter-controlled loops, logically controlled loops have fewer
Design Issues.
1. Should the control be pretest or posttest?
2. Should the logically controlled loop be a special form of a counting loop or a separate statement?
Iterative Statements
➢ Logically Controlled Loops
➢ The C-based programming languages include both pretest and posttest logically controlled loops that are not
special forms of their counter-controlled iterative statements.

➢ The pretest and posttest logical loops have the following forms:
Iterative Statements
➢ User-Located Loop Control
➢ C, C++, Python, Ruby, and C# have unconditional
unlabeled exits (break).
Mechanisms ➢ Java and Perl have unconditional labeled exits (break
➢ In some situations, it is convenient for a in Java, last in Perl).
➢ Following is an example of nested loops in Java, in
programmer to choose a location for loop control which there is a break out of the outer loop from the
other than the top or bottom of the loop body. nested loop:

➢ As a result, some languages provide this


capability.
➢ A syntactic mechanism for user-located loop
control can be relatively simple, so its design is
not difficult. Such loops have the structure of
infinite loops but include user-located loop
exits.
Iterative Statements
➢ User-Located Loop
Control Mechanisms
➢ C, C++, and Python include an
unlabeled control statement,
continue, that transfers control to
the control mechanism of the
smallest enclosing loop.
➢ This is not an exit but rather a way
to skip the rest of the loop
statements on the current iteration
without terminating the loop
structure.
Iterative Statements

➢ User-Located Loop Control Mechanisms


➢ Design Issues
1. Should the conditional mechanism be an integral part of
the exit?

2. Should only one loop body be exited, or can enclosing


loops also be exited?
Unconditional Branching

➢ Unconditional branching is when the programmer forces the execution of a program to jump to
another part of the program.

➢ Theoretically, this can be done using a good combination of loops and if statements.
➢ In fact, as a programmer, you should always try to avoid such unconditional branching and use this

technique only when it is very difficult to use a loop.

➢ We can use “goto” statements (unconditional branch statements) to jump to a label in a program.
➢ The goto statement is used for unconditional branching or transfer of the program execution to the
labeled statement.
Unconditional Branching

➢ UNCONDITIONAL CONTROLSTATEMENT:

• C supports an unconditional control statement that is goto.


• goto is used to transfer control from one point to other in a C program.
• goto is a branching statement.
• It requires a label.
• goto is a keyword.
Unconditional Branching
➢ Unconditional branching:
goto statement
➢ A goto statement in C programming
provides an unconditional jump from the
'goto' to a labeled statement in the same
function.
➢ NOTE − Use of goto statement is highly
discouraged in any programming language
because it makes difficult to trace the
control flow of a program, making the
program hard to understand and hard to
modify. Any program that uses a goto can
be rewritten to avoid them.
Unconditional Branching
➢ UNCONDITIONAL CONTROL STATEMENT: example
Subprograms

➢ Fundamentals of Subprograms

➢ A subprogram definition describes the interface to and the actions of the subprogram abstraction.

➢ A subprogram call is the explicit request that a specific subprogram be executed. A subprogram is said
to be active if, after having been called, it has begun execution but has not yet completed that execution.

➢ The two fundamental kinds of subprograms,


1. procedures : set of commands executed in order
2. functions : set of instructions used for some computation
Subprograms
➢ Fundamentals of Subprograms
➢ A subprogram header, which is the first part of the definition, serves several purposes.
➢ First, it specifies that the following syntactic unit is a subprogram definition of some particular kind(usually
specified with a special word- optional).
➢ Second, if the subprogram is not anonymous, the header provides a name for the subprogram.
➢ Third, it may optionally specify a list of parameters.
➢ Consider the following header examples:
def adder (parameters):
➢ This is the header of a Python subprogram named adder.
➢ Ruby subprogram headers also begin with def.
➢ The header of a JavaScript subprogram begins with function.
➢ In C, the header of a function named adder might be as follows:
void adder (parameters)
➢ The reserved word void in this header indicates that the subprogram does not return a value.
Subprograms

➢ General Subprogram Characteristics

1. Each subprogram has a single entry point.

2. The calling program unit is suspended during the execution of the called
subprogram, which implies that there is only one subprogram in execution at
any given time.

3. Control always returns to the caller when the subprogram execution terminates.
Subprograms
➢ Procedures and Functions
Design Issues of Subprogram

The following is a summary of these design issues for subprograms in


general.
• Are local variables statically or dynamically allocated?
• Can subprogram definitions appear in other subprogram definitions?
• What parameter-passing method or methods are used?
• Are the types of the actual parameters checked against the types of the formal
parameters?
• If subprograms can be passed as parameters and subprograms can be nested, what is the
referencing environment of a passed subprogram?
• Are functional side effects allowed?
• What types of values can be returned from functions?
• How many values can be returned from functions?
• Can subprograms be overloaded?
• Can subprograms be generic?
• If the language allows nested subprograms, are closures supported?
Subprograms : Local Referencing Environments
Local Variable
➢ Subprograms can define their own variables, thereby defining local referencing
environments.

➢ Variables that are defined inside subprograms are called local variables, because
their scope is usually the body of the subprogram in which they are defined.

➢ Local variables can be either static or stack dynamic.

➢ If local variables are stack dynamic, they are bound to storage when the subprogram
begins execution and are unbound from storage when that execution terminates.
Subprograms : Local Referencing Environments
➢ There are several advantages of stack- dynamic local variables:-

➢ The primary one being flexibility. It is essential that recursive subprograms have
stack- dynamic local variables.
➢ Another is that the storage for local variables in an active subprogram can be
shared with the local variables in all inactive subprograms

➢ The main disadvantages of stack- dynamic local variables are the following:
➢ First, there is the cost of the time required to allocate, initialize (when necessary),
and deallocate such variables for each call to the subprogram.
➢ Second, accesses to stack- dynamic local variables must be indirect, whereas
accesses to static variables can be direct.
Subprograms : Local Referencing Environments
➢ The primary advantage of static local variables over stack- dynamic local variables
are:-
➢ They are slightly more efficient— they require no run- time overhead for allocation
and deallocation. Also, if accessed directly, these accesses are obviously more
efficient.

➢ The greatest disadvantage of static local variables are:-


➢ inability to support recursion.
➢ Also, their storage cannot be shared with the local variables of other inactive
subprograms.
Subprograms : Local Referencing Environments

➢ In most contemporary languages, local variables in a subprogram are by default stackdynamic.

➢ In C and C++ functions, locals are stack dynamic unless specifically declared to be static.

➢ For example, in the following C (or C++) function, the variable sum is static and count is stack
dynamic.
Subprograms : Local Referencing Environments
➢ The methods of C++, Java, and C# have only stack- dynamic local variables.

➢ In Python, the only declarations used in method definitions are for globals. Any variable declared to
be global in a method must be a variable defined outside the method. A variable defined outside the
method can be referenced in the method without declaring it to be global, but such a variable cannot be
assigned in the method. If the name of a global variable is assigned in a method, it is implicitly declared
to be a local and the assignment does not disturb the global. All local variables in Python methods are
stack dynamic.

➢ Only variables with restricted scope are declared in Lua. Any block, including the body of a function,
can declare local variables with the local declaration, as in the following:
local sum
All nondeclared variables in Lua are global. Access to local variables in Lua is faster than access to
global variables according to Ierusalimschy(2006).
Subprograms : Local Referencing Environments
a=1

def f():
print('Inside f() : ', a)

def g():
a=2
print('Inside g() : ', a)

def h():
global a
a=3
print('Inside h() : ', a)

print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Subprograms : Local Referencing Environments
a=1

# Uses global because there is no local 'a'


def f():
print('Inside f() : ', a) Output::
# Variable 'a' is redefined as a local
def g():
a=2
print('Inside g() : ', a)

# Uses global keyword to modify global 'a'


def h():
global a
a=3
print('Inside h() : ', a)

# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Subprograms : Parameter-Passing Methods

➢ Parameter-passing methods are the ways in which parameters are


transmitted to and/or from called subprograms.

➢ Semantics Models of Parameter Passing


➢ Formal parameters are characterized by one of three distinct semantics models:
1) They can receive data from the corresponding actual parameter;
2) they can transmit data to the actual parameter; or
3) they can do both.

➢ These models are called in mode, out mode, and inout mode, respectively.
Subprograms
Implementation Models of Parameter Passing
➢ A variety of models have been developed by language designers to guidethe implementation of the three
basic parameter transmission modes. In the following sections, we discuss several of these, along with their
relative strengths and weaknesses
Subprograms
Implementation Models of
Parameter Passing

1. Pass By Value
➢ This method uses in-mode semantics.
➢ Changes made to formal parameter do not
get transmitted back to the caller.

➢ Any modifications to the formal parameter


variable inside the called function or method
affect only the separate storage location and
will not be reflected in the actual parameter
in the calling environment.

➢ This method is also called as call by value.


Subprograms
2. Pass- by- Result
➢ Pass- by- result is an implementation model for out- mode parameters.
➢ When a parameter is passed by result, no value is transmitted to the subprogram.
➢ Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to
the actual parameter.
• If, at the end of the execution of Fixer, the formal
parameter x is assigned to its corresponding actual
parameter first.
• then the value of the actual parameter a in the caller
will be 35.

• If y is assigned first, then the value of the actual


parameter a in the caller will be 17.
Subprograms
3. Pass- by- Value- Result
➢ This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result.
➢ Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back

to the actual parameter. This method is also called as pass by copy


Subprograms
4. Pass- by- Reference
➢ This technique uses in/out-mode semantics.
➢ Changes made to formal parameter do get
transmitted back to the caller through parameter
passing.
➢ Any changes to the formal parameter are reflected
in the actual parameter in the calling environment
as formal parameter receives a reference (or
pointer) to the actual data.
➢ This method is also called as call by reference.
This method is efficient in both time and space.
Subprograms
5. Pass- by- Name
➢ Pass-by-name is an inout-mode parameter transmission method
that does not correspond to a single implementation model.
➢ This technique is used in programming language such as Algol.
➢ Here, symbolic “name” of a variable is passed, which allows it
both to be accessed and update.
➢ When parameters are passed by name, the actual parameter is, in
effect, textually substituted for the corresponding formal
parameter in all its occurrences in the subprogram.
➢ This method is quite different from those discussed thus far; in this
case, formal parameters are bound to actual values or addresses at
the time of the subprogram call.
Subprograms
Implementing Parameter Passing Methods

➢ In most contemporary languages,


parameter communication takes place
through the run- time stack.

➢ The run- time stack is initialized and


maintained by the run- time system,
which manages the execution of
programs.

➢ The runtime stack is used extensively for


subprogram control linkage and
parameter passing.
Subprograms
Implementing Parameter Passing Methods

➢ Pass-by-value parameters have their


values copied into stack locations. The
stack locations then serve as storage for
the corresponding formal parameters.

➢ Pass-by-result parameters are


implemented as the opposite of pass- by-
value. The values assigned to the pass-
by- result actual parameters are placed in
the stack, where they can be retrieved by
the calling program unit upon termination
of the called subprogram.
Subprograms
Implementing Parameter Passing Methods
➢ Pass-by-value-result parameters can be
implemented directly from their semantics as
a combination of pass-by-value and pass-by-
result. The stack location for such a
parameter is initialized by the call and is then
used like a local variable in the called
subprogram.

➢ Pass-by-reference parameters are perhaps


the simplest to implement. Regardless of the
type of the actual parameter, only its address
must be placed in the stack. In the case of
literals, the address of the literal is put in the
stack.
Abstract Data Types
➢ Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of value and
a set of operations.
➢ The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented.
➢ It does not specify how data will be organized in memory and what algorithms will be used for
implementing the operations.
➢ It is called “abstract” because it gives an implementation-independent view.
➢ The process of providing only the essentials and hiding the details is known as abstraction.
➢ The user of data type does not need to know how that data type is implemented, for example, we have been
using Primitive values like int, float, char data types only with the knowledge that these data type can
operate and be performed on without any idea of how they are implemented.

➢ So a user only needs to know what a data type can do, but not how it will be implemented.
Design Issues of Abstract Data Types

Many contemporary languages, including C++, Objective-C, Java, and C#, directly support
abstract data types.

• The first design issue is whether abstract data types can be


parameterized.

• The second design issue is what access controls are provided and how
such controls are specified.

• Finally, the language designer must decide whether the specification of


the type is physically separate from its implementation (or whether
that is a developer choice).
Abstract Data Types

➢ Parameterized Abstract Data Types


➢ It is often convenient to be able to parameterize abstract data types. For example, we should be able to
design a stack abstract data type that can store any scalar type elements rather than be required to write a
separate stack abstraction for every different scalar type.
Encapsulation Constructs
➢ Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit.
➢ In encapsulation, the variables of a class will be hidden from other classes, and can be accessed
only through the methods of their current class. Therefore, it is also known as data hiding.
Advantages of Encapsulation
➢ Encapsulation hides the implementation of a program and hence easy to read and
modify in the future according to business requirements.
➢ It allows us to deploy the updated code version wherever required, without requiring the whole
program tobe restructured.
➢ It secures the program by providing data hiding functionality.
➢ Encapsulation promotes a modular way of programming making code resilient.
➢ Encapsulation in C++
➢ Encapsulation also lead to data abstraction
or hiding. As using encapsulation also hides
the data. In the above example the data of
any of the section like sales, finance or
accounts is hidden from any other section.
➢ In the above program the variable x is made
private. This variable can be accessed and
manipulated only using the functions get() and
set() which are present inside the class. Thus we
can say that here, the variable x and the
functions get() and set() are binded together
which is nothing but encapsulation.
➢ Encapsulation in C#

➢ Encapsulation is implemented by using access specifiers. An access specifier defines the scope and
visibility of a class member. C# supports the following access specifiers −

1. Public
2. Private
3. Protected
4. Internal
5. Protected internal
➢ Encapsulation in C#
➢ Public Access Specifier
Public access specifier allows a class to expose its member variables and member functions to other functions and objects.
Any public member can be accessed from outside the class.

➢ Private Access Specifier


Private access specifier allows a class to hide its member variables and member functions from other functions and objects.
Only functions of the same class can access its private members. Even an instance of a class cannot access its private
members.

➢ Protected Access Specifier


Protected access specifier allows a child class to access the member variables and member functions of its base class. This
way it helps in implementing inheritance.

➢ Internal Access Specifier


Internal access specifier allows a class to expose its member variables and member functions to other functions and objects
in the current assembly. In other words, any member with internal access specifier can be accessed from any class or
method defined within the application in which the member is defined.
➢ 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 fornames
➢ C++ Namespaces
• Can place each library in its own namespace and qualify names used outside with the namespace
• C# also includes namespaces
➢ 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
➢ Ada Packages
• Packages are defined in hierarchies which correspond to file hierarchies
• Visibility from a program unit is gained with the with clause

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy