PPL_Unit_2_ppt
PPL_Unit_2_ppt
• 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.
• There are 8 primitive data types in Java: byte, char, short, int, long, float, double and Boolean
• In python there are 4 primitive data types integer, floating, Boolean, string.
Primitive data Types (Cont’d)
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.
• 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.
• 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
• Advantage: accuracy
• E.g. Support Business system applications – Cobol. C# has a decimal data type
Boolean Types
• 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
• 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.
• Library functions that produce strings often supply the null character.
• Assignment
• 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
• 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.
• 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.
• 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, . . . . .
• 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?
• 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.
• 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.
• 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:
• 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.
• 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).
• 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
• 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.
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: 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
• The C-based languages do not provide any array operations, except through the
methods of Java, C++, and C#.
• 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
• 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
➢ 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.
➢ 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.
➢ 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.
➢ 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.
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?
• Records are frequently valuable data types in programming languages. The design of
record types is straightforward, and their use is safe.
• 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.
Design Issues
➢ The problem of type checking union types, is the major design issue.
➢ 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.
➢ The unions in these languages are called free unions, because programmers are allowed complete freedom from type
checking in their use.
• Type checking of unions requires that each union construct include a type
indicator.
➢ 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
• 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.
• 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?
• 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
• 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,
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
➢ 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.
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
➢ 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
➢ 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
➢ In other cases, a constant may be part of the machine language instruction and not
➢ 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.
of operands.
➢ For an integer type, the + operator gives the sum of
two numbers, and for the string type it concatenates
(joins) them.
➢ 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.
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
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.
➢ The value of a relational expression is Boolean, except when Boolean is not a type included
in the language.
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
➢ 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
➢ 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.
➢ 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?
c = a / b;
➢ In Fortran, C, and C++, any numeric type value can be assigned to any
numeric type variable.
➢ A control structure is a control statement and the statements whose execution itcontrols.
1. Selection Statements
2. Iterative Statements
3. Unconditional Branching
➢ 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.
➢Design Issues
Two-Way Selection Statements
➢ 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.
➢ 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:.
➢ Because the end reserved word closes the nested if, it is clear thatthe
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.
➢ 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
➢ 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:
➢ 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
➢ 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:
➢ 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.
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
➢ 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.
➢ 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.
➢ 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
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Subprograms : Parameter-Passing Methods
➢ 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.
➢ 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 second design issue is what access controls are provided and how
such controls are specified.
➢ 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.