VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 1
UNIT-II Data types: Introduction, primitive, character, user defined, array, associative, record, union,
Pointer and reference types, design and implementation uses related to these types. Names,
Variable, concept of binding, type checking, strong typing, type compatibility, named constants,
variable initialization. Sequence control with Expressions, Conditional Statements, Loops, Exception
handling
Data Types
A data type defines a collection of data values and a set of predefined operations on those values.
Types provide implicit context. Compilers can infer information, so programmers write less code.
e.g., the expression a+b in Java may be adding two integer, two floats or two strings depending on
context.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
System.out.println(2+2);
System.out.println(2.5+2.4);
System.out.println("Wel"+"Come");
}
}
Types provide a set of semantically valid operation. Compilers can detect semantic mistakes.
e.g., Python’s list support append () and pop (), but complex numbers do not.
>>> a = [10,20,30,40,50]
>>> a
[10, 20, 30, 40, 50]
>>>a.count(10)
1
list.append(X), list.insert(index,X), list.remove(X), list.count(X), list.sort(X)
list.pop(), list.reverse()
Design Issues for all Data Types
How is the domain of values specified?
What operations are defined and how are they specified?
What is the syntax of references to variables?
Typical primitives include: Boolean, Character, Integral Type, Fixed point type, Floating point type.
C
C++
Java
C#
Python
js
Int
2 Bytes
2 Bytes
4 Butes
Float
Char
1 Byte
1 Byte
2 Bytes
2 Bytes
complex
String
date/time
Enum
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 2
In computer programming, data types can be divided into two categories: value types and reference
types. A value of value type is the actual value. A value of reference type is a reference to another
value.
C++
Value type - booleans, characters, integer numbers, floating-point numbers, arrays, classes
(including strings, lists, dictionaries, sets, stacks, queues), enumerations
Reference type - alias, pointers
Java
Value type - booleans, characters, integer numbers, floating-point numbers
Reference type - arrays, classes (including immutable strings, lists, dictionaries, sets, stacks,
queues, enumerations), interfaces, null pointer
C#
Value type - structures (including booleans, characters, integer numbers, floating-point
numbers, fixed-point numbers, lists, dictionaries, sets, stacks, queues, optionals),
enumerations
Reference type - classes (including immutable strings, arrays, tuples, lists, dictionaries, sets,
stacks, queues), interfaces, pointers
Python
Reference type - classes (including immutable booleans, immutable integer numbers,
immutable floating-point numbers, immutable complex numbers, immutable strings, byte
strings, immutable byte strings, immutable tuples, immutable ranges, immutable memory
views, lists, dictionaries, sets, immutable sets, null pointer)
JavaScript
Reference type - immutable booleans, immutable floating-point numbers, immutable
symbols, immutable strings, undefined, prototypes (including lists, null pointer)
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 3
Primitive Data Types
Have a very simple nature either a number, a character or a truth-value
They are the most basic building blocks for any programming language and are the base
for more complex data types.
Almost all programming languages provide a set of primitive data types
Their representation is very efficient (both in terms of memory and CPU time), as they map
to small byte groups that are directly manipulatable by the CPU.
Primitive Data Types: Integer
The most common primitive numeric data type is integer.
Many computers support several sizes of integers: For example, Java allows these: byte
(1byte), short (2byte), int(4byte), long(8byte).
An integer is represented by a string of bits, with the leftmost representing the sign bit.
Primitive Data Types: Floating point
Floating point data types model real numbers, but the representations are only
approximations for most real values.
Floating-point values are represented as fractions and exponents
Most new computers use the standard IEEE format
Most languages use float and double as floating-point types
The float is stored in 4 bytes of memory
The double has twice as big of storage.
IEEE Floating Point Standard 754
Sign bit
Precision - The accuracy of the fractional part of a value, measured as the number of bits
Range a combination of the range of fractions and the range of exponents.
Primitive Data Types: Complex
Represented as an ordered pair of floating numbers
Python specifies the imaginary part by following it with a j or J(7 + 3j)
Languages that support a complex type include operations for arithmetic on complex values
>>>complex()
0j
>>>complex(1)
(1+0j)
>>>complex(1,2)
(1+2j)
>>> complex (1+2j)
(1+2j)
Primitive Data Types: Boolean
Simplest of all
Range of values: two elements, one for “true” and one for “false”
Could be implemented as bits, but often as bytes.
Advantage: readability (compared with using integers to represent switches/flags)
Primitive Data Types: Character
Stored as numeric coding
Most commonly used coding: ASCII
An alternative, 16-bit coding: Unicode
Includes characters from most natural languages,Originally used in Java
C# and JavaScript also support Unicode
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 4
public class Main
{
public static void main(String[] args) {
Boolean one = false;
System.out.println("one :" + one);
short s = 10000;
System.out.println("s :" + s);
int a = 100000;
System.out.println("a :" + a);
long l = 100000L;
System.out.println("l :" + l);
float f1 = 234.5f;
System.out.println("f1 :" + f1);
double d1 = 12.3;
System.out.println("d1 :" + d1);
char letterA = 'A';
System.out.println("letterA :" + letterA);
}
Non-Primitive Data Types: String, Array, Enum, Record, Unions
Note: In Java, Non-primitive data type refers to an object.
CHARACTER STRING TYPES
A character string type is one in which the values consist of sequences of characters.
Design Issues- -
o Is it a primitive type or just a special kind of array?
o Is the length of objects fixed or variable?
String data type is not supported in C Programming. In java, String isn't a primitive
datatype - it's a class, a reference type.
Operations- - Assignment - Comparison (=, > etc) - Concatenation - Substring reference - Pattern
matching.
Whenever it encounters a string literal in code, the compiler creates a String object.
o In Java: String greeting = "Hello world!";
o Object is with value in this case, "Hello world!'.
Exp1:
public class Main
{
public static void main(String[] args) {
char s1[] = {'h','e','l','l','o'};
String s2 = "hello";
System.out.println(s1);
System.out.println(s2);
//Error ->System.out.println(s1+s1);
System.out.println(s2+s2);
String s3 = new String(s1);
System.out.println(s3+s3);
}
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 5
In Java, the String class is immutable, so that once it is created a String object cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters, then you
should use String Buffer & String Builder.
Exp2:
public class Main
{
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Welcome");
s1.append(" OIST");
System.out.println(s1);
}
}
In Java, the String class support following methods:
o char charAt(int index)
Returns the character at the specified index.
o int compareTo(Object o)
Compares this String to another Object.
o int compareTo(String anotherString)
Compares two strings lexicographically.
o String concat(String str)
Concatenates the specified string to the end of this string.
o booleanequals(Object anObject)
Compares this string to the specified object.
o int length()
Returns the length of this string.
o String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
o char[] toCharArray()
Converts this string to a new character array.
o String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the
default locale.
o String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the
default locale.
o String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Exp3:
o public class Main
o {
o public static void main(String[] args) {
o System.out.println("Vivek".length());
o System.out.println("Vivek".toUpperCase());
o System.out.println("VIVEK".toLowerCase());
o System.out.println("Vivek".concat(" Dubey"));
o System.out.println("Vivek".compareTo("Vivek"));
o System.out.println("Vivek".charAt(2));
o System.out.println(" ABC ".trim() );
o }
o }
5
VIVEK
vivek
Vivek Dubey
0
V
ABC
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 6
Array Types
An array is an aggregate of homogeneous data elements in which an individual element is
identified by its position in the aggregate, relative to the first element.
Array Design Issues
What types are legal for subscripts?
Are subscripting expressions in element references range checked?
When are subscript ranges bound?
When does allocation take place?
What is the maximum number of subscripts?
Can array objects be initialized?
Are any kinds of slices allowed?
How to declare an array?
dataType[] arrayName;
dataType can be a primitive data type like: int, char, Double, byte etc. or an object
arrayName is an identifier.
Exp: int[] age;
How can allocate memory for array elements
Exp: age = new int[5];
Note: int[] age = new int[5];
Java Array Index
The default initial value of elements of an array is 0 for numeric types and false for Boolean
public class Main
{ public static void main(String[] args) {
int[] age = new int[5];
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
}
}
There is a better way to access elements of an array by using looping construct.
public class Main
{ public static void main(String[] args) {
int[] age = new int[5];
for (int i = 0; i< 5; ++i) System.out.println(age[i]);
}
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 7
How to initialize arrays in Java?
In Java, you can initialize arrays during declaration or you can initialize (or change values) later in the
program as per your requirement.
int[] age = {12, 4, 5, 2, 5};
public class Main
{
public static void main(String[] args) {
int[] age = {12, 4, 5, 2, 5};
for (int i = 0; i< 5; ++i)
System.out.println("Element at index " + i +": " + age[i]);
}
}
Exp: computes sum and average of values stored in an array of type int.
public class Main
{ public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int sum = 0;
Double average;
for (int number: numbers) {
sum += number;
}
int arrayLength = numbers.length;
// Change sum and arrayLength to double as average is in double
average = ((double)sum / (double)arrayLength);
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
}
}
Multidimensional Arrays
public class Main
{ public static void main(String[] args) {
int[][] numbers = {{1,2,3},{4,5,6},{7,8,9}};
int i,j;
for(i=0;i<=2;i++){
for(j=0;j<=2;j++)
System.out.print(numbers[i][j]+" ");
System.out.println("");}
}
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 8
Associative arrays in C++
Associative arrays are also called map or dictionaries. In C++. These are special kind of arrays,
where indexing can be numeric or any other data type
i.e can be numeric 0, 1, 2, 3.. OR character a, b, c, d… OR string geek, computers…
These indexes are referred as keys and data stored at that position is called
value. So in associative array we have (key, value) pair.
We use Standard Template Library (STL) maps to implement the concept of associative arrays in
C++.
Example:
Now we have to print the marks of computer geeks whose names and marks are
as follows
Name Marks
Ram 100
Ajay 91
Suraj 99
Manoj 78
Vijay 84
#include <bits/stdc++.h>
using namespace std;
int main()
{
// the first data type i.e string represents
// the type of key we want the second data type
// i.e int represents the type of values we
// want to store at that location
map<string, int>marks{
{ "Ram", 78 },
{ "Ajay", 91 },
{ "Suraj", 100 },
{ "Manoj", 99 },
{ "Vijay", 84 }
};
map<string, int>::iterator i;
cout<< "The marks of all students are" <<endl;
for (i = marks.begin(); i != marks.end(); i++)
cout<<i->first <<” <<i->second<<"\n";
cout<<endl;
// the marks of the students based on there names.
cout<< marks["Ram"] <<endl;
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 9
Associative arrays
For Example:
The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you
identify things by their position.
o For example, in Python
SAtt = { 78, 89,98}
Branch = {“CE”, “EC”, “CSE”}
An associative array, map, symbol table, or dictionary is an abstract data type composed of a
collection of (key, value) pairs, such that each possible key appears at most once in the
collection.
o For example, in Python
SAtt_Branch= { CE: 67, “EC”: 78, “CSE” : 98}
It is also called as or Hashes, or Dictionaries, or even unordered lists.
Operations associated with this data type allow:
the addition of a pair to the collection
the removal of a pair from the collection
the modification of an existing pair
the lookup of a value associated with a particular key
In php,
<?php
$student = array("CSE"=>"98", "EC"=>"78", "CE"=>"67");
foreach($student as $x => $x_value) {
echo "Key=" . $x .", Value=" . $x_value;
echo "\n";
}
?>
0
78
1
89
2
98
CE
78
EC
89
CSE
98
EX
89
IT
78
ME
121
AU
22
BS
220
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 10
User defined Ordinal Type
1. An ordinal data type is a data type with the property that its values can be counted. That is,
the values can be put in a one-to-one correspondence with the positive integers.
2. There are two kinds of ordinal types: enumeration and subrange.
3. Enumeration type:
4. in C/C++
associate nonnegative integer 0, 1,2, ......
#include<iostream>
using namespace std;
int main()
{
enumDayOfWeek{ SUN, MON, TUE, WED, THU, FRI, SAT };
DayOfWeek today = WEDNESDAY;
cout<<today<<endl;
for (int today=SUN; today<=SAT; today++)
cout<<today;
return 0;
}
5. In Python
>>>my_list = ['one', 'Two' ,'Three']
>>> for c, value in enumerate(my_list, 1):
print(c, value)
1 one
2 Two
3 Three
6. Subrange type:
Set up the type to support range checking.
Contiguous subsequence of an ordinal type.
It is for readability and writability.
For Example, in Pascal
type
day = (mon, tue, wed, thu, fri, sat, sun);
workday = mon..fri;
weekend = sat..sun;
letter = 'A'..'Z';
For Example, in Python
>>>a=[1,2,3,4,5,6,7,8]
>>>a[1:4]The 1 means to start at second element in the list (note that the slicing
index starts at 0). The 4 means to end at the fifth element in the list, but not
include it.
[2, 3, 4]
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 11
Structure/ Record Type
In computer science, a record (also called a structure, struct, or compound data) is
a basic data structure. ... A record is a collection of fields, possibly of different data
types, typically in fixed number and sequence.
For ExP: information about a person: his/her name, citizenship number and salary.
You can easily create different variables name, citNo, salary to store this
information separately.
o #include <iostream>
o using namespace std;
o
o struct Person
o {
o char name[50];
o int age;
o float salary;
o };
o
o int main()
o {
o Person p1;
o
o cout<< "Enter Full name: ";
o cin.get(p1.name, 50);
o cout<< "Enter age: ";
o cin>> p1.age;
o cout<< "Enter salary: ";
o cin>> p1.salary;
o
o cout<< "\nDisplaying Information." <<endl;
o cout<< "Name: " << p1.name <<endl;
o cout<<"Age: " << p1.age <<endl;
o cout<< "Salary: " << p1.salary;
o
o return 0;
o }
Difference between C structures and C++ structures
Member functions inside structure: Structures in C cannot have member
functions inside structure but Structures in C++ can have member functions
along with data members.
Direct Initialization: We cannot directly initialize structure data members in C but we
can do it in C++.
Static Members: C structures cannot have static members but is allowed in C++.
Constructor creation in structure: Structures in C cannot have constructor inside
structure but Structures in C++ can have Constructor creation.
Data Hiding: C structures do not allow concept of Data hiding but is permitted
in C++ as C++ is an object oriented language whereas C is not.
Access Modifiers: C structures do not have access modifiers as these
modifiers are not supported by the language. C++ structures can have this
concept as it is inbuilt in the language.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 12
Union Type
Both structure and union are collection of different datatype. They are used to group number of
variables of different type in a single unit.
Difference between Structure and union.
1. Declaration and Initialization of structure starts with struct keyword. Declaration and Initialization
of union starts with union keyword.
2. Structure allocates different memory locations for all its members while union allocates common
memory location for all its members. The memory occupied by a union will be large enough to hold
the largest member of the union.
#include<iostream.h>
struct stud1
{
int RollNo;
char Name[30];
float Marks;
};
Union stud2
{
int RollNo;
char Name[30];
float Marks;
};
void main()
{
stud1 st1;
stud2 st2;
cout<< “Structure Memory :”<<sizeof(st1);
cout<<”Union Memory :”<<sizeof(st2);
cin>>st1.RollNO; cout<<st1.RollNo;
cin>>st1.Name; cout<<st1.Name;
cin>>st1.Marks; cout<<st1.Marks;
cin>>st2.RollNO; cout<<st2.RollNo;
cin>>st2.Name; cout<<st2.Name;
cin>>st2.Marks; cout<<st2.Marks;
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 13
class type
It is a user defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class., known as object.
A class is like a blueprint for an object.
When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
Syntax of class
Example:
#include<iostream.h>
class stud
{ private:
int RollNo; char Name[30]; float Marks;
public:
void ReadData()
{
cin>>RollNO; cin>>Name; cin>>Marks;
}
void WriteData()
{
cout<<RollNo; cout<<Name; cout<<Marks;
}
};
void main()
{
stud st1;
st1.ReadData();
` st1.WriteData();
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 14
A) Class
1. A class in C++ can be defined as a collection of related variables and functions
encapsulated in a single structure.
2. A class in C++ is just an extension of a structure used in the C language. It is a
user defined data type. It actually binds the data and its related functions in
one unit.
3. Keyword for the declaration: Class
4. Default access specifier: Private
5. Purpose: Data abstraction and further inheritance
6. Type: Reference
7. Usage: Generally used for large amounts of data.
8. Its object is created on the heap memory.
9. The member variable of class can be initialized directly.
10. It can have all the types of constructor and destructor.
B) Structure
1. A structure in C++ can be referred to as an user defined data type possessing its
own operations.
2. A structure and a class in C language differs a lot as a structure has limited
functionality and features as compared to a class.
3. Keyword for the declaration: Struct
4. Default access specifier: Public
5. Purpose: Generally, grouping of data
6. Type: Value
7. Usage: Generally used for smaller amounts of data.
8. Its object is created on the stack memory.
9. The member variable of structure cannot be initialized directly.
10. It can have only parameterized constructor.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 15
Interface type
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.
A class implements an interface, thereby inheriting the abstract methods of the interface.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.
An interface is similar to a class in the following ways −
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
However, an interface is different from a class in several ways, including −
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
Interfaces have the following properties −
An interface is implicitly abstract. You do not need to use the abstract keyword while declaring
an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly public.
Syntax for Declaring Interface
o interface {
o //methods
o }
Example
o interface printable{
o void print();
o }
o class A6 implements printable{
o public void print(){System.out.println("Hello");}
o
o public static void main(String args[]){
o A6 obj = new A6();
o obj.print();
o }
o }
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 16
Pointers and Reference Types
Pointers and references are essentially variables that hold memory addresses as their values.
A pointer is declared as:
<Pointer type> *<pointer-name>
In the above declaration:
Pointer-type: It specifies the type of pointer. It can be int, char, float etc. This type
specifies the type of variable whose address this pointer can store.
Pointer-name: It can be any name specified by the user.
int x = 1, y = 2;
int *ip;
ip = &x;
A reference is treated *exactly* as if we had used the original variable in its place.
For example,
int x = 5;
int &y = x; // y is an alias for x
y = 6; // now x == 6
Names
Names are also associated with labels, subprograms, formal parameters and other program
constructs.
Name Forms
A name is a string of characters used to identify some entity in a program. The earliest
programming languages used single character names.
FORTRAN1 broke this tradition by allowing names up to 6 characters long. FORTRAN90 and C
allow up to 31 characters names. ADA has no length limit.
We can use some connecter characters like underscore (_) in the string. Some languages like
C, C++, a Java are case sensitive. That is, these languages differentiate between uppercase
and lowercase letters. Ex- SUN, Sun and sun are distinct in C++.
Special Word
Special words in programming languages are used to make programs more readable by
naming actions to be performed.
Keywords have a special meaning in a language, and are part of the syntax.
Reserved words are words that cannot be used as identifiers (variables, functions, etc.),
because they are reserved by the language. ... In Java, goto is a reserved word but not a
keyword.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 17
In C Language, there are 32 Keywords:
o auto double int struct
o break else long switch
o case enum register typedef
o char extern return union
o continue for signed void
o do if static while
o default goto sizeof volatile
o const float short unsigned
In C++ Language, there are 60 Keywords:
asm
auto
bool
break
case
catch
char
class
const_cast
continue
default
delete
do
Double
else
enum
dynamic_cast
extern
False
float
for
union
unsigned
Using
friend
goto
if
inline
Int
long
mutable
virtual
namespace
new
operator
private
protected
public
register
void
reinterpret_cast
return
short
signed
sizeof
static
static_cast
volatile
Struct
switch
template
this
throw
true
try
typedef
typeid
unsigned
wchar_t
while
In Java Language, there are 57 Keywords, Of these 57 keywords, 55 are in use and 2 are not
in use.
o abstract assert Boolean break byte
o case catch char class continue
o default do double else enum
o extends exports final finally float
o for if implements import instanceof
o int interface long module native
o new package private protected public
o requires return short static strictfp
o super switch synchronized this throw
o throws transient try void volatile
o while
Reserved words for literal values: true, false, null
Special identifiers: var
Unused: const, goto
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 18
VARIABLES
o A variable is a symbolic name for (or reference to) information. The variable's name represents
what information the variable contains.
o They are called variables because the represented information can change but the operations on
the variable remain the same.
o In general, a program should be written with "Symbolic" notation, such that a statement is
always true symbolically.
o For example, if we want to find the sum of any two numbers we can write: result = a + b;
o Both 'a' and 'b' are variables. They are symbolic representations of any numbers.
o For example, the variable 'a' could contain the number 5 and the variable 'b' could contain the
number 10. During execution of the program, the statement "a + b" is replaced by the Actual
Values "5 + 10" and the result becomes 15.
Variable Properties
There are 6 properties associated with a variable.
1. A Name
2. A Type
3. A Value
4. A Scope
5. A Life Time
6. A Location (in Memory)
Properties
1. A Name
o The name is Symbolic. It represents the "title" of the information that is being stored with
the variable.
o The name is perhaps the most important property to the programmer, because this is how
we "access" the variable. Every variable must have a unique name!
2. A Type
o The type represents what "kind" of data is stored with the variable.
o In C, Java etc, the type of a variable must be explicitly declared when the name is created.
3. A Value
o A variable, by its very name, changes over time. Thus if the variable is jims_age and is
assigned the value 21. At another point, jims_age may be assigned the value 27.
o Default Values
o Most of the time, when we "create a variable" w are primarily defining the variables
name and type. Often we will want to provide an initial value to be associated with
that variable name. If you forget to assign an initial value, then various rules "kick in"
depending on the language.
Example: age = 20; //this creates a variable named age with the value 20
4. A Scope
Good programs are "Chopped" into small self contained sections (called functions). A
variable that is seen and used in one function is NOT available in another section. This allows
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 19
us to reuse variable names, such as age. In one function 'age' could refer to the age of a
student, and in another function 'age' could refer to the vintage of a fine wine.
Further this prevents us from "accidentally" changing information that is important to
another part of our program.
5. A Life Time
The life time of a variable is strongly related to the scope of the variable. When a program
begins, variables "come to life" when the program reaches the line of code where they are
"declared". Variables "die" when the program leaves the "Scope" of the variable.
6. A Location (in Memory)
Generally we don't have to worry too much about where in the computer hardware the
variable is stored. The computer does this for us. But we should be aware that a "Bucket" or
"Envelope" exists in the hardware for every variable we declare. In the case of an array, a
"bunch of buckets" exist. Every bucket can contain a single value.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 20
Binding
1. A binding is an association, such as between an attribute and an entity, or between an operation
and a symbol. Binding time is the time at which a binding takes place.
2. For example, in C the binding time for a variable type is when the program is compiled (because
the type cannot be changed without changing and recompiling the program), but the value of
the variable is not bound until the program executes (that is, the value of the variable can
change during execution).
Some additional examples of attributes are:
the meaning of a keyword such as if
the operation associated with a symbol such as +
the entity (variable, keyword, etc.) represented by an identifier
the memory location for the value of an identifier
The most common binding times for attributes are (in chronological order):
1. Language definition
2. Language implementation
3. Program translation (compile time)
4. Link edit
5. Load
6. Program execution (run time)
Classes of Binding Times
Execution Time (Run time)
o This includes binding performed during program execution. Ex- Binding of variables to
their values as well as bindings of variables to particular storage locations.
Translation Time (Compile Time)-
o Binding chosen by the programmer
While writing a program, a programmer gives choice for variable names, types
for variables, program statement structures and so on that represents binding
during translation.
o Binding chosen by the translator
Some bindings are chosen by translator. Ex- The relative location of a data
object in the storage allocated for a procedure, how arrays are stored, how
descriptors for the arrays, if any are created all such decisions are made by the
language translator.
o Binding chosen by the Loader
A program usually consists of several subprograms that must be merged into a
single executable program. The translator binds variables to addresses within
the storage designated for each subprogram.
Language Implementation Time
o Some aspects of a language definition may vary between implementations. For Ex- The
details associated with the representation of numbers and arithmetic operation may be
determined by the underlying computer hardware.
Language Definition Time
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 21
o Most of the structure of programming language is fixed at language definition time. Ex-
Different data types, data structure types, control elements, program structure and so
on are all fixed at language definition time.
Types of Binding
o A binding is static if it first occurs before run time and remains unchanged throughout program
execution. A binding is dynamic if it first occurs during execution or can change during execution
of the program.
o Static Type Binding
If static, the type may be specified by either an explicit or an implicit declaration.
Variable Declarations
An explicit declaration is a program statement used for declaring the types of
variables.
An implicit declaration is a default mechanism for specifying types of variables
(the first appearance of the variable in the program.)
Both explicit and implicit declarations create static bindings to types.
FORTRAN, PL/I, BASIC, and Perl provide implicit declarations.
EX: In FORTRAN, an identifier that appears in a program that is not explicitly
declared is implicitly declared according to the following convention: I, J, K, L,
M, or N or their lowercase versions is implicitly declared to be Integer type;
otherwise, it is implicitly declared as Real type.
o Dynamic Type Binding (JavaScript and PHP)
Specified through an assignment statement
Ex, JavaScript
list = [2, 4.33, 6, 8]; ->single-dimensioned array
list = 47; -> scalar variable
Advantage: flexibility (generic program units)
Disadvantages: High cost (dynamic type checking and interpretation
Dynamic type bindings must be implemented using pure interpreter not compilers.
Pure interpretation typically takes at least ten times as long as to execute equivalent
machine code.
o Type error detection by the compiler is difficult because any variable can be
assigned a value of any type.
Incorrect types of right sides of assignments are not detected as errors; rather, the type
of the left side is simply changed to the incorrect type.
Ex:
o i, x -> Integer
o y ->floating-point array
o i = x ->what the user meant to type
o i = y -> what the user typed instead
No error is detected by the compiler or run-time system.
o i is simply changed to a floatingpoint array type.
o Hence, the result is wrong.
In a static type binding language, the compiler would detect the error and the program
would not get to execution.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 22
TYPE CHECKING
Type systems are the biggest point of variation across programming languages. Even languages
that look similar are often greatly different when it comes to their type systems.
Definition: A type system is a set of types and type constructors (integers, arrays, classes, etc.)
along with the rules that govern whether or not a program is legal with respect to types (i.e.,
type checking).
For example, C++ and Java have similar syntax and the control structures. They even have a
similar set of types (classes, arrays, etc.). However, they differ greatly with respect to the rules
that determine whether or not a program is legal with respect to types.
As an example, one can do this in C++ but not in Java:
o int x = (int) “Hello”;
In other words, Java’s type rules do not allow the above statement but C++’s type rules do allow it.
Why do different languages use different type systems?
o The reason for this is that there is no one perfect type system.
o Each type system has its strengths and weaknesses.
o Thus, different languages use different type systems because they have different
priorities.
o A language designed for writing operating systems is not appropriate for programming
the web; thus they will use different type systems.
o When designing a type system for a language, the language designer needs to balance
the tradeoffs between execution efficiency, expressiveness, safety, simplicity, etc.
o In other words, the type system affects many of the characteristics.
o Thus, a good understanding of type systems is crucial for understanding how to best
exploit programming languages.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 23
Type Conversion
Implicit Type Conversion Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Generally, takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with largest data
type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
Exp:
voidmain()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout<< "x = " << x <<endl<< "y = " << y <<endl<< "z = " << z <<endl;
}
Output: x=107 y=a z=108
Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user
can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front of
the expression in parenthesis. This can be also considered as forceful casting.
Syntax:(type) expression
Exp:
1. // Explicit conversion from int to float
2. floatResult = 3 / (float)2;
3. cout<< "Result = " <<Result; // 1.5
Conversion using Cast operator: A Cast operator is an unary operatorwhich forces one data
type to be converted into another data type.
C++ supports four types of casting:
o Static Cast
o Dynamic Cast
o Const Cast
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 24
o Reinterpret Cast
static_cast:
It can be used for any normal conversion between types, conversions that rely on static
(compile-time) type information.static_cast performs no run-time checks and hence no
runtime overhead.
Exp:
int a = 5, b = 2;
double result = static_cast<double>(a) / b;
dynamic_cast:
It can only be used with pointers and references to objects. It's almost exclusively used for
handling polymorphism. It makes sure that the result of the type conversion is valid and
complete object of the requested class.
Exp:
class Base { };
class Derived : public Base { };
Base a, *ptr_a;
Derived b, *ptr_b;
ptr_a = dynamic_cast<Base *>(&b); // Fine
ptr_b = dynamic_cast<Derived *>(&a); // Fail
The first dynamic_cast statement will work because we cast from derived class to base. The
second dynamic_cast statement will produce a compilation error because base class to
derived conversion is not allowed with dynamic_cast unless the base class is polymorphic (a
polymorphic type has at least one virtual function, declared or inherited).
reinterpret_cast
It is used to convert one pointer of another pointer of any type, no matter either the class is
related to each other or not.
It does not check if the pointer type and data pointed by the pointer is same or not.
Syntax :
data_type *var_name =
reinterpret_cast<data_type *>(pointer_variable);
Return Type: It doesn’t have any return type. It simply converts the pointer type
Exp:
#include <iostream>
using namespace std;
intmain()
{
int* p = new int(65);
char* ch = reinterpret_cast<char*>(p);
cout<< *p <<endl;
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 25
cout<< *ch<<endl;
return 0}
const_cast is considered safer than simple type casting. It’safer in the sense that the
casting won’t happen if the type of cast is not same as original object. For example, the
following program fails in compilation because ‘int *’ is being typecasted to ‘char *’
#include <iostream>
using namespace std;
int main(void)
{
int a1 = 40;
const int* b1 = &a1;
char* c1 = const_cast<char *> (b1); // compiler error
*c1 = 'A';
return 0;
}
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 26
Type Casting
Typecasting is making a variable of one type, such as an int, act like another type, a char, for one
single operation.
To typecast something, simply put the type of variable you want the actual variable to act as
inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.
Used when the programmer wants to explicitly convert one data type to another. It shows the
programmer's intention as being very clear.
i = 5.2 / f; // warning "loss of precision"
i = int(5.2 / f) // no warning but still loss
f = float(3 * i)
TYPE COMPATIBILITY
Compatible Types: A compatible type is one that is either legal for the operator, or is allowed
under language rules to be implicitly converted, by compiler-generated code, to a legal type.
Type compatibility is also called conformance or equivalence.
There are two type compatibility methods:
Name compatibility (also called strict compatibility):
o Two variables can have compatible types only if they are in either the same declaration
or in declarations that use the same type name.
o It is highly restrictive.
o It is easier to implement.
o Ada uses name compatibility.
Structure type compatibility
o Two variables have compatible types if their types have identical structures.
o It is more flexible.
o It is difficult to implement: compare the whole structure instead of just names.
o Two types are structurally compatible if:
o T1 is name compatible with T2; or
o T1 and T2 are defined by applying the same type constructor to structurally compatible
corresponding type components.
Examples:
Two records or structure types compatible if they have same structure but
different field names?
Two single-dimensioned array types in a Pascal or Ada program are compatible if
they have the same element type but have different subscript ranges?
C uses structural compatibility except for structures.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 27
Named Constants
o A named constant is a variable that is bound to a value only at the time it is bound to a value
only at the time it is bound to storage; its value cannot be changed by assignment or by an input
statement.
o Const int Max =30;
o Here Max is a constant of type integer with value30.
o Advantages:-
o It improves program readability and reliability. For Ex- using the name ‘Pi’ in the
program is more readable than using the value 3.14. Another advantage of named
constant is in the program that process a fixed number of data values say 10. Such
programs usually use the constant 10 in number of statements like for declaring array
subscript ranges, for loop control limits and other uses.
o Ex-
o void main()
o {
o const int limit=10;
o int A[limit], B[limit], C[limit];
o cout<<”enter array A elements”;
o for (i=0; i<limit; i++)
o { cin>>A[i];
o }
o cout<<”enter array B elements”;
o for (i=0; i<limit; i++)
o { cin>>B[i];
o }
o for (i=0; i<limit; i++)
o { C[i]= A[i]+B[i];
o }
o cout<<”the addition of array A and B elements”;
o for (i=0;i<limit;i++)
o { cout<<C[i];
o }
o }
o The advantage of using named constant ‘limit’ is that when the array limit needs to be changed
say from 10 to 100, then only one line is required to be changed, regardless the number of times
it is used in the program.
Variable Initialization
o The binding of a variable to a value at the time it is bound to storage is called variable
initialization.
o If the variable is bound to storage statically binding and initialization occur before runtime.
o If storage binding is dynamic, initialization is also dynamic.
o Ex- int fact =1;
o Here the variable ‘fact’ is initialized with the value 1 statically.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 28
Conditional Statements
o A conditional statement is one which makes the computer compare two or more variables in
some way and decide that the outcome is either 'true' or 'false', and then feeds this into a
function such as 'if' or 'while'.
The If statement
If the condition expression evaluates to true, the statement is ignored.
Syntax if(condition)
Statement;
Ex; - if (A < B)
{ printf (“A is smaller element”); }
If..else Statement
It is used to test the condition that has true and false part.
Syntax: - if (condition)
Statement1;
else
Statement2;
Ex- if (A < B){ printf (“A is smaller element”); }
else {printf “B is smaller element”); }
Switch Statement
o A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch
case.
o Syntax:
o The syntax for a switch statement in C programming language is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 29
}
The?: operator
It is shorthand method for specifying
(If expression)? (Evaluate if true): (else evaluate this)
This reduces the readability of program. This does not in any way speed up execution time.
LOOPS
o Loop statements are used to perform some action repeatedly. Different types of loop control
statement used in C language are-
1) While statement The while statement is used to carry out looping operations in which a group
of statements is executed repeatedly until some condition has been satisfied.
while (expression)
{
Statement
}
Ex- To print numbers between 1 to 100 using while
#include<stdio.h> void main() { int i=1; while (i<=100) { printf(\n %d”,i); i++; }
2) The do while statement- When a loop is constructed using the while statement the test for
continuation of the loop is carried out at the beginning of each pass. Sometime it is desirable to have
a loop with the test for continuation at the end of each pass.
do
{
Statement
} while (expression);
The statement will be executed repeatedly, till the value of the expression is true.
Ex- void main() { Int i=1; do { printf( “%d”, i); I++; } while (i<=100);
3) The for statement
The for statement is the most commonly used looping statement in C
for (expression1; expression2; expression3)
Statement;
SEQUENCE CONTROL
o Control Structure in a PL provides the basic framework within which operations and data are
combined into a program and sets of programs.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 30
Sequence Control-> Control of the order of execution of the operations
Data Control-> Control of transmission of data among subprograms of program
Sequence Control may be categorized into four groups:
1) Expressions
o They form the building blocks for statements. An expression is a combination of variable
constants and operators according to syntax of language. Properties as precedence rules and
parentheses determine how expressions are evaluated
2) Statements
o The statements (conditional & iterative) determine how control flows from one part of program
to another.
3) Declarative Programming
o This is an execution model of program which is independent of the program statements. Logic
programming model of PROLOG.
4) Subprograms
o In structured programming, program is divided into small sections and each section is called
subprogram. Subprogram calls and co-routines, can be invoked repeatedly and transfer control
from one part of program to another.
IMPLICITAND EXPLICIT SEQUENCE CONTROL
Implicit Sequence Control
o Implicit or default sequence control structures are those defined by the programming language
itself. These structures can be modified explicitly by the programmer.
eg. Most languages define physical sequence as the sequence in which statements are executed.
Explicit Sequence Control
o Explicit sequence control structures are those that programmer may optionally use to modify
the implicit sequence of operations defined by the language.
eg. Use parentheses within expressions, or goto statements and labels
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 31
Sequence Control within Expressions
o Expression is a formula which uses operators and operands to give the output value.
i) Arithmetic Expression
o An expression consisting of numerical values (any number, variable or function call) together
with some arithmetic operator is called “Arithmetic Expression”.
Evaluation of Arithmetic Expression
o Arithmetic Expressions are evaluated from left to right and using the rules of precedence
of operators. If expression involves parentheses, the expression inside parentheses is
evaluated first.
ii) Relational Expressions
o An expression involving a relational operator is known as “Relational Expression”. A relational
expression can be defined as a meaningful combination of operands and relational operators.
(a + b) > c c< b
Evaluation of Relational Expression
o The relational operators <, >, <=, >= are given the first priority and other operators (==
and ! =) are given the second priority. The arithmetic operators have higher priority
over relational operators. The resulting expression will be of integer type, true = 1, false
= 0
iii) Logical Expression
o An expression involving logical operators is called ‘Logical expression”. The expression formed
with two or more relational expression is called logical expression.
Ex. a > b && b < c
Evaluation of Logical Expression
o The result of a logical expression is either true or false. For expression involving AND
(&&), OR (||) and NOT (!) operations, expression involving NOT is evaluated first, then
the expression with AND and finally the expression having OR is evaluated.
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 32
Controlling the evaluation of expressions
a) Precedence (Priority)
If expression involving more than one operator is evaluated, the operator at higher level
of precedence is evaluated first.
b) Associativity
The operators of the same precedence are evaluated either from left to right or from
right to left depending on the level. Most operators are evaluated from left to right
except
VivekDubey
Subject: Principle of Programming Language/eNotes:Unit-2
Computer Science & Engg Dept Page 33
Expression Tree
Syntax for Expressions
Infix notation
Operators are written in-between their operands.
( (A * B) + (C / D) )
Prefix or Polish notation
Operators are written before their operands.
(+ (* A B) (/ C D) )
Postfix or reverse polish
Operators are written after their operands.
( (A B *) (C D /) +)
+
*
/
a
b
c
d