Unit-2
Unit-2
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
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.
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;
Fandarona yoed
« 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();
(oo ]
] [ [ [
[Cintegeai ] [Fioating point | [ Ciass | [Anays | [interface]
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;
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
m Design Issues
The two most important design issues for character string types are -
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
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 -
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];
- 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]
Review Questions
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
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;
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.
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;
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.
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
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.
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.
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 +
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
not. ! not
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;
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);
c=a/b;
In above code, c is float, the values of a and b could be coerced to float before the
division.
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 : 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*
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
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++)
printf(*%d" ali );
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:
end;
- 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
©
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.
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 -
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.
void main ()
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();
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.
[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;
[d]:
Q.13 Choose the correct statement.
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
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
Qoo