New_Unit 2
New_Unit 2
College of Engineering
SE Computer
Course Name :Principles of Programming Language
Course Code: 210255
Course InCharge: Kainjan M. Sanghavi
Unit 2
Structuring the Data, Computations and Program
● Elementary Data Types : Primitive data Types, Character String types, User Defined Ordinal Types,
Array types, Associative Arrays, Record Types, Union Types, Pointer and reference Type.
● Expression and Assignment Statements: Arithmetic expression, Overloaded Operators, Type
conversions, Relational and Boolean Expressions, Short Circuit Evaluation, Assignment Statements,
Mixed mode Assignment.
● Statement level Control Statements: Selection Statements, Iterative Statements, Unconditional
Branching.
● Subprograms: Fundamentals of Sub Programs, Design Issues for Subprograms, Local referencing
Environments, Parameter passing methods. Abstract Data Types and Encapsulation Construct: Design
issues for Abstraction, Parameterized Abstract Data types, Encapsulation Constructs, Naming
Encapsulations
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s
SNJB’s Late
Late Sau.
Sau. K.
K. B.
B. J.
J. College
College of
of Engineering
Engineering
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
● Primitive data types are those that are not defined in terms of other data types
● These are not built from other types
● These are atomic and cannot be decomposed further
● Some of the data types are merely reflections of the hardware - for eq. Integer
types
Boolean Types
Advantage:
Readability
Character Types
primitive type?
● Limited dynamic length - may need a run-time descriptor for storing length (but not
in C and C++ because the end of a string is marked with the null character)
● Dynamic length - need complex storage management. Length of string is not fixed ,
● First approach :
○ Using linked list
○ Disadvantage - Extra storage for links and complexity of operations
● Second approach :
○ Store as array of pointers to individual characters allocated in a heap.
○ Disadvantage- Still uses extra memory
● Third approach:
○ To store complete strings in adjacent storage cells
○ When a string grows and adjacent storage is not available, a new area of memory
is found that can store the complete new string and the old part is moved to this
area, and the memory cells for the old string are deallocated.
○ This results in faster string operations and requires less storage
○ Disadvantage : = Allocation / deallocation process is slower.
Enumeration Types
● All possible values, which are named constants, are provided in the definition
● C# example
enum days {mon, tue, wed, thu, fri, sat, sun};
● The enumeration constants are typically implicitly assigned the integer values, 0, 1, …, but
can be explicitly assigned any integer literal in the type’s definition
Design issues
● Is an enumeration constant allowed to appear in more than one type definition, and if so,
how is the type of an occurrence of that constant checked?
● Are enumeration values coerced to integer?
● Any other type coerced to an enumeration type?
Enumeration Types
● In languages that do not have enumeration types, programmers usually simulate them with
integer values.
● E.g. Fortran 77, use 0 to represent blue and 1 to represent red:
● Problem:
○ There is no type checking when they are used.
○ It would be legal to add two together. Or they can be assigned any integer value thus
destroying the relationship with the colors.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Enumeration Types-Design
● In C++, we could have
● In Java, all enumeration types are implicitly subclasses of the predefined class Enum. They
can have instance data fields, constructors and methods.
Enumeration Types-Design
Java Example
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Monday");
…
dayNames.add("Friday");
days = dayNames.elements();
while (days.hasMoreElements())
System.out.println(days.nextElement());
Enumeration Types-Design
● C# enumeration types are like those of C++ except that they are never coerced to integer.
● Operations are restricted to those that make sense.
● The range of values is restricted to that of the particular enumeration type.
Subrange Type
An ordered contiguous subsequence of an Ada’s design
ordinal type type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
● Not a new type, but a restricted subtype Weekdays is Days range Mon..Fri;
existing type subtype Index is Integer range 1..100;
Day1: Days;
Example: 12..18 is a subrange of
Day2: Weekday;
integer type
Day2 := Day1; //legal if Day1 is not set to Sat or
Introduced by Pascal and included in Sun
Ada
Array Type
An array is an aggregate of homogeneous data elements in which an individual
element is identified by its position in the aggregate, relative to the first
element.
Categories of Arrays
Categories of Arrays
● Static: subscript ranges are statically bound and storage allocation is static
(before run‐ time)
● Advantage: efficiency (no dynamic allocation/deallocation required)
● Example: In C and C++ arrays that include the static modifier are static
○ static int myarray[3] = {2, 3, 4};
● int static_array[7];
void foo(int n) {
int * heap_dynamic_array = malloc(n * sizeof(int));
}
void foo()
fixed stack‐dynamic
{ int fixed_stack_dynamic_array[7]; }
void foo(int n)
Stack‐dynamic
{ int stack_dynamic_array[n];}
void foo(int n)
heap_dynamic_array
{ int * heap_dynamic_array = malloc(n * sizeof(int)); }
int a[5];
Array Initialization
Some language allow initialization at the time of storage allocation
● Fortran
List (3) Data List /0, 5, 5/ // List is initialized to the values
● C, C++, Java, C# example
int list [] = {4, 5, 7, 83}
● Character strings in C and C++
char name [] = “freddie”; // eight elements, including last element as null
character
● Arrays of strings in C and C++
char *names [] = {“Bob”, “Jake”, “Joe”];
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Array Initialization
● Some language allow initialization at the time of storage allocation
Array Operations
Language Array Operation
Slice
Slice
● Fortran Declaration:
○ Vector(3:6) Four element from third to sixth
● Python Declaration
○ A =[10,20,30,40,50,60]
■ A[1:4] [10,20,30]
■ A[:5] [10,20,30,40,50]
■ A[4:] [50,60]
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Compile-Time Descriptors
Associative Array
Associative Array
Associative Array
Design Issues
$lookup{"dave"} = 7634;
Associative Array
Associative Array
Associative Array
Associative Array
● The size of a Perl hash is dynamic.
● That is, it grows when a new element is added, and shrink when an
element is delete, and also when it is emptied by assignment of the
empty literal.
● The exists operator returns true or false, depending on whether its
operand key is an element in hash.
● For example,
Associative Array
● The size of a Perl hash is dynamic.
● That is, it grows when a new element is added, and shrink when an
element is delete, and also when it is emptied by assignment of the
empty literal.
● The exists operator returns true or false, depending on whether its
operand key is an element in hash.
● For example,
Record Type
Record Type
01 EMP-REC.
02 EMP-NAME.
References to Records
● Record field references
FIRST, FIRST OF EMP-NAME, and FIRST of EMP-REC are elliptical references to the
employee’s first name
References to Records
struct { fully qualified reference: lists all
struct { person.name.first
} name;
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Operations on Records
Operations on Records
Union
● A union is a type whose variables are allowed to store
different type values at different times during
execution
● Design issues
○ Should type checking be required?
○ Should unions be embedded in records?
Pointer Operations
The
assignment
operation
j = *ptr
Dangling Pointer
Dangling pointers (dangerous)
A pointer pointing to data that does not exist anymore is called a
dangling pointer.
d is a dangling pointer.
float stuff[100];
float *p;
p = stuff;
Reference Type
● C++ includes a special kind of pointer type called a reference type
that is used primarily for formal parameters
○ Advantages of both pass-by-reference and pass-by-value
● Java extends C++’s reference variables and allows them to
replace pointers entirely
○ References are references to objects, rather than being
addresses
● C# includes both the references of Java and the pointers of C++
int result = 0;
int &ref_result = result; result and
. . . ref_result are
ref_result = 100;
Cout<<result; //100 aliases.
Pointer Vs Reference
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Introduction
■ Unary Minus ( -A ):
⚪ Examples: -num, -num/5, num1 * -num2
Department of Computer Engineering
107
SNJB’s Late Sau. K. B. J. College of Engineering
Unary Arithmetic Operators in C/C++ and Java (cont.)
■ The pre-increment is specified as follows: (++a)
⚪ It says to add 1 to the current value of the variable and then to use the new value (if
necessary).
■ The post-increment is specified as follows: (a++)
⚪ It says to use the current value of the variable (if necessary) and then add 1 to it.
■ The pre-decrement is specified as follows: (--a)
⚪ It says to subtract 1 from the current value of the variable and then to use the
new value (if necessary).
■ The post-decrement is specified as follows: (a--)
⚪ It says to use the current value of the variable (if necessary) and then subtract 1 from it.
if (count == 0) average = 0;
else average = sum/count;
■ APL is different; all operators have equal precedence and all operators
associate right to left.
+, –, &, mod
– (unary)
*i += 5;
void main() {
int x = 3;
x = x + fun(&x);
// 20 is printed // 8 is printed
Department of Computer Engineering
118
SNJB’s Late Sau. K. B. J. College of Engineering
Overloaded Operators
■ Operator Overloading is accomplished by defining functions that
have the same name as the operator being overloaded.
■ Some are common (e.g., +, -, *, … for int and float).
■ avg= sum/count
int a, b;
float x;
x = (float)a/(float)b;
Department of Computer Engineering
125
SNJB’s Late Sau. K. B. J. College of Engineering
Type Conversions:Errors in Expressions
■ Causes:
⚪ Errors resulting from narrowing conversions.
⚪ Errors resulting from limitations of computer arithmetic:
■ The result of an operation cannot be represented in the memory cell where it
must be stored.
■ Overflow Or Underflow: depending on result is too large or too small
⚪ Some languages (Ada, C++, Java) provide an exception handling mechanism that allows the
programmer to handle conditions such as divide by 0.
⚪ Often ignored by the run-time system.
⚪ Sometimes known as exceptions.
■ Types:
1. In Arithmetic Expressions:
2. In logical Expressions:
■ Ex.: The value of (a >= 0) and (b < 10) is independent of the second relational
expression if a < 0.
■ Assignment as an expression:
⚪ In C, C++, and Java the assignment statement produces a result and can
be used as operands.
while ((ch = getchar()) != EOF) { … }
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
• Python
if sum == 0 :
if count == 0 :
result = 0
else :
result = 1
Department
Copyright © 2009 Addison-Wesley. All rights reserved. of Computer Engineering 1-150
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples C, C++, Java
switch (index) {
case 1:
Without the break-
case 3: odd+=1; statement control
sumodd+=index; continues to the next
break;
case 2:
alternative.
case 4: even+=1;
sumeven+=index;
break;
default:cout << “Error in switch,
index = “ << index; break;
}
Department of Computer Engineering 1-151
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples c#
switch (value) {
case -1: Every selectable segment must
Negatives++; end with an explicit
break; unconditional branch
case 0: statement: either a break, which
Zeros++; transfers control out of the
goto case 1; switch construct, or a goto,
case 1: which can transfer control to
Positives++; one of the selectable
break; segments (or virtually anywhere
default: else).
Console.WriteLine(“Error in switch \n”);
Break; }
Department of Computer Engineering 1-152
SNJB’s Late Sau. K. B. J. College of Engineering
Multiple-Way Selection: Examples
• Ada design choices:
1. Expression can be any ordinal type
2. Segments can be single or compound
3. Only one segment can be executed per execution of the construct
4. Unrepresented values are not allowed
• Constant List Forms:
1. A list of constants
2. Can include:
- Subranges
- Boolean OR operators (|)
[else expression]
end
• Design choices:
○ Type of the loop variable is that of the discrete range (A discrete
range is a sub-range of an integer or enumeration type).
○ Loop variable does not exist outside the loop
○ The loop variable cannot be changed in the loop, but the
discrete range can; it does not affect loop control
○ The discrete range is evaluated just once
• Cannot branch into the loop body
• Design choices:
■ There is no explicit loop variable
■ Everything can be changed in the loop
■ The first expression is evaluated once, but the other two are
evaluated with each iteration
● The object is often a range, which is either a list of values in brackets ([2, 4,
6]), or a call to the range function (range(5)), which returns 0, 1, 2, 3, 4
● The loop variable takes on the values specified in the given range, one
for each iteration
● The else clause, which is optional, is executed if the loop terminates
normally
while (ctrl_expr)
loop body
do
loop body
while (ctrl_expr)
OuterLoop:
for (row = 0; row < numRows; row++)
for (col = 0; col < numCols; col++) {
sum += mat[row][col];
if (sum > 1000.0)
break outerLoop;
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
• Introduction
• Fundamentals of Subprograms
• Design Issues for Subprograms
• Local Referencing Environments
• Parameter-Passing Methods
– Data abstraction
• Emphasized in the1980s
• Keyword
– The name of the formal parameter to which an actual
parameter is to be bound is specified with the actual
parameter
– Parameters can appear in any order
• Keyword
– The name of the formal parameter to which an actual
parameter is to be bound is specified with the actual
parameter
– Parameters can appear in any order
where variables are confined to specific blocks. This prevents unintended access or
2. Reduced Scope Conflicts: By limiting the visibility of local data to their specific blocks, the risk
of naming conflicts with other variables in different parts of the program is reduced.
3. Memory Efficiency: Local data is stored on the stack, which is typically more memory-efficient
than global data stored in the heap. Local variables are automatically deallocated when they
void test(int A)
{ A++; } //2
A B
void main() // --- 5
{ int B=5; //1 1
(entry -? 5
test(B); ) 5
// ?+1
cout << B;//3
2// ---
} ?+1
3 -
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Result (Out Mode)
• When a parameter is passed by result, no value is transmitted to the
subprogram;
• the corresponding formal parameter acts as a local variable;
• its value is transmitted to caller’s actual parameter when control is
returned to the caller
– Require extra storage location and copy operation
• Potential problem: sub(p1, p1); whichever formal parameter is
copied back will represent the current value of p1
void test(int A)
A B
{A++;} //2 // --- 5
void main() 1
(entry -*B 5
{ int B=5; //1 )
test(*B); // *B 6
cout << B;//3 2// --- 6
} 3 -
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Reference (Inout Mode)
• Pass an access path
• Also called pass-by-sharing
• Passing process is efficient (no copying and no duplicated
storage)
• Disadvantages
– Slower accesses (compared to pass-by-value) to formal parameters
– Potentials for unwanted side effects
– Unwanted aliases (access broadened)
Department of Computer Engineering 1-227
Pass By Name
• Conceptual model is to substitute
name of the actual parameter for the
formal parameter
SNJB’s Late Sau. K. B. J. College of Engineering
Pass-by-Name (Inout Mode)
• By textual substitution
• Formals are bound to an access method at the time of the
call, but actual binding to a value or address takes place at
the time of a reference or assignment
• Allows flexibility in late binding
• C++
– A special pointer type called reference type for pass-by-reference
• Java
– All parameters are passed by value
– Object parameters are passed by reference
Ada
– Three semantics modes of parameter transmission:
in, out, in out; in is the default mode
– Formal parameters declared
■ out can be assigned but not referenced;
■ those declared in can be referenced but not assigned;
■ in out parameters can be referenced and assigned
● C++ allows call by reference and the code of that function will be copied at the
place where it is being called.
● It is not advisable to use call by reference more frequently. You can use call by
reference for small functions like one or two lines of function or the function like
swap, you can use call by reference.
● But don’t use it for heavy functions which are having loops and are having
complex logic.
● Parameterized ADTs allow designing an ADT that can store any type elements
(among other things) – only an issue for static typed languages
● Also known as generic classes
● C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs
class Stack {
Classes can be somewhat …
Stack (int size)
generic by writing
{
parameterized constructor stk_ptr = new int [size];
functions max_len = size - 1;
top = -1;
};
…
}
Stack stk(100);
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Parameterized Abstract Data Types -C++
template class<T>
class Stack {
int size; //Number of available elements to implement the stack
int tos; //Index of the element on top of the stack
T* S; //An array of integers used to implement the stack
Public:
Stack(int sz=100):size(sz),tos(-1){S=new T[size];}
~Stack () {if (S) delete [] S;}
bool empty(void){return tos<0;}
bool full(void){return tos>=size-1;}
● Ada specification packages can include any number of data and subprogram
declarations
● Ada packages can be compiled separately
● A package’s specification and body parts can be compiled separately
● Large programs define many global names need a way to divide into logical
groupings
● A naming encapsulation is used to create a new scope for names
● Can place each library in its own namespace and qualify names used outside with
the namespace
● C# also includes namespaces
● 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
● The concept of ADTs and their use in program design was a milestone in the development of
languages
● Two primary features of ADTs are the packaging of data with their associated operations and
information hiding
● Ada provides packages that simulate ADTs
● C++ data abstraction is provided by classes
● Java’s data abstraction is similar to C++
● Ada, C++, Java 5.0, and C# 2005 support parameterized ADTs
● C++, C#, Java, Ada, and Ruby provide naming encapsulations