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

Unit-2

Uploaded by

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

Unit-2

Uploaded by

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

UNIT - 11

Structuring the Data,


Computations and Program

Syllabus
Elementary Data Types : Primitive data Types, Character String types, U Defined Ordinal Type
Array types, Associative Arrays, Record Type: 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, lrerative
Statements, Unconditional Branching. Subprograms : Fundamentals of Sub Programs, Design
Issuesfor 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

Contents
21 Elementary Data Types. May-19, Marks 6
2.2 Expression and Assignment Statements
2.3 Statement-level Control Statements
2.4 Subprograms
2.5 Abstract Data Types and Encapsulation Construct.....Dec.-17, Marks 7
2.6 Multiple Choice Questions

@7
Principles of Programming Languages 2-2 Structuring the Data, Computations and Program

Xl Elementary Data Types 9, Marks

Primitive Data Types


o The primitive data types are elementary data types which are not built from some
other types.
o The values of primitive data types are atomic and cannot be decomposed into
simpler constituents.
o Many times the built in data types can be interchangeably used with built in data
type but there are exceptions. For example - enum in C is a primitive data type
which is used to define new constants.
Any programming language has a predefined set of built in data types. This built in
data type reflects the behavior of underlying hardware.
« Due to built in data type, the values are interpreted differently using hardware
instructions.
« Following are the types of built in types of programming languages.
Primilive data types

[Numerictspes| [[Booleantype | [Cheracter type]


Integer
Floaling- point
Complex

Decimal
Fig. 2.1.1 Data types
1) Numeric Types :
o Integer:
o This is the most commonly used data type.
o The integer data types can be signed or unsigned data types.
o InJava there are singed integer data types such as byte, short, int and long,
o In C++ unsigned integer data types are simply the integer values without signs.
The unsigned integer data types are typically used for binary data.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-3 Strusturing the Data, Computations and Program
« Floating Point:
© The floating point data type s used for representing the real numbers.
© On most of the computers the floating point numbers are stored in binary
number format
o Floating point values are represented as fractions and exponents.
o In most of the languages, there are two types of floating point values - float and
double.
o Complex:
© Complex values are represented as pair of real and imaginary part
© The imaginary part of complex number is represented as literal such as i or .
o For example 5+ 7i is a complex number
o Python is a programming language that supports the complex data ty pe
* Decimal
© The decimal data type is used to support business systems applications.
o This is a type of data type that store fixed number of decimal digits with decimal
point at a fixed position in the value.
© The languages like COBOL and C# makes use of decimal data type.
o The decimal data type values can be stored using a special representation called
Binary Coded Decimal (BCD)

2) Boolean Types :
« This data type define only two values TRUE and FALSE.
« InBoolean algebra the Boolean data type is used.
¢ The basic operations performed are and, not, or.

3) Character Type :
o The single character value is represented using char data type.
o InC the character fype variable is
char choice;

Type Structure of C++


o The type structure of C++ is divided into two main categories - Fundamental types
and derived types.
o The fundamental type is - integer and float. The integer data type is classified into
int, char, short, long. The float data type is clas ified into float and double.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-4__ Structuring the Data, Computations and Program
o The derived type of actually derived from the fundamental types - For example,
arrays, class, structure, union, functions and pointers.
C++ type structure|

Fandarona yoed

[mteger] [Froat ] [Amays] [[ctoss | [[siuet | [[union | [Pointer]

O] o] (o] [ ] [Rom] [5oume]


Fig. 2.1.2 Type structure of C++
o Arrays is collection of similar data type elements. For example
int a[10]; //1t will create an array of 10 integer elements

« The class, structure and union allows the programmer to create user defined data
types. The class is well known entity in C++ by which one can encapsulate data
members and member functions in C++. For example
dlass stack
{
private:
ine s{10];
int top;
public:
void push(int item)
int pop();

The above class creates a stack data structure using class


The pointer is different type of data type which stores the address of the variable. Just
similar to pointer there i a concept of reference which holds the address of a variable.
Reference variable is initialized by another variable.

Type Structure of Java


The type structure of Java is classified in two categories
1. Built in Data Types
2. Derived Types.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-5 _ Structuring the Data, Computations and Program
Java data ype structure

(oo ]
] [ [ [
[Cintegeai ] [Fioating point | [ Ciass | [Anays | [interface]

Byle Char Shot it Long Fleal Double


Fig. 2.1.3 Types structure of Java
The built in data types :
Various data types used in Java are byte, short, int, long, char, float, double and
boolean.

byte
This is in fact smallest integer type of data type. Its width is of 8-bits with the range
~128t0 127. The variable can be declared as byte type as
byte Lj;

short

‘This data type is also used for defining the signed numerical variables with a width of
16 - bits and having a range from -32,768 to 32,767. The variable can be declared as short
as
short a,b;

int
This i the most commonly used data type for defining the numerical data. The width
of this data type is 32-bit having a range 2,147,483,648 to 2,147,483,647. The dedlaration
can be
int p,a;

long
Sometimes when inf is not sufficient for declaring some data then long is used. The
range of long is really very long and it is -9,223,372,036,854,775808 to
9,223,372,036,854,775,807. The dedlaration can be
long xy;

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-6 Structuring the Data, Computations and Program
float
To represent the real number(i.e. number that may have decimal point) float data type
can be used. The width is 32-bit and range of this data type is 340282347 x 10%,
1.40239846 x 10~
double
To represent the real numbers of large range the double data type is used. Its width is
64-bit having the range 1.8 x 10°%, 4.9 x 10~ 2¢

char
This data type is used to represent the character type of data. The width of this data
type is 16-bit and its range is 0 to 65,536.
boolean
Boolean is a simple data type which denotes a value to be either true or false

Character String Types


A character string type is one in which values are sequences of characters

m Design Issues
The two most important design issues for character string types are -

1) Is it a primitive type or just a special kind of character array ?


o Cand C++ use char arrays to store char strings. These char strings are terminated by
a special character null.
o In Java strings are supported by String class whose value are constant string, and
the String Buffer class whose value are changeable and are more like arrays of
single characters.
o C# and Ruby include string classes that are similar to those of Java.
¢ Python strings are immutable, similar to the String class objects of Java.

2) Is the length of objects static or dynamic ?


o The length can be static and set when the string is created. For example - in C, C++,
Java we can have static length string.
« When the string length is dynamic then it has no maximun limit. For example - Perl
and JavaScript provide this kind of facility.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-7 _ Strusturing the Data, Computations and Program
EEE®] string Operation
Various types of string operations include
1) Finding Length of string : Finding length means counting number of characters
within a string.
2) Comparing two string : In this operation, the match between characters from each
string is evaluated.
3) Finding substring : In this operation, the substring of the original string returms.
4) String concatenation : Concatenation is an operation in which second string is
appended to the first string.
[EEEE] string Length Options
o The string length can be static or can be dynamic. There are three kind of design
choices for string length -

[ 1. Static 2. Limited Dynamic 3. Dynamic

1) Static String Length : The length can be static and set when the string is created. For
example - in C,C+, Java we can have static length string. This is a choice for
immutable objects.
2) Limited Dynamic String Length : This option allows strings to have varying length
up to a declared and fixed maximum set by variable's definition
3) Dynamic String Length : When the string length is dynamic then it has no
maximum limit. For example
- Perl and JavaScript provide this kind of facility.
[EEEX] implementation of Character String Type
For each of the following type of strings the implementation methods vary -
¢ Static Length Strings : A descriptor for a static character string type, which is
required only during compilation, has three fields.
o Nameof the type
o Type's length
o Address of first char

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-8 _ Strusturing the Data, Computations and Program
Itis as shown in following Fig. 2.1.4 -
Static slring
Length
Address.

Fig. 2.1.4 Compile time descriptor


« Limited Dynamic Length Strings : It needs a run-time descriptor for length to store
both the fixed maximum length and the current length. The limited dynamic strings
of C and C+ do not require run-time descriptors, beca se the end of a string is
marked with the null character. They do not need the maximum length, because
index values in array references are not range-checked in these languages. It is as
shown by following Fig. 2.1.5 -
Limited dynamic string
Maximum length
Current length
Address

Fig. 2.1.5 Run time descriptor


« Dynamic Length strings : Dynamic length strings require more complex storage
management. The length of a string is not fixed hence storage may grow or shrink
dynamically.
K] User Defined Ordinal Types
These are the data types that are defined by the programmer with the help of primitive
data types. For example - In C structure is an user defined data type created using the
keyword struct

struct student {
int roll;
char name([10];
%
An ordinal type is one in which the range of possible values can be easily associated
with the set of positive integers. There are two user-defined ordinal types -

1) Enumeration Type 2) Subrange

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-9 Strusturing the Data, Computations and Program
1) Enumeration Type
Enumeration types provide a way of defining and grouping collections of named
constants, which are called enumeration constants.
For example in C# we can define the enum data type as follows -
enum days {mon, tue, wed, thu, i, sat, sun};
The enumeration constants are typically implicitly assigned the integer values, 0, 1,
but can explicitly assigned any integer literal in the type’s definition. That means, in
following example we can explicitly assign the enumeration constants
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades =
kL

Design Issues for Enumeration Types


Following are design issues for enumeration types -
o Is an enumeration constant allowed to appear in more than one type definition ?
o If enumeration constants appear in more than one type definition, then how the
type of an occurrence of that constant is checked ?
o Are enumeration values coerced to integer ?
Any other type coerced to an enumeration type ?
2. Subrange
« Subrange data types are used in Pascal and ADA. It is basically the a continuous
sequence of an ordinal types. For defining a subset of values the subrange
« Forexample -
type Color is(RED, ORANGE ,YELLOW,GREEN,
BLUE INDIGO,VIOLET)
subtype myfavcolor is Color range ORANGE. . BLUE;

R Array Types
o Array is collection similar data type elements
o It is homogeneous aggregate of data elements in which an individual element is
identified by its position in the aggregate, relative to the first element.
o Individual array element is specified using subscription expression
o Forexample - In C, C++ array can be declared as
int a[10];

TECHNICAL PUBLICATIONS' An up thrust for knowledge.


Principles of Programming Languages 2-10 __ Structuring the Data, Gomputations and Program
Design Issues
The primary design issues specific to arrays are the following :
1) What types are legal for subscripts ?
2) Are subscripting expressions in element references range checked ?
3) When are subscript ranges bound ?
4) When does allocation take place ?
5) Are ragged or rectangular multidimensional arrays allowed, or both ?
6) Can arrays be initialized when they have their storage allocated ?
7) Whatkinds of slices are allowed, if any ?

[EEEEA subscript Binding for Arrays


« The binding of subscript type to an array variable is usually static, but the subscript
value ranges are sometimes dynamically bound.
¢ InC, C++ the lower bound of all index ranges is fixed at 0; In Fortran 95, it defaults
tol.

[EREE] Array Categories based on Subscript Binding


There are basically four categorie:
1) Static Array : It is one in which the subscript ranges are statically bound and
storage allocation is static that means it is done before run time. Advantage of this
type of arrays is - Its working is efficient as there is no need to allocate and
deallocate memory.
2) Fixed Stack Dynamic Array : A fixed stack-dynamic array is one in which the
subscript ranges are statically bound, but the allocation is done at elaboration time
during execution. The advantage of this type is - it is space efficient. A large array in
one subprogram can use the same space as a large array in different subprograms.
3) Fixed Heap Dynamic Array : It is similar to fixed stack-dynamic. The storage
binding is dynamic but fixed after allocation (i binding is done when requested
and storage is allocated from heap, not stack).
4) Heap Dynamic Array : In this type, binding of subscript ranges and storage
allocation is dynamic and can change any number of times. The advantage of this
type of array is - it is very flexible.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-11__ Structuring the Data, Gomputations and Program
-Helemgeneous Array
¢ Heterogeneous array is a type of array in which the elements need not be of the
same data type.
o Heterogeneous arrays are supported by the programming languages such as Perl,
JavaScript, Python and Ruby.
o InPerl, the heterogeneous array consists of numbers, strings and references.
« InPython and Ruby array elements are references to the objects of any type.
-Army Initialization
* Array initialization is a process in which a list of values that are put in the array in
the order in which the array elements are stored in memory.
« Some language allow initialization at the time of storage allocation.
« Forexample - Following is an array initialization in C
int a[]={10,20,30};
e Character Strings in C & C++ are implemented as arrays of char. These arrays can be
initialized to string constants -
char name[] ="1SRO"
J/Note that this array will contain 5 elements and this string is terminated by null
o InJava the array of string can be initialized as follows -
String|] names=|"Aditya"," Aakash"," Amit"

- Array Operations
The common array operations are - assignment, catenation, comparison for
equality and inequality, and slices
o The C-based languages do not provide any array operations, except through the
methods of Java, Ct+, and C#.
o Perl supports array assignments but does not support comparisons.
« Python's arrays’ are called lists, they behave like dynamic arrays. In this lists the
objects can be of any datatype. Hence arrays are heterogeneous. Python also
supports array catenation and element membership operations.
« In Python, assignment with an = on lists does not make a copy. Instead, assignment
makes the two variables point to the one list in memory. For example
color=[10,20,30]
a=color;
The list will point to the same memory location as that of color.
+ Ruby also provides array catenation.
« APL provides the most powerful array processing operations for vectors and
matrixes as well as unary operators.
TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.
Principles of Programming Languages 2-12 _ Structuring the Data, Computations and Program
EBEEA Rectanguiar
and Jagged Arrays
Rectangular Array : A rectangular array is a multidimensional array in which all of
the rows have the same number of elements, all of the columns have the same number of
elements and so on.
For example -
rect_amay[3] 2]
1| 12| 13
14 15 16

17 18 19

Jagged Array: A jagged array is one in which the length of the rows need not be the
same. For example -
Jagged_anfo] —|
Jagged_anf3) (] et —

Jagged_anjr] —|

It can be represented as
int arr(]{] = new intll{l {
new intl] {1,2,34,5.6};
new int[] {7,8,9,1(
new int[] {11,12};
)
Slices
Slice of an array is nothing but the substructure of that array. The : Operator used
within the square bracket to indicate that it s a list slice and not the index of the list
For example in Python -
>>> a=[10,20,30,40,50,60]
>>> a[14]
(20, 20, 40]
>>> a[5]
(10, 20, 30, 40, 50]

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-13 _ Structuring the Data, Gomputations and Program
>>> al4]
150, 60]
>>>af]
10, 20, 30, 40, 50, 60]

Review Questions

1. Mention the primary design issues specific o arrays.


2. Explain the subscript binding and array categories.
3. Describe the process of array initialization.
4. Define and explain rectangular and jagged array.
X Associative Arrays
o Anassodative array is an unordered collection of data elements that are indexed by
an equal number of values called keys
« Eachelement of an associative array is a pair of a key and a value.
o Assodiative arrays are supported by the standard class libraries of Java, C++, C#,
and F#.
« For Example : In Perl, associative arrays are often called hashes. Names begin with
%; literals are delimited by parentheses. Hashes can be set to literal values with
assignment statement as shown below -
%ages= “AAA" =>25, "BBB"=>10, “CCC"=>55);
« Subscripting is done using braces and keys. For example -
S$ages{"CCC"}=48;
o InPython, the associative arrays are called as dictionaries. For example -
thisdiot= {
"brand": "Honda",
"model": "Honda-Civic',
'year': 2019
}
PHP’s arrays are both normal arrays and a ociative array.
o C#and F# support associative arrays through a .NET class
Review Question
1. Explain the concept of associative arrays with example.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-14 __ Structuring the Data, Gomputations and Program
XK Record Types
o A data structure which is collection of components of different data types is termed
as record.
o Specification : The attributes of record are
1. The number of components
2. The data type of each component
3. The selector used to name each component
o InC the syntax for record declaration is denoted by struct.
Forexample - InC, C++ and C#, records are supported with the struct data type
struct student{
int roll_no;
char name|[20];
}
Access to Record Fields
Most of the programming languages make use of dot operator to access or refer to
different fields of the record. For example -
struct student.roll_no
PAW4 Union yp Types
« A union is a type whose variables are allowed to store different type values at
different times during execution.
« Forexample - In C we can declare union as follows
union Student
{
char name[301;
int rollno;
}s1s2;
Here s1 and s2 are the variables of union.
« We can access the elements of union using dot operator. For instance sLrollno
« Note that only one member of unionis accessed at a time. For example if -
slname="AAA";
s1.rollng

Then as an output we get either s Lrollno =10 or sLname ="AAA”;

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-15 _ Structuring the Data, Gomputations and Program
ERERT Design Issues
The primary design union types are as follows -
1) Should unions be embedded in records ?

2 hould type checking is needed ? If so, then such type checking must be dynamic.
Discriminated and Free Unions
Two types of unions are
1) Free Union : The union constructs in which there is no language support for type -
checking is called free union. C, C++ provide such type of unions. For example -
union test {
inta;
float b;
}
‘union test u;
float x;

u. 10;
x=ub;
Note that the integer value is gned to the float variable in the last assignment and
there is no type checking mechanism.
2) Discriminated Union : Discriminated union is a union structure in which cach
union incude the type indicator. The discriminated unions are supported by
ALGOL 68, ML, HASKELL.

For example — the shape base class posses three derived dlasses namely Circle, Triangle
and Square classes.
type Shape
// The value here is the radius.
| Circle of float
// The value here is the side length.
| Equilateral Triangle of double
//'The value here is the side length.
| Square of double
// The values here are the height and width.
| Rectangle of double * double.
J&] ADA Union Types
The syntax is as follows -
type Typ (Choice : Discrete_Type) is record
case Choice is

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-16 __ Structuring the Data, Computations and Program
when Choice_1 =>
N1:Typl;

when Choice_2 | Ghoice 3=>

when others =>

end case;
end record;
For example -
type Traffic_Light is (Red, Yellow, Green);
type Union (Option : Traffic_Light := Traffic_LightFirst)is
record
- common components

case Option is
when Red =>
-- components for red
‘when Yellow =>
- components for yellow
‘when Green =>
-- components for green
end case;
end record;

Distinguish between PASCAL and ADA Union Types.


Solution : The ADA union is similar to Pascal union types but there is a difference
between the two -
1) In ADA, there are no free unions. That means the tag is specified with union
declaration.
2) When tag is changed, all appropriate fields must be set.
Review Question

1. Explain discriminated and free union variables.


Pointer and Reference Types
« Pointer : A pointer is a variable that stores a memory address, for the purpose of
acting as an alias to what is stored at that address.
o A pointer can be used to access a location in the area where storage is dynamically

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-17__ Structuring the Data, Gomputations and Program
allocated which is called as heap.
o Variables that are dynamically allocated from the heap are called heap dynamic
variables.
* Variables without names are called anonymous variables.

Uses of Pointers
1) Provide the power of indirect addressing.
2) Provide a way to manage dynamic memory. A pointer can be used to access a
location in the area where storage is dynamically created usually called a heap.
Design Issues
The primary design issues are
1) Should a language support a pointer type or reference type or both ?
2) What are the scope and lifetime of a pointer variable ?
3) Are pointers used for dynamic storage management, indirect addressing or both 2
4) Are pointers restricted as to type of value to which they can point 2
5) Whatis a the life time of dynamic variable ?

R} Point Operations
Consider the variable declaration
int *ptr;
pir is the name of our variable. The * informs the compiler that we want a pointer
variable, the int says that we are using our pointer variable which will actually store the
address of an integer. Such a pointer is said to be integer pointer.
‘Thus pr is now ready to store an address of the value which is of integer type,
ptr
~|—— We can stors the address
of some varable whose
value need 1o referrec.

Fig. 2.1.6 Pointer variable

The pointer variable is basically used to store some address of the variable which is
holding some value.
Consider ,
Line 1-> int *pw;
Line 2-> int a,b;

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-18 _ Structuring the Data, Comptations and Program
/*storing some value in a*/
a;/*storing address of a in ptr*/
‘ptr;/*getting value from address in ptr and storing it in b*/
Here we have used two important operators * and &. The * means ‘contents at the
specified addre and & means the ‘address at'.
On Line 1 and Line 2 we have declared the required variables out of which ptr is a
pointer variable and variables a and b are our normal variables. On Line 3 we have
assigned value 10 to variable a. The Line 4 tells us that address of variable a i tored in a
pointer variable ptr. And on Line 4 we have written that in ptr variable we have stored
some address and at that address whatever value is stored, store that value in variable b.
That means at ptr we have stored address of variable a. Then at the address of a whatever
is a value we have to store that value in variable b. This can be illustrated by following
Fig.2.17.

Fig. 2.1.7 Use of * and & operator


The dynamic memory allocation is done using an operator new. The syntax of
dynamic memory allocation using new is
new data type;
For example :
int *p;
p=new int;

We can allocate the memory for more than one element. For instance if we want to
allocate memory of size in for 5 elements we can dedlare.
int *p;
p=new int[5];

In this case, the system dynamically assigns space for five elements of type int and
returns a pointer to the first element of the sequence, which is assigned to p. Therefore,
now, p points to a valid block of memory with space for five elements of type int.

An up thrust for knowledge.


Principles of Programming Languages 2-19 _ Structuring the Data, Gomputations and Program
int

I I I
P
The memory can be deallocated using the delete operator. The syntax is
delete variable_name;
For example
delete p
Pointer Problems
Following are implementation problems when pointers are used -
1. Management of heap storage area : Due to creation of objects of different sizes
during execution time requires management of general heap storage area.
2. The garbage problem : Sometimes the contents of the pointers are destroyed and
abject still exists which is actually not at all accessible.
3. Dangling references : The object is destroyed however the pointer still contains the
address of the used location, and can be wrongly used by the program
For a language that provides a pointer type for programmer- constructed data
abjects and operations such as new and dispose that allocate and free storage for data objects,
write a program segment that generates a dangling reference. If one or the other program
segment cannot be written, explain why.
Solution : The dangling reference is a live pointer that no longer points to a valid object.

varq : integer;
var p: integer;
begin The live pointer p has created
now(p); reference for q and then p is deleted.
a=p; This creates dangling reference for q.
dispose(p);

end

Pnimers in Various Languages


CandC#++
Pointers are basically the variables that contain the location of other data objects. It
allows to construct complex data objects. In C or C++ pointer are data objects that can be
manipulated by the programmer.
TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.
Principles of Programming Languages 2-20 _ Structuring the Data, Gomputations and Program
For example -
int *ptr;
‘ptr=malloc(sizeof(int);
The * is used to denote the pointer variable.
FORTRAN 90
The fir ep in using Fortran pointer s to determine the variables to which you will
need to associate pointers. They must be given the TARGET attribute in a type statement
For example
real, target :: a, b(1000), ¢(10,10)
integer, target :: i, j(100), k(20,20)
Then we define some pointers as -
1eal, pointer :: pa, aptr, pb(:), pel(:), pe2(.:)
The type of the pointer must match the type of the intended target
ADA
Pointers in ADA are known as access types. There are four kinds of access types in
Ada : pool access types, general access types, anonymous access types, access to
subprogram types.
For example -
type It is range -100 . +500;
type Acc_Int is access Int;

PASCAL
Pascal support use of pointers. Pointers are the variables that hold the address of
another variable.
For example -
Program pointers;
type
Buffer = String|255];
BufPtr = ~ Buifer;
Var B : Buffer;

In this example, BP is a pointer to a Buffer type; while Bis a variable of type Buffer.
- Reference Type
* Reference : A reference 1s a variable that refers to something else and can be used as
an alias for that something else.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-21__ Structuring the Data, Gomputations and Program
A pointer is a reference, but a reference is not necessarily a pointer.
* Difference between Reference and Pointer Variable

No. Reference Pointer


1 References must be initialized when Pointer can be initialized at any time.
created.
2. Oncereference is assigned with Pointers can point to another object at any
some object it can not be changed. time,
3. Onecannothave NULL references. The pointer can be assigned with the value
NULL.

o In pointers to access the value of actual variable we need to explicitly dereference


the pointer variable by using value at address or using * operator. In references, to
access the value of actual variable we do not need to explicitly dereference the
reference variable.
o InCr, the reference variable is a better choice for formal parameter than pointer. It
must be initialized with the address of some variable in its definition and after
initialization a reference type variable can never be set to reference any other
variable,
« Reference can never point to NULL value whereas pointer can point to NULL. Thus
with the use of reference there can not be NULL pointer assignment problem.
« Creating Reference Variable
The reference variables are created using the &. For example we can create a
reference variable x for an integer variable a. It is as follows
0;
/[ xis a reference

Here variable x acts as a reference variable for variable i. Hence if value of i is


changed then the value of x changes automatically. This is because variable x is a
reference of variable i.
Review Question
1. What is built-in and primitive data types? State the primitive data types in C++ and Jaon.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-22 _ Structuring the Data, Computations and Program
BB Expression and Assignment Statements

X1 Arithmetic Expressions
+ Arithmetic expressions consist of operators, operands, parentheses, and function
calls.
o Forexample x=y+2*sqrt(25);
o The purpose of an arithmetic expression s to specify an arithmetic computation.
- Design Issues
Design issues for arithmetic expressions are -
1) What are the operator precedence rules 2
2) What are the operator associativity rules ?
3) What is the order of operand evaluation ?
4) Are there restrictions on operand evaluation side effects 2
5) Does the language allow user-defined operator overloading ?
6) What mode mixing is allowed in expressions ?
Precedence and Associativity
Precedence :
o The operator precedence rules for expression evaluation define the order in which
the operators of different precedence levels are evaluated.
« Many languages also include unary versions of addition and subtraction.
o Unary addition (+) is called the identity operator because it usually has no
associated operation and thus has no effect on its operand.
Inall of the common imperative languages, the unary minus operator can appear
in an expression either at the beginning or anywhere inside the expression, as long
as it is parenthesized to prevent it from being next to another operator. For example,
unary minus operator (-) :
x+(y)*z J/is legal
X+-y*z J/is llegal
« Exponentiation has higher precedence that unary minus.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-23 _ Structuring the Data, Computations and Program
o The precedence of Ruby and C language operators is as given in following table
Precedence Ruby cIcH

Highest = postlix ++,-


unary 4 - prefix ++,~unary +-
1% 1%
Lowest binary +, - binary +, -

Associativity :
o The operator associativity rules for expression evaluation define the order in which
adjacent operators with the same precedence level are evaluated. An operator can
be either left or right associative.
o Typical associativity rules:
o Left to right, except exponentiation **, which is right to left.
o Forexample— a-b+c /1 left to right
© Sometimes unary operators associate right to left (Fortran)
A**B**C // right
to left.
(a*B*C //in Ada it mustbe parenthesized
o The associativity rules for a few common languages are given here :
Language Associativity Rule
Ruby, FORTRAN Left:®, [/ +, -
Right: **
C-Based Languages 1, %, binary +, binary -
Right : ++, —, unary-, unary +

Operand Evaluation Order


The operand evaluation order is as given below -
1) Variables : Fetch the value form memory.
2) Constants : Sometimes a fetch from memory; sometimes the constant in the
machine language instruction and not require a memory fetch.
3) Parenthesized expression : Evaluate all operands and operators first.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-24 _ Structuring the Data, Gomputations and Program
Overloaded Operators
o Overloading the operators is an activity for using the operator for more than one
purpose. For example - the + operator can be used for addition of two integers, two
complex numbers or for concatenating two strings.
« Both binary and unary operators can be overloaded
o Cr+ has few operators that can not be overloaded such as dot operator(), scope
resolution(:) operator.
o User-defined operator overloading can harm the readability of a program because
the built in operator has the precision and compiler knows all the precision between
the operators, and it works on that precision. User can also create its own operator
but the compiler does not come to know how to make precision of this operator.
This will be the cause of the overloading harm.

EXE] Type Conversion


« Type conversion is a technique in which element present in one data type can be
converted into another data type.
o There are two type of conversions —
[l)Narmwinp,cun\'ersiunand 2) Widening conversion. I
A narrowing conversion is one that converts an object to a type that cannot include
all of the values of the original type. For example - conversion from double to float.
A widening conversion is one in which an object is converted to a type that can
include at least approximations to all of the values of the original type. For example
- from int to float.

There are two approaches of type conversions -


1) Implicit type conversion : This type of type conversion is also called as coercion.
The one data type element is automatically converted into another data type by
widening conversion.
For example : In the following code the character data type of variable ¢ is
converted implicitly to integer data type.
int num = 10;
char ¢ = 'm’; /* ASCII value is 109 */
int sum;
cum — num + o; // output:119
In Ada, there are virtually no coercions in expressions
In ML and F#, there are no coercions in expressions

TECHNICAL PUBLICATIONS' An up thrust for knowledge.


Principles of Programming Languages 2-25 _ Structuring the Data, Gomputations and Program
2) Explicit type conversion : It is also called as type casting is C based languages
Syntax is
(type-name) expression
For example —
floata = 1.5;
inth=(ntja+ 1 //outputwill be 2
XX Relational and Boolean Expression
Relational Expression
o Any relational expression is comprised of relational operator and two operands. A
relational operator is an operator that compares the values of its two operands
o The value of a relational expression is Boolean, unless it is not a type included in the
language
o Operator symbols used vary somewhat among languages (1=, /=, .NE., <, #)
o The syntax of the relational operators available in some common languages is as
follows :
Operation Ada C-Based Languages Fortran 95
Equal - - EQ or—
Not Equal /= = NE.or<
Greater than > > GT.or>
Less than < < LT or<

Greater than or equal >= >~ GE.or>=


Less than or equal -~ < LE. or >=
* JavaScript and PHP have two additional relational operator, = and !=

Boolean Expression
o In boolean expression, the operands are Boolean and result of the expression is
Boolean.
« Boolean operators used in various languages are -
FORTRAN 90 C Ada

and && and


or " or

not. ! not

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-26 _ Structuring the Data, Gomputations and Program
During evaluation of Boolean expression, the leftmost operator is evaluated first
because in C language the relational operators are left associative producing either 0 or 1.
X short Circuit Evaluation
Short circuit evaluation is a kind of evaluation in which the expression is evaluated
only if it is necessary.
MODULA-2 uses short circuit evaluation for OR and AND operators. The short circuit
evaluation is also allowed in C as well.
For example -
‘while( p>=0
&& g<=10)

If p>=10is true then only the control reaches to test q<=10


With short circuit evaluation,
i) While evaluating E1 or E2, if E1 is true then the whole expression is true and in that
case E2 is not evaluated.
ii) Similarly, while evaluating E1 and E2, if E1 is false then E2 is not evaluated.

XX Assignment Statement
The purpose of assignment statement is to assign the value to a variable.
Types of Assignment Statements
1) Simple Assignments : The language like C, C++, JAVA makes use of = operator for
assignment statement. The ALGOL, PASCAL, ADA makes use of := operator for
assignment purpose.
2) Conditional Targets : In Per! the conditional target can be specified as -
($count ? $total : $subtotal) = 0
‘The above code is equivalent to
if (Scount){
S$total =
Yelse {
$subtotal = 0
}
3) Compound Assignment Operator : This is commonly used form of assignment
statement in which shorthand method of using assignment statement.
For example -
a=atb
can be written as
at=b;

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-27 _ Structuring the Data, Gomputations and Program
4) Assignment as an Expression : In the C-based languages, Perl, and JavaScript, the
assignment statement produces a result and can be used as an operand.
while ((ch = getchar())!=EOF) {

In above code, ch = getchar() is carried out; the result (assigned to ch) is used as a
conditional value for the while statement.
5) Unary Assignment Operator : 1t is possible to combine increment or decrement
operator with assignments. The operators ++ and - can be used cither in expression
or to form stand-alone single-operator assignment statements. They can appear as
prefix operators.
For example -
sum = ++ count; is equivalent to count=count+1; sum=count;
1If the same operator appears as postfix operator then
sum=count+ +; sum=count; count=count-+1
6) Multiple Assignments : It is possible to perform multiple assignments at a time. For
example - the Perl, Ruby, and Lua provide multiple-target multiple-source
assignments.
(Sone, $two, $three) = (100, 200, 300);

Mixed Mode Assignment


o Assignment statements can also be mixed-mode.
o In Fortran, C, and C+, any numeric value can be assigned to any numeric scalar
variable; whatever conversion is necessary is done.
« InJava and C#, only widening assignment coercions are done.
o In Ada, there is no assignment coercion.
o In all languages that allow mixed-mode assignment, the coercion takes place only
after the right-side expression has been evaluated. For example, consider the
following code :
inta, b;
float¢;

c=a/b;
In above code, c is float, the values of a and b could be coerced to float before the
division.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-28 _ Structuring the Data, Computations and Program
Review Questions

1. Explain implicit and explicit type comversion process.


2. What is short circuit evaluation? Explain.
4. Explain various types of assignment statements.
5. Explain mix mode operation.
Pl statement-level Control Statements
A control structure is a control statement and the statements whose execution it
controls.
Design Issue : There is only one design issue for control structure -
“ should a control structure have multiple entries ?”

Selection Statements
For choosing one correct path from two or more paths of execution, the selection
statement is used.
There are two general categories of selection statements

{ 1) Two Way Selectors 2) Multiple-way Selectors J

1) Two way selectors : The general form of two way selector statement is -
if control_expression
then clause
else clause

Here
Control expression : Thes se are specified in parenthesis. Some languages like C, C+ or
JAVA do not use the reserved word then. The Java, C, C++ makes use of boolean
expressions for control expressions
Clause : In most contemporary languages, the then and else clauses either appear as
single statements or compound statements. C-based languages use braces to form
compound statements. One exception is Perl, in which all the and else clauses must be
compound statements, even if they contain single statements. In Python and Ruby,
clauses are statement sequences. Python uses indentation to define clauses. For example -
ifa>b:
a—b
‘print " a is greater than b*

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-29 _ Structuring the Data, Gomputations and Program
Design Issues for Two-way Selection
1) How are then and else clauses specified ?
2) What s the form and type of expressions used for selection ?
3) How to specify the meaning of nested selectors ?
2) Multiple-way Selectors : It allows the selection of one of any number of statements
or statement groups. For example - In C we can use switch case statement as
switch (choice) {

break;
case 4:c=a/b;
break;
default : printf(*exit”);
}
Design Issues for Multi-way Selection Statement
1. Whatis the form and type of the control expression ?
2. How are the selectable segments specified ?
3. Is execution flow through the structure restricted to include just a single selectable
segment ?
4. How are case values specified ?
5. Whatis done about unrepresented expression values 2
Itera e Statements

Definition : Iterative statements is one that cause a statement or collection of


statements to be executed zero one or more times.
o The repeated execution of statements can be achieved either by iterative statements,
or by using recursion
o The iterative statements are normally called as loop.
o The general design issues for iterative statements are,
o How is iteration controlled ?
© Where should the control mechanisin appear in the loop statement 2
o The loop has body which is basically collection of statements whose execution is

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-30 _ Structuring the Data, Gomputations and Program
controlled by iterative statements,
o The iteration statement and the associated loop body together form an iteration
statement.

o There are two important terms associated with loop and those are -
o Pretest : The term pretest means that the loop completion occurs before the loop
body is executed.
o Posttest : The term pretest means that the loop completion occurs after the loop
body is executed.
o Example of Loop : Following is an example of for loop used in C
0;i<10;i++)

EEEX] Counter Controlled Loops


« The counter-controlled loops are those loop that possess a variable called the loop
variables. This loop variable i used to maintain the count value.
o The loop variables of counter controlled loops include the means of specifying the
initial and terminal values of the loop variable, and the difference between
sequential loop variable values, is called the stepsize.
o The initial, terminal and stepsize are called the loop parameters.
o Design issues for the counter controlled loops are -
© What are the type and scope of the loop variable ?
o Should it be legal for the loop variable or loop parameters to be changed in the
loop body, and if so, does the change affect loop control ?
o Should the loop parameters be evaluated only once, or once for every iteration ?
* Example of counter controlled loop : Following code in Java that displays the
character and its’ ASCII value for all lower case characters.
for (char x = 'a; x <= x++)
System.out printinx + "+ (int) x);

EEEH] Logically Controlled Loops


« The logically controlled loop is a kind of loop statement in which repetition control
is based on a Boolean expression rather than a counter,
Cand C+ have both pretest and posttest forms, in which the control expression can
be arithmetic :
TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.
Principles of Programming Languages 2-31__ Structuring the Data, Gomputations and Program
Forexample :
while(control_expression) do
loop body loop body
while(control_expression)
o Inboth C and C++it s legal to branch into the body of a logically-controlled loop.
o Javais like C and C+, except the control expression must be Boolean.
« Design Issues are
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 ?

m User-located Loop Control Mechanism


« This is a control structure in which programmer choose a location for loop control.
This location generally other than the top or bottom of the loop.
e In C or C+ the user located loop control mechanism is accomplished using
unlabeled exits such as break.
o Following is an example user located loop control using C#
UP:
for (row = 0; row < 1; row++)
for (col = 0; col <m; col++)
sum += a[row][col];
if (sum > 1000.0)
break UP;
i
« The motivation for user-located loop exits is simple.
« They fulfill a common need for goto statements through a highly restricted branch
statement.
« The target of a goto can be many places in the program, both above and below the
goto itself .
PEEY] Examples of Looping in C
The iteration means repeated execution of statements based on some condition. In €
the for, while, do-while statements are used for iterations.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-32 _ Structuring the Data, Gomputations and Program
1. forloop : The general form of for loop is
for(initialization;condition;step)
{
. //statements
}
2. while statement : The general form of while statement is
‘while(condiition)
{
.//statements
}

3. do-while: The general form of do-whileis


do
{
.//statements
}while(condition);
For example - Following code will store numbers 10,11,12,13,14,15 in an array and
display them
#include <stdioh>
void main()

printf(*%d" ali );

EEE] unconditional Branching


« An unconditional branch statement transfers execution control to a specified place
in the program.
« The unconditional branch, or goto, is the most powerful statement for controlling
the flow of execution of a program’s statements
« Forexample -

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-33 _ Structuring the Data, Computations and Program
sum = sum+i;
if(i==5)
{
goto addition;
}
}
addition:

printi(%d", sum);
o Java, Python, and Ruby do not have a goto. C# uses goto in switch statement.
Problems associated with unconditional branching
¢ The unconditional branch, or goto, is the most powerful statement for controlling
the flow of execution of a program atements.
« Without restrictions on use, imposed by either language design or programming
standards, goto statements can make programs very difficult to read, and as a
result, code becomes highly unreliable and costly to maintain.
« The gotos have ability to force any program statement to follow any other in
execution sequence, regardless of whether the statement proceeds or follows
previously executed statement in textual order.
B subprograms

Fundamentals of Subprograms
o Subprograms can be viewed as abstract operations on a predefined data set.
* A subprogram definition describes the interface to and the actions of the
subprogram abstraction
o A subprogram call is an explicit request that the subprogram be executed. For
example - In Python the header of subprogram is as follows -
dof swap(parametors):
o There are two categories of sub-program—
Procedure and 2. Function:

+ Procedure - Procedure is set of commands executed in order.


o Function - Function is set of instructions for used for some computation.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-34 Structuring the Data, Computations and Program
IEXEE] General Subprogram Characteristics
« Each subprogram has a single entry point.
o The calling program is suspended during execution of the called subprogram.
o Control always returns to the caller when the called subprogram’s execution
terminates.

JF] Basic Definitions


o The subprogram call is an explicit request that subprogram be executed.
o The subprogram header is first part of the definition, including the name, the kind
of subprogram and the formal parameters.
o The signature is also called as parameter profile which is nothing but the number,
order and types of its parameters.
EXEE] P rocedure and Functions
Sr.No. Procedure Function
1 Procedure may or may not retum a value. Function returns a value.

2. Procedure is set of commands executed in ~ Function is set of instructions for used


order. for some computation.
3. Function can be called from procedure. Procedures can not be called from
function.
4. Example - Pascal, ADA are some Example - C, C++, Java are some
programming languages that make use of programming languages that make
procedures. use of functions.

Example of Procedure in Pascal


Procedure MaxNum (x, y : integer; var z : integer)
begin
i x> ythen
z=x
else

end;

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-35 _ Structuring the Data, Gomputations and Program
Example of Function in Pascal
Function MaxNum (x, y : integer) : integer; ( returning maximum between two numbers )
var
rTesult : integer;
Dbegin
if (% > y) then
Tesult: =

Different Elements of Procedure


Various elements of procedure are -
1. Name for declaration of procedure
2. Body consisting of local declarations and statements
3. Formal parameters which are the placeholders of actuals
4. Optional result type.
For example
Consider following C code
# include < stdioh>
void main
{
int ab;

- sum(ab);
printi(%d ¢
Formal
Pmcgdure\/'parame1ers

mt stm(intwx, int

ype Local
declarations

intz;
asx+ Body
7 retan z of
( procedure

Statements
TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.
Principles of Programming Languages 2-36 _ Structuring the Data, Gomputations and Program
Benefits of Procedure
Following are some benefits of using procedures
The implementation of certain piece of code can be separated out from the main
implementation. Suitable names used for such procedure represents its purpose as
well. For instance - If we call swap(a,b) function in the main implementation then it
will indicate interchanging of the values a and b.
2. Writing a separate procedure allows to hide implementation details. The main
procedure looks abstract with simply the call to the procedure.
. Procedures can be used to partition a program into smaller modules. These
©

modules are useful to maintain a large and complex code.


4. Finding errors from a large complex program becomes simplified when procedures
or functions are written.

EX®] Design Issues for Subprogram


The design issues are as follows -
* Are local variables static or dynamic ?
o Can subprogram definitions appear in other subprogram definitions ?
« What parameter passing methodsare provided ?
o Are parameter types checked ?
o If subprograms can be passed as parameters and subprograms can be nested, what
is the referencing environment of a passed subprogram ?
« Can subprograms be overloaded ?
« Can subprogram be generic ?
o If the language allows nested subprograms, are closures supported ?
EXE] Local Referencing Environments
What is the meaning of referencing environment 2
o Each program or subprogram has a set of identifiers that has associations for the use
in referencing during its execution. Thus referencing environment is a complete set
of bindings active at a certain point ina program.
* Local referencing environment : This kind of referencing environment is denoted
by the set of identifiers that are created on the entry of the subprogram and are
used within the subprogram. The meaning of reference to the name can be found
within the local environment of the subprogram definition. For example local

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-37___ Structuring the Data, Gomputations and Program
variables, and formal parameters represent the set of identifiers that are associated
with local referencing environment, This kind of referencing environment is also
called as local environment.
Local Variables
« Variables that are defined inside subprograms are called local variables, There are
two types of local variables -

1. Static Local Variables 2. Stack Dynamic Variables J

1. Static local variable : The static local variables are variables whose scope finishes
when the subprogram within which it is defined gets terminated and they retain
their value once they are initialized.
Advantages :
1) The static local variables are efficient than stack-dynamic local variables as they
require no run time overhead for allocation and deallocation.
2) It allows direct accessing.
3) They allow subprograms to be history sensitive.
Disadvantages :
1) They do not support for recursion.
2) The storage for locals cannot be shared among some programs
2. Stack dynamic variable : The stack dynamic local variables are kind of local
variables which are bound to storage when the subprogram begins execution and
are unbound from storage when the execution terminates. Stack-dynamic variables
are allocated from the run-time stack.
Advantages
1) The stack dynamic local variables support for recursion.
2) The storage for locals is shared among some subprograms.
Disadvantages
1) The cost is required to allocate, initialize, and deallocate the variables for each
call to subprogram.
2) Accesses to stack dynamic local variables must be indirect.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-38 _ Structuring the Data, Computations and Program
3) When all the local variables are stack dynamic, subprograms cannot be history
sensitive. That means they can not retain data values of local variables between
calls
m Nested Subprograms
Some non-C-based static-scoped languages such as Fortran 95, Ada, Python,
JavaScript, and so on use stack-dynamic local variables and allow subprograms to
be nested.
All variables that can be non-locally accessed reside in some activation record
instance in the stack.
The process of locating a non-local reference is as follows -
o Find the correct activation record instance
© Determine the correct offset within that activation record instance
Locating a non-local reference
o Finding the offset is casy
o Finding the correct activation record instance
Static semantic rules guarantee that all non-local variables that can be referenced
have been allocated in some activation record instance that is on the stack when the
reference is made.
XX Parameter Passing Methods
Parameter passing is the mechanism used to pass parameters to a procedure
(subroutine) or function.
The most common methods are to pass the parameters are call by value and call
by reference.
When the value of the actual parameter is passed then it is called call by value
method.
When we pass the address of the memory location where the actual parameter is
stored to the function or procedure then it is called as call by reference method.

Various Parameter Passing Methods


1 Call by value : This is the simplest method of parameter passing
o The actual parameters are evaluated and their r-values are passed to called
procedure
« The operations on formal parameters do not changes the values of actual
parameter

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-39 _ Structuring the Data, Gomputations and Program
Example : Languages like C, C++ use actual parameter passing method. In
PASCAL the non-var parameters.
2. Call by reference : This method is also called as call by address or call by location.
The L-value, the address of actual parameter is passed to the called routines
activation record.
o The values of actual parameters can be changed.
« The actual parameters should have an L-value.
Example : Reference parameters in C++, PASCAL'S var parameters.
3. Copy restore : This method is a hybrid between call by value and call by reference.
This method is also known as copy-in-copy-out or values result.
« The calling procedure calculates the value of actual parameter and it is then
copied to activation record for the called procedure.
« During execution of called procedure, the actual parameters value is not
affected.
e If the actual parameter has L-value then at return the value of formal
parameter is copied to actual parameter.
Example : In Ada this parameter passing method is used.
4. Call by name: This s less popular method of parameter passing.
o Procedure is treated like macro. The procedure body is substituted for call in
caller with actual parameters substituted for formals.
o The actual parameters can be surrounded by parenthesis to preserve their
integrity.
o The locals names of called procedure and names of calling procedure are
distinct.
Example: ALGOL uses call by name method.
Difference between Parameter Pass By Value and Parameter Pass By Reference

Call By Value Call By Reference


When a function is called, then in that When a function is called, then in that
function actual values of the parameters function addresses of the parameters are
are passed. passed.
The parameters are simple variables. The parameters are pointer variables.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-40 Structuring the Data, Computations and Program
1f the values of the parameters get 1 the values of the parameters get
changed in the function then that change changed in the function then that change
is not permanent. That means the values is permanent. That means the values of
of the parameter get restored when the the parameter get changed when the
control returns back to the caller control returns back to the caller function.
function.
Example: Example
‘main() main()
{ {
x=10; x=10;
fun(x); fun(x);
‘printf(*%d” x);} ‘printf(*%d",*x);
void fun(x) }
{ wvoid fun(x)
{
+ x=15;
Output willbe 10 and not 15 i
Output will be 15 and not 10
Compiler executes this type function Compiler executes this type of function
slowly as values get copied to formal faster as addresses get copied to the
parameters. formal parameters.
Parameter Passing Methods of Common Languages :
ne
It supports pass by value method
o The pass by reference is achieved by using pointers as parameter.
2Cs:
A special pointer type called reference type is used for pass-by-reference.
3)dava:
All parameters are passed by value
o Obiject parameters are passed by reference
4 ADA:
There are 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

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-41__ Structuring the Data, Gomputations and Program
5)CH:
* Default method of parameter passing is pass by value.
o Pass-by-reference is specified by preceding both a formal parameter and its actual
parameter with ref as keyword.

X Abstract Data Types and Encapsulation Construct


Concept of Abstraction
© An abstraction is a view or representation of an entity that includes only the most
significant attributes.
o Itis fundamental aspect of programming.
« Almost all the languages support process of abstraction with subprograms.
o Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it docs it.
* InJava, abstraction is achieved using Abstract classes and interfaces.

Benefits of Abstraction
1) It allow organization of data and corresponding operations in a single unit which
can be considered as a data structure together.
2) Modifications can be made easily without affecting rest of the code.
3) By hiding the data representations, user code cannot directly accessible. This helps
in making the programs reliable.
Data Abstraction
o The concept of data abstraction is represented by means of abstract data type.
o An abstract data type is a user-defined data type that satisfies the following two
conditions :
1) The representation of objects of the type is hidden from the program units that
use these objects.
2) The declarations of the type and the protocols of the operations on objects of the
type are contained in a single syntactic unit. Other program units are allowed to
create variables of the defined type.
Procedural Abstraction
o It specifies what a procedure does and ignores how it does. Following are
advantages of procedural abstraction -

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-42 _ Structuring the Data, Gomptations and Program
1) Locality: Programmers don’t need to know the implementation details.
2) Modifiability: Replacing of one code does not affect another code.
3) Language Independence : Due to procedural abstraction implementation could
be done in any programming language.
o Procedural abstractions are normally characterized in a programming language as
“function/sub-function” or "procedure” abstraction.
Difference between Data Abstraction and Procedural Abstraction
Data Abstraction Procedure Abstraction
‘The focus is primarily on dataand thenon The focus is only on procedures for
procedure for abstraction. abstraction.
Data abstraction is characterized asa data Procedural abstractions are normally
structure unit. characlerized in a programming language as
“function/sub-function” or "procedure”
abstraction.

The advantage of data abstraction over Due to procedural abstraction implementation


procedural abstraction is that the dataand could be done in any programming language.
the associated operations get specified
together and hence it is easy to modify the
code when data changes.

Design Issues For Abstraction


Following are the design issues of abstract data types -
1) What is the form of the container for the interface to the type ?
2) Can abstract types be parameterized ?
3) What access controls are provided ?

EEE] Parameterized Abstract Data Types


« Parameterized ADTs allow designing an ADT that can store any type elements -
only an issue for static typed languages.
« Itisalso known as generic classes.
C++ Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-43 _ Structuring the Data, Gomputations and Program
Parameterized ADT in ADA
The generic package can be used for implementing the stack of any type of elements is
as follows -
generic
Max: Positive;
type Element_T is private;
package Generic_Stack is
procedure Push (E: Element_T);
function Pop retum Element_T;
end Generic_Stack;
package body Generic_Stack is
Stack: amay (1. Max) of Elemen_T;
Top : Integer range 0 . Max = 0; - initialiseto empty

end Generic_Stack;
A stack of a given size and type could be defined in this way :
declare
package Float 100 Stack is new Generic_Stack (100, Float);
use Float_100_Stack;
begin
Push (45.8);

end;
Parameterized ADT in C++
Templates are considered to be the generic abstract data type. In case of templates, the
data components can be of different types however, the operations are the same.
Using class template we can write a class whose members use template parameters as
types.
The complete program using clas s template is as given below.
#include <iostreamh>
template <class T>
class Compare { //writing the class as usual
Ta,b; //note we have used data type as T
public:
Compare (T first, T second)
{
irs;
econd;
¥
Tmax () //finds the maximum element among two.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-44 _ Structuring the Data, Computations and Program
/emplate class member function definition
//here the member function of template class is max
template <class T>
T Compare <T>:: max ()
{
T val;
if(a>b)
val=a;
else.
val=b;
Tetum val;

void main ()

Compare <int> obj1 (100, 60); J/comparing two integers


Compare <char> obj2(p' /fcomparing two characters
cout <<"\n maximum(100,60) = ' <obj1.max();
cout<<"\n maximum(p,t) = "<obj2.max();
}
Output
maximum(100,60) 100
maximum(p),t)

k] Encapsulation Constructs
« Encapsulation is a mechanism for wrapping the data (variables) and code acting on
the data (methods) together as a single unit.
The logical module of C++ is class. The class defines the encapsulated unit. It
encapsulates the data members and the operations that can be performed on these
data members.
For example
class Test
{
private:
intabe;
public:
void add();
void display();

« Thus encapsulation approach is useful in two ways -


o Itbinds the data members with operations or methods.
o Itimposes the level of abstraction in a program.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-45 _ Structuring the Data, Gomputations and Program
Review Question

1. What are abstract data types ? How C-++ implements abstract data types ? Give example.
PU : Dec
XX Naming Encapsulations
o 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,
o C#+,Ct,Java, Ada, and Ruby provide naming encapsulations
« Namespaces are used to group the entities like class, variables, objects, function
under a name. The namespaces help to divide global scope into sub-scopes, where
each sub-scope has its own name.
« Forexample - Following C+ program shows how to create namespaces
namespace nst
{

}
namespace ns2
{
char a[] = 'Hello'; s
}
int main ()
{
cout<<nsia << endl;
cout<<ns2:a << endl;
retum 0;
}
Program Explanation :
In above program,
1) There are two different namespaces containing the variable a. The variable a in the
first namespace nsl is of type int but the variable a in the second namespace ns2 is
of array of characters. The both the entities are treated separately. There is no
re-declaration error for variable a.

TECHNICAL PUBLICATIONS™ - An up thrust for knowledgo.


Principles of Programming Languages 2-46 _ Structuring the Data, Computations and Program
XA Mutliple Choice Questions
Q1 Which of the followingis not valid variable name?
[a]int $index; int index1;
[d]int index;
Explanation : The variable name should not begin with special symbols like @, #, $, %
and so on
Q.2 Which of the following is true for variable names in C?

[&] They can contain alphanumeric characters as well as special characters


Variable names cannot start with a digit
It is not an error to declare a variable to be one of the keywords (like goto, static)
[d] None of these
Q.3 Which of the following is true of l-values and r-values ?
[a]An Lvalue is alogical value, and an r-value is a real value.
[b]1-values are always to the left of r-values
An |-value refers to a variable's location while an r-value to its current value
[d] 1-values are local and r-values are relative.
Q4 Which is the longest scope in the following code?
#include<stdioh>
int x;
int main()
{
inty;
fun();
retum 0;
i
void fun()
{
intz;
i
[ bly
[d]botha andb
Explanation : The variable x is a global variable and its scope is entire program
including all the functions

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-47 __ Structuring the Data, Gomputations and Program
Q5 The variables which can be accessed by al modules in a program, are called
local variables intemal variables
external variable global variables
Q.6 The value of an automatic variable that is declared but not initialized will be
2o
Unpredictable [d] none of these
Explanation : If the variable is not initialized then it takes the garbage value. Hence the
unpredictable value is present in the unintialized variable.
Q.7 Which of the following is not data type in Pascal?
[a]real [b]float
char [d]integer
Q8 What will happen
if null pointer is converted
to bool
The bool value is evaluated to true
[b] The bool value is evaluated to false
error is raised

[d]None of these
Explanation : In pointer, the nonzero pointer is converted to true and zero pointer is
converted to false.
Q9 Whatis the output of the following code?
int main(void)
{
char name = 'P;
'P' = 10; /* assigningto character
P number 10 */
retumn 0;

[a] name will contain value 10 [6]P will contain 10


Syntax error None of these
Explanation : The assignment P'=10 will cause the error: Lvalue required as left
operand of assignment.
Q.10 Choose the correct statement
[a] Reference is stored on stack Reference is stored on heap
Reference is siored on queue Nore of these

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-48 _ Structuring the Data, Computations and Program
Q.11 Discriminated unions are supported by
c for
All of these

[d]:
Q.13 Choose the correct statement.

I. Array of References can be created.,


1l Change in reference changes the referent.
[a]only 1is correct [b] Only s correct
Both 1 and Il are correct [d] Neither 1 and Il are comect
Q.14 Choose the correct statement.
Reference must be initialized within a function.
[b] Reference must be initialized outside the function.
Reference must be always initialized.
None of these
Q.15 Choose the correct statement.
[a] A reference is not a constant pointer
Reference is automatically de-referenced
Bothaand b
none of these

Q.16 Choose the correct option.


[a] A referenced variable need not be de-referenced to access value.
A referenced variable need to be de-referenced to access value.
It depends upon the type of reference whether to de-refer it fo access value.
[d] None of these
Q.17 Choose the correct statement |. The variable and its reference are linked together.

Il. We can change the value of variable via its reference.


[a]ony1 [blony
Both Tand II [d]None of these

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-49 _ Structuring the Data, Computations and Program
Q.18 If an expression contains double, float, and long then the data type of that expression
becomes._
[a]int [b]float
double

Q.19 Explicit type conversion is known as


casting
separation None of these

Q.20 What is strong type system?


[&] The type system in which only buill-in data types are allowed.
The lype system in which only user defined data types are allowed.
The type system that guarantees not to generate type errors.
[d] None of these
Q.21 For representing logical values _____ data type is used in C++.
[a]int [b]bool
[d]al of the above
Explanation : The C++ allows the boolean data type for denoting true or false values.
Q.22 Looping in a program means_ .
jumping to the specified branch of program
[6] repeat the specified lines of code
both of above
none of these

Q.23 Which of the following s the correct order of evaluation for the below expression?
z=x+y z/4%2-1
E*/% +-= 1%+ -
%I+ =
Q.24 Which of the following statement allows the programmer to make the control to the
beginning of the loop, without executing the next statement inside the loop ?
[a] while Continue
[d]ie

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-50 _ Structuring the Data, Gomputations and Program
Q.25 Which selection process is an example of muttiple branches from a single expression?
[b]select Case
For....Next

Q.26 What s required to reference an element in an array ?


[a] Array name [b] index value of the element
Element value [d]Both aand b
Q.27 The following
the exit controlled loop :
[a] while [b] do-while
[dgoto
Q.28 The scope of a variable refers to : .
[2] The length of the variable [b] The name of the variable
The accessibility of the variable The lifetime of the variable

Q.29 The attributes of three arithmetic operators in some programming language are given
below.
Operator | Precedence Associativity | Arity
+ High Left Binary
- Medium Right Binary
* Low left Binary
The value of the expression 2-5+1-7*3 in this language is ?
[h [b]2
[d]o
Explanation :
2(5+1)-7*3 as + is having high precedence
=26773
= 2:(67)"3 as - has medium precedence
=2:(1)'3
=3%3
=9

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.


Principles of Programming Languages 2-51 Structurring the Data, Gomputations and Program
Q.30 The goal of structured programming is to :
[a] Have well indented programs
[b] Be able to infer the flow of control from the compiled code
Be able to infer the flow of conirol from the program fext
[d] Avoid the use of GOTO statements
Answer Keys for Multiple Choice Questions :
Q1 A Q2 b Q3 Q4
Qs d Q6 ¢ Q7 Qs
Q9 c Q10 a Qi1 Q12
Q13 b Q1 < Q.15 Q16
Q17 c Qs d Q19 Q20
Q21 b Q22 b Q23 Q24
Q25 b Q26 d Q27 Q28
Q29 d Q30 <

Qoo

TECHNICAL PUBLICATIONS™ - An up thrust for knowledge.

You might also like