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

Lecture 17 & 18

The document discusses user-defined ordinal types in programming languages, covering primitive data types, boolean types, character types, enumeration types, and subrange types. It provides examples from various programming languages like Java, C++, and Python, illustrating how these types are implemented and used. Additionally, it explains the syntax for defining these types and includes code snippets demonstrating their application.

Uploaded by

mmuzammal2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 17 & 18

The document discusses user-defined ordinal types in programming languages, covering primitive data types, boolean types, character types, enumeration types, and subrange types. It provides examples from various programming languages like Java, C++, and Python, illustrating how these types are implemented and used. Additionally, it explains the syntax for defining these types and includes code snippets demonstrating their application.

Uploaded by

mmuzammal2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

COMSATS University Islamabad,

Wah Campus

Lecture No. 17 & 18


User Defined Ordinal Types: Primitive Data Types , Boolean Types , Character Types,
Character String Types, Enumeration Types, Evaluation, Sub-range Types,
Implementation of User-Defined Ordinal Type, Record Types ,Tuple Types ,List Types
Union Types, Pointer and Reference Types, Type Checking , Strong Typing, Type
Equivalence

Theory Of Programming Languages


Fall 2024 1
~~~ Dr. Khalid Iqbal Khattak ~~~
User Defined Ordinal Types

User can define In Java, for example,


two types of An ordinal type is the primitive ordinal
ordinal types one in which the types are integer, char,
range of possible and boolean.
values can be easily
enumeration
associated with the User-defined ordinal
types that have been
set of positive supported by
integers. programming
languages: enumerati
subrange. on & subrange

Languages Perl, JavaScript, PHP, Python, Ruby, and Lua


do not allow enumeration data type.
Theory Of Programming Languages
Fall 2024 2
~~~ Dr. Khalid Iqbal Khattak ~~~
PL Examples (Enumeration)
• C or C++ Language
– enum colors {red, blue, green, yellow, black};
– colors myColor = blue, yourColor = red
• In Java,
• class MyEnum
– {enum colors {red, blue, green, yellow, black}
– public static void main(String args[])
– {colors myColor = colors.blue, yourColor = colors.red;
– System.out.println("My Color is "+myColor.ordinal());
– System.out.println("Your Color is "+yourColor.ordinal()); }

• C# Language
– enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

Theory Of Programming Languages


Fall 2024 3
~~~ Dr. Khalid Iqbal Khattak ~~~
PL Examples (Subrange)
• A subrange type is a contiguous subsequence of an ordinal
type.
– For example, 12.. 14 is a subrange of integer type.
– Subrange types were introduced by Pascal and are included in Ada.
• Syntax
– Syntax for the declaration as a DUT object:
– TYPE <name>: <Inttype> (<ug>..<og>) END_TYPE;
• F#: is a JavaScript and .NET language for web, cloud, data-science, and apps.
– type weekdays = | Monday | Tuesday | Wednesday | Thursday | Friday
• Ada Language
– Subranges are included in the category of types called subtypes.
– type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
– subtype Weekdays is Days range Mon..Fri;

Theory Of Programming Languages


Fall 2024 4
~~~ Dr. Khalid Iqbal Khattak ~~~
Primitive Data Types

Theory Of Programming Languages


Fall 2024 5
~~~ Dr. Khalid Iqbal Khattak ~~~
Primitive Data Types: Examples in PLs
PLs Data Tpes
Python Integers Floating point Characters Booleans
numbers
Java Integers Floating point Characters Booleans
numbers
C# Integers Floating point Characters Booleans
numbers
C++ Integers Floating point Characters Booleans
numbers
JavaScript Integers Floating point Characters Booleans
numbers

JavaScript does not have explicit integer types.


Floating point numbers are used to represent both integers and decimal numbers.
It is important to note that the names and specific features may vary slightly from language to
language.
However, the fundamental idea of primi ve types remains consistent in most languages.
Theory Of Programming Languages
Fall 2024 6
~~~ Dr. Khalid Iqbal Khattak ~~~
Boolean & Character data Types
Java
Boolean Types: It has only two
• Booleanos: boolean - Represents a value of
elements, true and false. Boolean true (true) the fake (false) and is used in
types are often used to represent logical expressions and decision making.
• Characters: char - Stores a single Unicode
switches or flags in programs. character, such as a letter or symbol.

C++
Character Types: It stores a single • Characters: char - Stores a single ASCII or
character and requires a single byte Unicode character.
• Booleanos: bool - Stores a true value (true)
of memory in almost all compilers. the fake (false), similar to Java.

C# Python
• Booleanos: bool - Similar to Java and C++, • Booleanos: bool - Stores a true value (True)
stores a true value (true) the fake (false) the fake (False), used in logical expressions
• Characters: char - Stores a single Unicode and decision making
character. • Characters: str (text string) - Stores a
sequence of characters. Represents a text
string, such as "Hello", "Python", "123".
Theory Of Programming Languages
Fall 2024 7
~~~ Dr. Khalid Iqbal Khattak ~~~
Character String Types
A character string type is one in which the values consist of sequences of
characters

String Length Options

The most common string operations are assignment, concatenation,


substring reference, comparison, and pattern matching.

The length can be static and set when the string is created. Such a string is
called a static length string. e.g. Java, Python.

Limited dynamic length strings are those strings which are allowed to have
varying length up to adeclared and fixed maximum set by the variable’s
definition. e.g. C, C++.

Dynamic length strings are those strings which have varying length with no
maximum. e.g. JavaScript, Perl, and the standard C++ library.
Theory Of Programming Languages
Fall 2024 8
~~~ Dr. Khalid Iqbal Khattak ~~~
Character String Types

Theory Of Programming Languages


Fall 2024 9
~~~ Dr. Khalid Iqbal Khattak ~~~
Enumeration Types
An enumerated type is a data type consisting of a set of named
values called elements, members, enumeral, or enumerators of
the type.
• The enumerator names are usually identifiers that behave as constants in the
language.

An enumeration is a data type that consists of a set of named


values that represent integral constants, known as enumeration
constant.

Enumeration or Enum in C is a special kind of data type defined by


the user.

• It consists of constant integrals or integers that are given names by a user.


• The use of enum in C to name the integer values makes the entire program easy
to learn, understand, and maintain by the same or even different programmer.
Theory Of Programming Languages
Fall 2024 10
~~~ Dr. Khalid Iqbal Khattak ~~~
Enumeration Types
• enum Weekdays = (Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday);

Syntax

Theory Of Programming Languages


Fall 2024 11
~~~ Dr. Khalid Iqbal Khattak ~~~
Enumeration Example

Syntax: enum enumerated-type-name


{value1, value2, value3…..valuen };

Theory Of Programming Languages


Fall 2024 12
~~~ Dr. Khalid Iqbal Khattak ~~~
Subrange Type
. • A subrange type defines a subset of the values of a
particular type.

• Examples:
– type digit=0..9; letter='A'..'Z';
– Var num:digit; alpha:letter
• A subrange type is a data type whose value range only covers
a subset of a base type.
Only integer types are possible as the base type.
• Syntax: <Name> : <Inttype> (<lower bound>..<upper bound>)
<Inttype> Data type of the subrange
(SINT, USINT, INT, UINT, DINT, UDINT, BYTE, WORD, DWORD, LINT, ULINT, LWORD).

<lower Lower bound of the range: Constant that must be compatible with the base data type. The lower bound itself is
bound> included in this range.

<opper Upper bound of the range: Constant that must be compatible with the base data type. The upper bound itself is
bound> included in range.
Theory Of Programming Languages
Fall 2024 13
~~~ Dr. Khalid Iqbal Khattak ~~~
Subrange Type
. • Syntax: <Name> : <Inttype> (<lower bound>..<upper bound>)
<Inttype> Data type of the subrange
(SINT, USINT, INT, UINT, DINT, UDINT, BYTE, WORD, DWORD, LINT, ULINT,
LWORD).
<lower Lower bound of the range: Constant that must be compatible with the base
bound> data type. The lower bound itself is included in this range.
<upper Upper bound of the range: Constant that must be compatible with the base
bound> data type. The upper bound itself is included in range.

DWORD variable
A DWORD is a 32-
• Sample bit unsigned
can hold values in
the range 0 to
– VAR integer
4,294,967,295
nVarA: INT (-4095…4095);
nVarB : UINT (0…10000);
END_VAR

Theory Of Programming Languages


Fall 2024 14
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation

Time Complexity: O(1)


Auxiliary Space: O(1)

Theory Of Programming Languages


Fall 2024 15
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation

Current system time System uptime:


Output (UTC): 2024-11-25 13255468
01:30:45.500 milliseconds

Time Complexity: O(1)


Auxiliary Space: O(1)

Theory Of Programming Languages


Fall 2024 16
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation of User-Defined Ordinal Type
#include <bits/stdc++.h> int main()
#define M 32
using namespace std; {
// Function to add two bitset int number1, number2;
int binAdd(bitset<M> atemp, bitset<M> btemp)
{ // To store the bits of answer number1 = 12;
bitset<M> ctemp; number2 = 34;
for (int i = 0; i < M; i++)
ctemp[i] = 0;
// Initialize carry to 0 // Converting number 1 to bitset form
int carry = 0;
for (int i = 0; i < M; i++) { bitset<M> num1(number1);
// Both bits are zero
if (atemp[i] + btemp[i] == 0) {
if (carry == 0) // Converting number 2 to bitset form
ctemp[i] = 0; bitset<M> num2(number2);
else { ctemp[i] = 1;
carry = 0; } }
// Any of the one bit is 1 cout << binAdd(num1, num2) << endl;
else if (atemp[i] + btemp[i] == 1) {
if (carry == 0) }
ctemp[i] = 1;
else {ctemp[i] = 0; } }
// Both bits are 1
else {if (carry == 0) {
ctemp[i] = 0;
carry = 1; }
else { ctemp[i] = 1;
}} }
// To convert bitset into decimal equivalent
return ctemp.to_ulong(); }
Theory Of Programming Languages
Fall 2024 17
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation of User-Defined Ordinal Type
#include <bits/stdc++.h> int main()
#define M 32
using namespace std; {
// Function to add two bitset
int binAdd(bitset<M> atemp, bitset<M> btemp)
int number1, number2;
{ // To store the bits of answer number1 = 12;
bitset<M> ctemp;
for (int i = 0; i < M; i++) number2 = 34;
ctemp[i] = 0;
// Initialize carry to 0
Approach:
int carry = 0; // Converting number 1 to bitset form
forSince
(int i = we
0; i < M; i++) { if(carry==1)
// Both bits are zero bitset<M> num1(number1);
1+1=0 carry
know that+ btemp[i] ==1+0=1
if (atemp[i] 0) { 0+1=1 0+0=0 1+1=1 carry
1
in(carry
if bit == 0) 1
additionctemp[i] = 0; // Converting number 2 to bitset form
else { ctemp[i] = 1;
carry = 0; } }
bitset<M> num2(number2);
// Any of the one bit is 1
else if (atemp[i] + btemp[i] == 1) {
if (carry == 0) cout << binAdd(num1, num2) << endl;
ctemp[i] = 1;
else {ctemp[i] = 0; } }
}
// Both bits are 1
else {if (carry == 0) {
ctemp[i] = 0;
carry = 1; }
else { ctemp[i] = 1;
}} }
// To convert bitset into decimal equivalent
return ctemp.to_ulong(); }

Theory Of Programming Languages


Fall 2024 18
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation of User-Defined Ordinal Type

#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {
seasons s;
s = autumn;
cout << “autumn= " << s << endl;
return 0;
}
Output

autumn= 9
Theory Of Programming Languages
Fall 2024 19
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation
#include <iostream>
using namespace std; bitwise OR | operator

enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
};
int main()
{
int myDesign = BOLD | UNDERLINE;

// 00000010
// | 00000100
// ___________
// 00000110
Output
cout << myDesign;
return 0;} 6
Theory Of Programming Languages
Fall 2024 20
~~~ Dr. Khalid Iqbal Khattak ~~~
Implementation
C++ Program to find direction using Enumeration

#include <iostream>
using namespace std;

enum direction { North, South, East, West };


int main(){
direction dir;
dir = East;
cout << "Direction: " << dir;
return 0;
}
Output

Direction: 2
Theory Of Programming Languages
Fall 2024 21
~~~ Dr. Khalid Iqbal Khattak ~~~
Record Types

A record is an aggregate of heterogeneous data elements in which


the individual elements are identified by names and accessed
through offsets from the beginning of the structure.

Theory Of Programming Languages


Fall 2024 22
~~~ Dr. Khalid Iqbal Khattak ~~~
Record Types
Syntax

• A record type is a composite data type that


consists of one or more identifiers and their
corresponding data types. CREATE
pkg7a IS
OR REPLACE PACKAGE

• TYPE rectype IS RECORD TYPE t1_typ IS RECORD (

– Specifies an identifier for the c1 T1.C1%TYPE,

record type. c2 VARCHAR(10) );

• field END;

– Specifies an identifier for a field of the record type.


• datatype
– Specifies the corresponding data type of the field.
Theory Of Programming Languages
Fall 2024 23
~~~ Dr. Khalid Iqbal Khattak ~~~
Tuple Types
A tuple is a well-defined group of values of specific types
that can be handled together as a single grouped value,
and also be taken apart into their individual values
easily.
A tuple type is expressed with the tuple of keywords,
followed by a list of two or more types (since a tuple of just
one value makes very little sense).

A record struct definition specifies both the name and type


of each piece of data, allowing you to retrieve the field by
name.
In contrast, tuple struct definitions omit field names; only
specifying the field types.
Theory Of Programming Languages
Fall 2024 24
~~~ Dr. Khalid Iqbal Khattak ~~~
Record vs Tuple Types: Examples

/
/
const user = #{ const address = #{ t
// a const enemies = const friends = #[“Taha",
name: “T.Iqbal", street: "21B Mehr
record
age: 27 } Street", city: ‘Wah'} u #[ “Tom", “Taha"] “Jawad Ahmed"]
p
l
e

Theory Of Programming Languages


Fall 2024 25
~~~ Dr. Khalid Iqbal Khattak ~~~
List Types
The LIST data type is a collection type that can store ordered
non-NULL elements of the same SQL data type.
The LIST data type supports, but does not require, duplicate
element values. The elements of a LIST data type have ordinal
positions

LIST{"blue", "green", "yellow"}

LIST{"yellow", "blue", "green"}

The above list expressions are not equal because the values are not in the
same order.
To be equal, the second statement must be:

LIST{"blue", "green", "yellow"}


Theory Of Programming Languages
Fall 2024 26
~~~ Dr. Khalid Iqbal Khattak ~~~
List Types: Python
Lists are used to store multiple items in a single variable.

mylist = ["apple", "banana", "cherry"]

Output
list1 = ["Taha", "Saif", "Jawad"]
['Taha', 'Saif', 'Jawad']
list2 = [10, 50, 70, 90, 30]
[10, 50, 70, 90, 30]
list3 = [True, False, False]
[True, False, False]
print(list1)

print(list2)

print(list3)

Theory Of Programming Languages


Fall 2024 27
~~~ Dr. Khalid Iqbal Khattak ~~~
union union_name { datatype
field_name; datatype
Union Types field_name; // more variables };
A union is a special data type available in C that allows to store
different data types in the same memory location.
A union can be defined with many members, but only that
contain a value at any given time.
Unions provide an efficient way of using the same memory
location for multiple purpose.
union car
{
char name[50]; This code defines a derived
type union car
int price;
A union is a user-defined type similar to structs in C except for one key difference.
};
Structures allocate enough space to store all their members, whereas
unions can only hold one member value at a time.
Theory Of Programming Languages
Fall 2024 28
~~~ Dr. Khalid Iqbal Khattak ~~~
Difference between unions and structures

Output

after fixing x value the coordinates of t will be 3 3

After fixing y value the coordinates of t will be 4 4

The coordinates of t1 are 1 2

Note : Size of the union is the size of its largest field because sufficient number of bytes must
be reserved to store the largest sized field.
Theory Of Programming Languages
Fall 2024 29
~~~ Dr. Khalid Iqbal Khattak ~~~
Union Types

union variables car1, car2,


and a union pointer car3
of union car type are
In the above examples, created in above
examples.
•To access price for car1, car1.price is used.
•To access price using car3, either (*car3).price or car3->price can be used
Theory Of Programming Languages
Fall 2024 30
~~~ Dr. Khalid Iqbal Khattak ~~~
Difference between unions and structures

size of
size of structure
union = = 40
Output
32

Theory Of Programming Languages


Fall 2024 31
~~~ Dr. Khalid Iqbal Khattak ~~~
Pointer and Reference Types
A pointer type is one in which the variables have a range of values
that consists of memory addresses and a special value, nil.
A reference type variable is similar to a pointer, with one important and
fundamental difference: A pointer refers to an address in memory, while a
reference refers to an object or a value in memory.

Example (C++ )
Example
variables a int * ptr1;
and b are int a = 0;
aliases. b is int * ptr2 = new int[100];
reference to int &b = a;
a. ptr1 = ptr2;

b = 100; delete [] ptr2;


Theory Of Programming Languages
Fall 2024 32
~~~ Dr. Khalid Iqbal Khattak ~~~
Pointer and Reference Types
int a = 10;
int *p = &a;
int i = 3;
// OR
// A pointer to variable i or "stores
int *p;
the address of i"
p = &a;

int *ptr = &i;


int a = 10;

int &p = a; // It is correct


// A reference (or alias) for i.
// but

int &p;
int &ref = i;
p = a; // It is incorrect as we should declare and
initialize references at single step
Theory Of Programming Languages
Fall 2024 33
~~~ Dr. Khalid Iqbal Khattak ~~~
Pointer and Reference Types

Output

Theory Of Programming Languages


Fall 2024 34
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Checking
Type checking is the process of verifying the each
operation executed in a program respects the type system
of the PL

All operands in expression are of suitable type and


number.

A lot of type checking is completed in semantic analysis


phase.

Theory Of Programming Languages


Fall 2024 35
~~~ Dr. Khalid Iqbal Khattak ~~~
Strong Typing
Strongly typed programming language refers to an idea that describes the enforcement of firm
restrictions on mixing different data types and values
Smalltalk, Ruby, Python are all "strongly typed" in the sense that typing errors are prevented at
runtime and they do little implicit type conversion, but these languages make no use of static
type checking
A love B. (Explicit) A hate everyone but B. (Implicit)

In C++, Strong types are user-defined types that do not allow implicit
conversions (coercion) to other types.
#include <iostream>
using namespace std;
int main() { int num_int;
double num_double = 9.99;
// implicit conversion
// assigning a double value to an int variable
num_int = num_double;
cout << "num_int = " << num_int << endl;
cout << "num_double = " << num_double << endl;
return 0;}
Theory Of Programming Languages
Fall 2024 36
~~~ Dr. Khalid Iqbal Khattak ~~~
Strong Typing

Output x = 107 y=a z = 108

Output Sum = 2

Theory Of Programming Languages


Fall 2024 37
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Equivalence
TYPE if two type expressions are
CHECKING equivalent
RULES then return a given type
else
return type_error

Structural equivalence is based on the content of type definitions: roughly


speaking, two types are the same if they consist of the same components,
put together in the same way.

Name equivalence is based on the lexical occurrence of type


definitions: roughly speaking, each definition introduces a new
type.

Theory Of Programming Languages


Fall 2024 38
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Equivalence

Algol-68, Modula-3, C, ML
use structural type
equivalence.

Java and Ada use


name equivalence.

Theory Of Programming Languages


Fall 2024 39
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Equivalence
struct Rec1{
char x;
int y;
char z[10]; };

struct Rec2{
char x;
int y;
char z[10];};

struct Rec3{
int y;
char x;
char z[10];};
In a C-like syntax, the types struct Rec1 and struct Rec2 are structurally
equivalent, but struct Rec1 and struct Rec3 are not
Theory Of Programming Languages
Fall 2024 40
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Equivalence

struct RecA{ struct RecB{


char x; char a;
int y;}; int b;};

RecA and RecB are structurally equivalent; however, RecA


and RecB are not equivalent, because variables of the
different structures would have to use different names to
access the member data.
Theory Of Programming Languages 41
Fall 2024
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Checking
Type checking is the process by which a translator verifies that all
constructs in a program make sense in terms of the types of its
constants, variables, procedures, and other entities.

It involves the application of a type equivalence algorithm to


expressions and statements, with the type-checking algorithm
varying the use of the type equivalence algorithm to suit the
context.

A complicating factor is the use of type names in declarations.


Type expressions in declarations may or may not be given explicit
names.
• For example, in C, variable declarations may be given using anonymous types (type
constructors applied without giving them names), but names can also be given right
in structs and unions, or by using a typedef.
Theory Of Programming Languages
Fall 2024 42
~~~ Dr. Khalid Iqbal Khattak ~~~
Type Checking: type names a complicating factor
Anonymous types (type constructors applied without giving them names), but
names can also be given right in structs and unions, or by using a typedef

typedef struct typedef


struct RecA{ RecB b; struct{
RecA RecA; struct{
char x; char x;
char x; int y; } c;
int y; } a;
int y;} RecB;

variable c’s type has no


Variable a has a data type
Variable b’s type has only name at all! (Actually, c’s
with two names: struct
the name RecB (the struct type still has a name, but it
RecA and RecA (as given by
name was left blank) is internal and cannot be
the typedef).
referred to by the
programmer)

Theory Of Programming Languages


Fall 2024 43
~~~ Dr. Khalid Iqbal Khattak ~~~
_______________________________

END

_______________________________

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy