尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
Course code: CS213
Course title :
(Programming Languages Concepts)
PART: 2
Prof. Taymoor Mohamed Nazmy
Dept. of computer science, faculty of computer science, Ain Shams uni.
Ex-vice dean of post graduate studies and research Cairo, Egypt
1
Describing syntax and semantics
2
Where are we?
High-level Programming
Languages
Logic
Functional
Imperative
Concepts
• specification (syntax, semantics)
• variables (binding, scoping, types, …)
• statements (control, selection, assignment,…)
Implementation
• compilation (lexical &
syntax analysis)
Assembly
Language
Machine
Language
Object
Oriented
You are
here 3
Syntax and semantics
• Syntax - the form or structure of the expressions, statements, and
program units.
• Semantics - the meaning of the expressions, statements, and
program units.
• Ex:
• while (<Boolean_expr>)<statement>
• The semantics of this statement form is that when the current value
of the Boolean expression is true, the embedded statement is
executed.
• The form of a statement should strongly suggest what the statement
is meant to accomplish.
4
Compiler processing steps of PL
• compilers have several steps of processing to do
before their programs are runnable:
- Reads the individual characters of the source code you give it.
- Sorts the characters into words, numbers, symbols, and operators.
- Takes the sorted characters and determines the operations they
are trying to perform by matching them against patterns, and
making a tree of the operations.
- Iterates over every operation in the tree made in the last step, and
generates the equivalent binary.
5
17-6
Language Components
• Lexicon, Syntax, Semantics
• All languages, including computer languages have vocabulary,
grammar and meaning. In computer science and linguistics,
these concepts are referred to as lexicon, syntax and semantics,
respectively.
• The lexicon of a computer language is its total inventory of
words and symbols. An item in the lexicon is called a lexeme,
which is the basic unit of meaning in a computer program.
• Lexemes are made up of smaller units called characters that
have no inherent meaning by themselves.
The Compiler check the correctness
of the language then translate it by
• Lexical analysis
– (or scanning), involves reading the individual characters of the computer
program, building each lexeme and identifying the token to which it
belongs. It can detects inputs with illegal tokens
• Parsing
– Or syntax analysis, the Parser (syntactical analyzer) takes the sequenceof tokens
and generates a tree representation, the Abstract Syntax. This tree is analyzed by
the type checker and is then used to generate the intermediate representation. It
can detects inputs with ill-formed parse trees
• Semantic analysis
– Catches all remaining errors, then the compiler translates the program
statement into the equivalent machine code instructions, a process called
code generation. 7
Syntax and semantics as a parts of Compiler Architecture
Analysis
of input program
(front-end)
character
stream
Lexical Analysis
Code Generation
Optimization
Intermediate Code
Generation
Semantic Analysis
Syntactic Analysis
annotated
AST
abstract
syntax tree
token
stream
target
language
intermediate
form
intermediate
form
Synthesis
of output program
(back-end)
Symbol
Table Error handler
8
Lexical rules
• Words are not elementary. They are constructed
out of characters belonging to an alphabet. Thus
the syntax of a language is defined by two sets of
rules: lexical rules and syntactic rules.
• Lexical rules specify the set of characters that
constitute the alphabet of the language and the
way such characters can be combined to form
valid words.
9
What is Lexical Analysis?
- The lexical analyzer deals with small-scale language constructs,
such as names and numeric literals. The syntax analyzer deals
with the large-scale constructs, such as expressions, statements,
and program units.
- The syntax analysis portion consists of two parts:
1. A low-level part called a lexical analyzer (essentially a
pattern matcher).
2. A high-level part called a syntax analyzer, or parser.
The lexical analyzer collects characters into logical
groupings and assigns internal codes to the groupings
according to their structure.
10
Lexical Analyzer in Perspective
• LEXICALANALYZER
– Scan Input
– Remove white space, …
– Identify Tokens
– Create Symbol Table
– Insert Tokens into AST
– Generate Errors
– Send Tokens to Parser
11
Token
• In programming, a token is a single element of a
programming language. There are five categories of
tokens:
• 1) constants,
• 2) identifiers,
• 3) operators,
• 4) separators,
• and 5) reserved words.
• For example, the reserved words "new" and "function"
are tokens of the JavaScript language. Operators, such as
+, -, *, and /, are also tokens of nearly all programming
languages.
12
13
Lexical analyzers extract lexemes from a given input string and
produce the corresponding tokens.
Sum = oldsum – value /100;
Token Lexeme
IDENT sum
ASSIGN_OP =
IDENT oldsum
SUBTRACT_OP -
IDENT value
DIVISION_OP /
INT_LIT 100
SEMICOLON ;
Lexemes vs token
14
15
Parser
• A parser is a compiler or interpreter component that breaks
data into smaller elements for easy translation into another
language.
• Parsing, syntax analysis, or syntactic analysis is the
process of analysing a string of symbols, either in natural
language, computer languages or data structures,
conforming to the rules of a formal grammar.
• A parser takes input in the form of a sequence of tokens or
program instructions and usually builds a data structure in
the form of a parse tree or an abstract syntax tree.
16
Parse Tree: a+b*c
<exp> * <exp>
<exp>
<exp> + <exp>
b c
a
Parse Tree: ((a+b)*c)
<exp>
<exp> + <exp>
( <exp> )
<exp> * <exp>
( <exp> )
a b
c
17
Error Management
or handler
• Errors can occur at all phases in the compiler
• Invalid input characters, syntax errors, semantic
errors, etc.
• Good compilers will attempt to recover from
errors and continue.
18
Abstract Syntax Tree
• The parse tree is used to recognize the components of the
program and to check that the syntax is correct.
• As the parser applies productions, it usually generates the
component of a simpler tree (known as Abstract Syntax Tree).
A syntax tree shows the structure of a program by abstracting away
irrelevant details from a parse tree.
Each node represents a computation to be performed;
The children of the node represents what that computation is
performed on.
19
Abstract Syntax Trees
E
E * E
15 ( E )
E + E
3 4
Times
Int 15 Plus
Int 3 Int 4
Parse tree Abstract syntax tree
15*(3+4)E for Expression
20
Semantic analyzer
• The semantic analyzer uses the syntax tree
and the information in the symbol table to
check the source program for semantic
consistency with the language definition.
• It also gathers type information and saves it in
either the syntax tree or the symbol table, for
subsequent use during intermediate-code
generation.
21
• The semantics consist of:
• Runtime semantics: behavior of program at run
time.
• Static semantics: checked by the compiler.
22
SEMANTIC ANALYZER(CONT.)
6
The semantic analyzer does the following:
Checks the static semantics of thelanguage.
Annotates the syntax tree with typeinformation, as
shown in example a.:= x + y * 2.5;
:= real
id a real + real
id x real * real
inttoreal literal 2.5 real
id y integer
Annotated syntax tree
23
STATIC SEMANTICS
2
4
Declaration of variables and constants before use. i.e.
int
x;
x=3;
Calling functions that exist (predefined in a library or defined by the user) i.e.
n = Max(4,7);
int Max(int x, int y)
{
int z;
if(x >
y)
z = x;
else
z =
y; return z;
}
24
STATIC SEMANTICS
2
5
Passing parameters properly.
Type checking, i.e.
int x, y;
x= 3;
y = 2.5;
performs an error, cause 2.5 is not int it is float data type.
Static semantics can not be checked bythe parser.
25
Symbol table
• symbol table is a data structure used by a language translator
such as a compiler or interpreter, where each identifier in a
program's source code is associated with information relating to
its declaration or appearance in the source.
• Symbol table stores the information related about the symbol.
• During early phases (lexical and syntax analysis) symbols are
discovered and put into the symbol table
• During later phases symbols are looked up to validate their
usage.
26
27
Symbol Table
• A “Dictionary” that maps names to info the compiler knows
about that name.
• What names?
– Variable and procedure names
– Literal constants and strings
• What info?
Textual name
Data type
Declaring procedure
Lexical level of declaration
If array, number and size of dimensions
If procedure, number and type of parameters
Symbol Table Management
• Typical symbol table activities:
1) To store the names of all entities in a structured form at
one place.
2) To verify if a variable has been declared.
3) To implement type checking, by verifying assignments
and expressions in the source code are semantically
correct.
4) To determine the scope of a name (scope resolution).
5) Add a new name
6) Add information for a name
7) Access information for a name
8) Determine if a name is present in the table
9) Remove a name
28
29
Optimizers
• Intermediate code is examined and improved.
• Can be simple:
– changing “a:=a+1” to “increment a”
– changing “3*5” to “15”
• Can be complicated:
– reorganizing data and data accesses for cache efficiency
• Optimization can improve running time by orders of
magnitude, often also decreasing program size.
30
Code Generation
• Generation of “real executable code” for a particular
target machine.
• It is completed by the Final Assembly phase
• Final output can either be
– assembly language for the target machine
– object code ready for linking
31
32
Compilation process
Source code
(character stream)
Lexical analysis
Parsing
Token stream
Abstract syntax tree
(AST)
Semantic Analysis
if (b == 0) a = b;
if ( b ) a = b ;0==
if
==
b 0
=
a b
if
==
int b int 0
=
int a
lvalue
int b
boolean
Decorated AST
int
;
;
33
Compilation process
Intermediate Code Generation
Optimization
Code generation
if
==
int b int 0
=
int a
lvalue
int b
boolean int
;
CJUMP ==
MEM
fp 8
+
CONST MOVE
0 MEM MEM
fp 4 fp 8
NOP
+ +
CJUMP ==
CONST MOVE
0 DX CX
NOPCX
CMP CX, 0
CMOVZ DX,CX
PL grammar
34
Why Backus-Naur form (BNF)
• BNF is a metalanguage which is used to explain
computer languages.
• In the world of computing, there are several
widely used metalanguages are Backus Naur
Form (BNF), Extended Backus Naur Form
(EBNF), Augmented Backus Naur Form (ABNF).
BNF is essential in compiler construction
35
Backus-Naur form (BNF)
• BNF is a meta-language. A meta-language is a language that is
used to describe other languages. The Backus Naur Form is
designed in a set of derivation rules expressed as,
• <symbol> ::= __expression__
• We describe BNF first, and then we show how it can be used to
describe the syntax of a simple programming language.
• The symbols
• ::=, < , > , * , + , ( , ) , and |
• are symbols of the metalanguage: they are metasymbols.
36
BNF symbols
• < > indicate a nonterminal that needs to be
further expanded, e.g. <variable>
• Symbols not enclosed in < > are terminals;
they represent themselves, e.g. if, while,
• The symbol ::= means is defined as
• The symbol | means or; it separates
alternatives,
37
• <integer> ::= <digit> | <digit><digit>
• Here, both <integer> and <digit> are Non-
Terminals and will give an output like,
• <integer> ::= 5
• <integer> ::= 86
38
BNF for as language descriptor
• <program> ::= <stmts>
<stmts> ::= <stmt>
<stmts> ::= <stmnt> ; <stmnts>
• <stmt> ::= <var> = <expr>
• <var> ::= a | b | c | d
• <expr> ::= <term> + <term> | <term> - <term>
• <term> ::= <var> | const
39
• e.g1.
<while_stmt> ::= while <logic_expr> do <stmt>
• This is a rule; it describes the structure of a while
statement.
• e.g2.
• if-then-else-statement ::= if <test>
then <statement> else <statement>
• This is a rule; it describes the structure of if statement
40
BNF and Parse Trees
<program>
<stmts>
<stmt>
<var> = <expr>
a <term> + <term>
<var> const
b
A parse tree is a hierarchical representation of BNF
41
42
BNF and Parsing
source file
Scanner
Parser
input stream
parse tree
sum = x1 + x2;
sum
=
x1
+
x2
;
sum
=
+
x1 x2
tokens
Regular expressions
define tokens
BNF rules define
grammar elements
Imperative languages
43
Imperative programming
• Imperative programming based on Von Neumann’s
computer model. It describes a sequence of steps that
change the state of the computer.
• Imperative programming explicitly tells the
computer "how" to accomplish a specific task .
44
Comparing imperative, functional and
object oriented paradigms
46
What is a Type?
• A type is a qualifier that is used by the compiler
 Machine languages do not have types
• The type of a variable or constant tells the
compiler:
– How much space the object occupies
– What operations on the object mean
What is a Type?
• Given an address in RAM, what does it mean?
 Could be anything!
• Types tell the compiler
– Which instruction to apply
Integer addition, floating pt addition
– How to increment pointers
Array references, fields
Data Types
 Data Type:
 In computer science and computer programming, a data type or
simply type is a classification identifying one of various types of data,
A data type is used to:
Identify the type of a variable when the variable is declared
Identify the type of the return value of a function
Identify the type of a parameter expected by a function
 Types of Data Type:
 primitive data types
 non-primitive data types 50
• Primitive Data Type: include floating-point,
integer, enumerated type, double and many
other topics from this portion.
• Non Primitive Data Type consists of:
• Composite Data Type: It may includes array,
union, record and tagged union data type.
• Abstract Data Type: Like stack, queue,
graph, tree etc.
51
52
Data Type Examples
• Predefined:
– type: int
– elements: …, -2, -1, 0, 1, 2, …
– operations: +, -, *, /, %, …
• User-defined:
– type: complex
– elements: 1+3i, -5+8i, …
– operations: newComplex, add, distance, …
53
• Other examples of data types
• Boolean (e.g., True or False)
• Character (e.g., a)
• Date (e.g., 03/01/2016)
• Double (e.g., 1.79769313486232E308)
• Floating-point number (e.g., 1.234)
• Integer (e.g., 1234)
• Long (e.g., 123456789)
• Short (e.g., 0)
• String (e.g., abcd)
• Void (e.g., no data)
54
Size and Range of Integer Data
55
Decimal Integer
 It consists of 0-9 digits, preceded by an optional – or
+ sign.
 Valid example of decimal integer are : 123 , -321, 0 ,
654321, +78
 Embedded spaces, comma and non digit characters
are not permitted between digits.
 15 750, 20,000, $1000 are Illegal
56
Floating Point Types
 Floating point numbers are stored in 32 bits with
6 digits of precision.
 When the accuracy provided by float is not
sufficient double data type is used. It uses 64 bits
giving a precision of 14 digits.
 When you want to extend more precision you can use
the long double data type. It uses 80 bits
57
Void Types
 Void type has no values.
 Void type does not return any values.
 These are used to specify the return values from the
function when they don‟t have any value to return
58
Character Types
59
60
61
62
2 dimensional array
Records
• A (possibly heterogeneous) aggregate of data
elements in which the individual elements are
identified by names
64
Pointers
int x = 20;
int *p;
p = &x;
*p = 20;
Declares a pointer
to an integer
& is address operator
gets address of x
* dereference operator
gets value at p
65
A pointer is a variable holding an address value
Pointers
int x = 20;
int *p;
p = &x;
*p = 20;
*p refers to the value stored in x.
p
x20
A pointer is a variable holding an address value
66
Declarations
• Constants and variables must be declared before they can be used.
• A constant declaration specifies the type, the name and the value of the
constant.
• A variable declaration specified the name and possibly the initial value of
the variable.
• When you declare a constant or a variable, the compiler
1. Reserves a memory location in which to store the value of the constant
or variable.
2. Associates the name of the constant or variable with the memory
location. (You will use this name for referring to the constant or
variable.)
67
Variables
• A variable is an abstraction of a memory cell
• Variables can be characterized by several
attributes:
– Name
– Address
– Value
– Type
– Lifetime
– Scope
Variables
• Address
– the memory address with which it is associated
– A variable may have different addresses at different times
during execution – e.g., local variables in subprograms
– A variable may have different addresses at different places in
a program – e.g., variable allocated from the runtime stack
– Aliases
• If two variable names can be used to access the same memory
location
• harmful to readability (program readers must remember all of them)
• How aliases can be created:
– Pointers, reference variables, Pascal variant records, C and C++ unions,
and FORTRAN EQUIVALENCE
Variables
• Type
– determines the range of values of variables and the
set of operations that are defined for values of that
type
• int type in Java specifies a value range of –2147483648
to 2147483647 and arithmetic operations for addition,
subtraction, division, etc
– in the case of floating point, type also determines
the precision (single or double)
Variables
• Value
– the contents of the memory cells with which the
variable is associated
– Abstract memory cell - the physical cell or
collection of cells associated with a variable
• The l-value of a variable is its address
• The r-value of a variable is its value
slide 73
Variables: Locations and Values
• When a variable is declared, it is bound to some
memory location and becomes its identifier
– Location could be in global, heap, or stack storage
• l-value: memory location (address)
• r-value: value stored at the memory location identified
by l-value
• Assignment: A (target) = B (expression)
– Destructive update: overwrites the memory location
identified by A with a value of expression B
slide 74
Variables and Assignment
• On the RHS of an assignment, use the variable’s
r-value; on the LHS, use its l-value
– Example: x = x+1
– Meaning: “get r-value of x, add 1, store the result
into the l-value of x”
• Example: x=x*y means “compute rval(x)*rval(y) and
store it in lval(x)”
Names, binding, type
checking, and scope
76
Introduction
• The central feature of imperative languages are variables
• Variables are abstractions for memory cells in a Von
Neumann architecture computer
• Attributes of variables
– Name, Type, Address, Value, …
• Other important concepts
– Binding and Binding times
– Strong typing
– Type compatibility rules
– Scoping rules
77
Preliminaries
• Name: representation for something else
– E.g.: identifiers, some symbols
• Binding: association between two things;
– Name and the thing that it names
• Scope of binding: part of (textual) program that
binding is active
• Binding time: point at which binding created
– Generally: point at which any implementation decision
is made.
78
Names (Identifiers)
• Names are not only associated with variables
– Also associated with labels, subprograms, formal
parameters, and other program constructs
• Design issues for names:
– Maximum length?
– Are connector characters allowed? (“_”)
– Are names case sensitive?
– Are the special words: reserved words or keywords?
79
Names
• Length
– Language examples:
• FORTRAN I: maximum 6
• COBOL: maximum 30
• FORTRAN 90 and ANSI C (1989): maximum 31
– Ansi C (1989): no length limitation, but only first 31 chars significant
• Ada and Java: no limit, and all are significant
• C++: no limit, but implementors often impose one
• Connector characters
– C, C++, and Perl allows “_” character in identifier names
– Fortran 77 allows spaces in identifier names:
Sum Of Salaries and SumOfSalaries refer to the same identifier
80
Names
• Case sensitivity
– C, C++, and Java names are case sensitive
– Disadvantages:
• readability (names that look alike are different)
• writability (must remember exact spelling)
– Java: predefined names are mixed case (e.g.
IndexOutOfBoundsException)
– Earlier versions of Fortran use only uppercase letters
for names
81
Case Sensitive or Case
Insensitive?
foobar == FooBar == FOOBAR
?
C-basedlanguages:case sensitive
C convention: variable namesonly lower caseletters
Pascal:case insensitive
Javaconvention: CamelCaseinstead ofunder_scores
82
Names
• Special words
– Make program more readable by naming actions to
be performed and to separate syntactic entities of
programs
– A reserved word is a special word that cannot be
used as a user-defined name
83
Special Words
keyword:identifier with special
meaningin certaincontexts
reserved word: specialword
that cannot beusedasaname
Integer Apple
Integer = 4
type
name
Fortran
Integer Real
Real Integerpackage
example;
class User {
private String name;
public String get_name
{
return name;
}
}
Java
84
Binding
• 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
86
Binding Times
• Possible binding times:
1. Language design time
e.g., bind operator symbols to operations
2. Language implementation time
e.g., bind floating point type to a representation
3. Compile time
e.g., bind a variable to a type in C or Java
4. Load time
e.g., bind a FORTRAN 77 variable to a memory cell (or a C static variable)
5. Runtime
e.g., bind a nonstatic local variable to a memory cell
87
88
Storage Binding
• Storage Bindings
– Allocation
• getting a cell from some pool of available memory cells
– Deallocation
• putting a cell back into the pool of memory cells
• Lifetime of a variable is the time during which it is bound to a
particular memory cell
– 4 types of variables (based on lifetime of storage binding)
• Static
• Stack-dynamic
• Explicit heap-dynamic
• Implicit heap-dynamic
89
90
Type Systems
• A language’s type system specifies which
operations are valid for which types
• The goal of type checking is to ensure that
operations are used with the correct types
– Enforces intended interpretation of values, because
nothing else will!
• Type systems provide a concise formalization of
the semantic checking rules
Type Checking
• Type checking ensures that the operands and the operator are of
compatible types
• Generalized to include subprograms and assignments
• Compatible type is either
– legal for the operator, or
– language rules allow it to be converted to a legal type
• Coercion
– Automatic conversion
• Type error
– Application of an operator to an operand of incorrect type
• Nearly all type checking can be static for static type bindings
• Type checking must be dynamic for dynamic type bindings
91
92
Kinds of Type Checking
• Three kinds of languages:
– Statically typed: All or almost all checking of types
is done as part of compilation (C, Java, Cool)
– Dynamically typed: Almost all checking of types is
done as part of program execution (Scheme)
– Untyped: No type checking (machine code)
93
Also called lexicalscoping.
Ifa variable name's scope isa certain function,
then itsscope isthe program textof the function
definition:withinthat text, the variable name exists,
and is bound to itsvariable, but outside that text,
the variable name does not exist.
94
Indynamic scoping (ordynamic scope), ifa
variable name's scope is a certain function, then its
scopeisthe time-period duringwhich the function is
executing.
While the function isrunning,the variable name exists,
and isbound to itsvariable, but after the function
returns,the variable name does not exist.
95
Expressions and assignment
statements
96
LHS and RHS
• LHS = Left Hand Side
 Means replace contents
 Set value where this thing is stored
• RHS = Right Hand Side
– Means value
– Evaluate expression, function, etc.
– Arrive at a value to store in LHS
Constants
• Fixed values such as numbers, letters, and
strings are called “constants” - because their
value does not change
• Numeric constants are as you expect
• String constants use single-quotes (')
or double-quotes (")
>>> print 123
123
>>> print 98.6
98.6
>>> print 'Hello world'
Hello world
98
Sentences or Lines
x = 2
x = x + 2
print x
Variable Operator Constant Reserved Word
Assignment Statement
Assignment with expression
Print statement
100
Assignment Statements
• We assign a value to a variable using the assignment
statement (=)
• An assignment statement consists of an expression on
the right hand side and a variable to store the result
x = 3.9 * x * ( 1 - x )
101
x = 3.9 * x * ( 1 - x )
0.6x
Right side is an expression. Once
expression is evaluated, the result is
placed in (assigned to) x.
0.6
0.6
0.4
0.93
A variable is a memory location used to
store a value (0.6).
102
x = 3.9 * x * ( 1 - x )
0.6 0.93x
Right side is an expression. Once
expression is evaluated, the result is
placed in (assigned to) the variable on
the left side (i.e. x).
0.93
A variable is a memory location used to
store a value. The value stored in a
variable can be updated by replacing the
old value (0.6) with a new value (0.93).
103
Order of Evaluation
• When we string operators together - it must know
which one to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others
x = 1 + 2 * 3 - 4 / 5 ** 6
104
Operator Precedence Rules
• Highest precedence rule to lowest precedence
rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and Remainder
• Addition and Subtraction
• Left to right
Parenthesis
Power
Multiplication
Addition
Left to Right
105
Parenthesis
Power
Multiplication
Addition
Left to Right
1 + 2 ** 3 / 4 * 5
1 + 8 / 4 * 5
1 + 2 * 5
1 + 10
11
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11
>>>
106
Parenthesis
Power
Multiplication
Addition
Left to Right
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11
>>>
1 + 2 ** 3 / 4 * 5
1 + 8 / 4 * 5
1 + 2 * 5
1 + 10
11
Note 8/4 goes before 4*5
because of the left-right rule.
107
108
Arithmetic Expressions
Boolean Expressions
Relational Expressions
109
Arithmetic Expressions can either be
integer expressions or real expressions.
Sometimes a mixed expressions can also
be formed which is a mixer of real and
integer expressions.
110
Expressions
• An expression is a sequence of operands and operators
that reduces to a single value.
– Example: 2 * 5
• Operators
– An operator is a language-specific syntactical token that requires
an action to be taken.
• Operand
– A operand receives an operator’s action.
– The operands of multiply are the multiplier and the multiplicand.
111
=> OPERATORS: “An operator is a symbol (+,-,*,/) that
directs the computer to perform certain mathematical or
logical manipulations and is usually used to manipulate data
and variables”
=>The objects of the operation(s) are referred to as
Operands.
Ex: a + b
operands
Operator
112
Example
----------------------
3 + 5
2 - 4
Num * 5
Sum / Count
Count % 4
-----------------------
Count ++
Count --
Operator
----------------
+
-
*
/
%
----------
++
--
Definition
----------------
Addition
Subtraction
Multiplication
Division (quotient)
Division (remainder)
-----------------------
Increment
Decrement
Arithmetic operators
113
Meaning
----------------------
Store 5 in Num
Num = Num + 5
Num = Num - 5
Num = Num * 5
Num = Num / 5
Num = Num % 5
Operator
----------------
==
+=
-=
*=
/=
%=
Example
----------------
Num = 5
Num += 5
Num -= 5
Num *= 5
Num /= 5
Num %= 5
Assignment operators
114
• Integer Expressions are formed by connecting integer
constants and/or integer variables using integer
arithmetic operators.
• The following are valid integer expressions :
• int I,J,K,X,Y,Z,count;
• A) k - x
• B) k + x – y + count
• C) –j + k * y
• D) z % y
115
• Real Expressions are formed by connecting real
constants and/or real variables using real arithmetic
operators.
• The following are valid real expressions:
• float qty,amount,,value;
• double fin,inter; const bal=250.53;
• i) qty/amount
• ii) (amount + qty*value)-bal
• iii) fin + qty* inter
• iv) inter – (qty * value) + fin 116
The process of converting one
predefined type into another is
called Type Conversion.
C++ facilitates the type
conversion .
117
Boolean expression
• Boolean expression is used expression in a
programming language that produces a Boolean
value when evaluated, that is one of true or false.
• A Boolean expression may be composed of a
combination of the Boolean constants true or
false, Boolean-typed variables, Boolean-valued
operators, and Boolean-valued functions.
118
Example
----------------------
! ( Num1 < Num2 )
(Num1 < 5 ) && (Num2 > 10 )
(Num1 < 5 ) || (Num2 > 10 )
Operator
----------------
!
&&
||
Definition
----------------
NOT
AND
OR
Logical operators
119
120
Example
----------------------
Num1 < 5
Num1 <= 5
Num2 > 3
Num2 >= 3
Num1 == Num2
Num1 != Num2
Operator
----------------
<
<=
>
>=
==
!=
Definition
----------------
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
Relational operators
121
End of Part 2
122

More Related Content

What's hot

Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
Ashwini Sonawane
 
Cpcs302 1
Cpcs302  1Cpcs302  1
Cpcs302 1
guest5de1a5
 
Principles of compiler design
Principles of compiler designPrinciples of compiler design
Principles of compiler design
Janani Parthiban
 
Compiler Design Lecture Notes
Compiler Design Lecture NotesCompiler Design Lecture Notes
Compiler Design Lecture Notes
FellowBuddy.com
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
Farzana Aktar
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
Huawei Technologies
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
Nayemid4676
 
Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...
Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...
Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...
Bhavin Darji
 
Compilers
CompilersCompilers
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Dr. Jaydeep Patil
 
Cd unit i
Cd unit iCd unit i
Cd unit i
thulasib1
 
Compiler design
Compiler designCompiler design
Compiler design
sanchi29
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1Compiler Engineering Lab#1
Compiler Engineering Lab#1
MashaelQ
 
The Phases of a Compiler
The Phases of a CompilerThe Phases of a Compiler
The Phases of a Compiler
Radhika Talaviya
 
Ss ui lecture 2
Ss ui lecture 2Ss ui lecture 2
Ss ui lecture 2
Avinash Kapse
 
The analysis synthesis model of compilation
The analysis synthesis model of compilationThe analysis synthesis model of compilation
The analysis synthesis model of compilation
Huawei Technologies
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compiler
Karan Deopura
 
Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compiler
Sumit Sinha
 
phases of a compiler
 phases of a compiler phases of a compiler
phases of a compiler
Ms.SHANTHI.S CSE
 
Principles of compiler design
Principles of compiler designPrinciples of compiler design
Principles of compiler design
DHARANI BABU
 

What's hot (20)

Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Cpcs302 1
Cpcs302  1Cpcs302  1
Cpcs302 1
 
Principles of compiler design
Principles of compiler designPrinciples of compiler design
Principles of compiler design
 
Compiler Design Lecture Notes
Compiler Design Lecture NotesCompiler Design Lecture Notes
Compiler Design Lecture Notes
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
 
Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...
Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...
Overview of Language Processor : Fundamentals of LP , Symbol Table , Data Str...
 
Compilers
CompilersCompilers
Compilers
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Cd unit i
Cd unit iCd unit i
Cd unit i
 
Compiler design
Compiler designCompiler design
Compiler design
 
Compiler Engineering Lab#1
Compiler Engineering Lab#1Compiler Engineering Lab#1
Compiler Engineering Lab#1
 
The Phases of a Compiler
The Phases of a CompilerThe Phases of a Compiler
The Phases of a Compiler
 
Ss ui lecture 2
Ss ui lecture 2Ss ui lecture 2
Ss ui lecture 2
 
The analysis synthesis model of compilation
The analysis synthesis model of compilationThe analysis synthesis model of compilation
The analysis synthesis model of compilation
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compiler
 
Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compiler
 
phases of a compiler
 phases of a compiler phases of a compiler
phases of a compiler
 
Principles of compiler design
Principles of compiler designPrinciples of compiler design
Principles of compiler design
 

Similar to Plc part 2

1._Introduction_.pptx
1._Introduction_.pptx1._Introduction_.pptx
1._Introduction_.pptx
Anbarasan Radhakrishnan R
 
COMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptxCOMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptx
Rossy719186
 
11700220036.pdf
11700220036.pdf11700220036.pdf
11700220036.pdf
SouvikRoy149
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
sivaganesh293
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
sivaganesh293
 
System software module 4 presentation file
System software module 4 presentation fileSystem software module 4 presentation file
System software module 4 presentation file
jithujithin657
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
adilmehmood93
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
Sarmad Ali
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
Compiler Design.pptx
Compiler Design.pptxCompiler Design.pptx
Compiler Design.pptx
SouvikRoy149
 
Principles of Compiler Design
Principles of Compiler DesignPrinciples of Compiler Design
Principles of Compiler Design
Marimuthu M
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Mir Majid
 
1 compiler outline
1 compiler outline1 compiler outline
1 compiler outline
ASHOK KUMAR REDDY
 
automata theroy and compiler designc.pptx
automata theroy and compiler designc.pptxautomata theroy and compiler designc.pptx
automata theroy and compiler designc.pptx
YashaswiniYashu9555
 
Compiler1
Compiler1Compiler1
Compiler1
Natish Kumar
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
NesredinTeshome1
 
Chapter-1.pptx compiler Design Course Material
Chapter-1.pptx compiler Design Course MaterialChapter-1.pptx compiler Design Course Material
Chapter-1.pptx compiler Design Course Material
gadisaAdamu
 
phases of compiler-analysis phase
phases of compiler-analysis phasephases of compiler-analysis phase
phases of compiler-analysis phase
Suyash Srivastava
 
Introduction to Compilers
Introduction to CompilersIntroduction to Compilers
Introduction to Compilers
vijaya603274
 

Similar to Plc part 2 (20)

1._Introduction_.pptx
1._Introduction_.pptx1._Introduction_.pptx
1._Introduction_.pptx
 
COMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptxCOMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptx
 
11700220036.pdf
11700220036.pdf11700220036.pdf
11700220036.pdf
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
 
System software module 4 presentation file
System software module 4 presentation fileSystem software module 4 presentation file
System software module 4 presentation file
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
Compiler Design.pptx
Compiler Design.pptxCompiler Design.pptx
Compiler Design.pptx
 
Principles of Compiler Design
Principles of Compiler DesignPrinciples of Compiler Design
Principles of Compiler Design
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
1 compiler outline
1 compiler outline1 compiler outline
1 compiler outline
 
automata theroy and compiler designc.pptx
automata theroy and compiler designc.pptxautomata theroy and compiler designc.pptx
automata theroy and compiler designc.pptx
 
Compiler1
Compiler1Compiler1
Compiler1
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
 
Chapter-1.pptx compiler Design Course Material
Chapter-1.pptx compiler Design Course MaterialChapter-1.pptx compiler Design Course Material
Chapter-1.pptx compiler Design Course Material
 
phases of compiler-analysis phase
phases of compiler-analysis phasephases of compiler-analysis phase
phases of compiler-analysis phase
 
Introduction to Compilers
Introduction to CompilersIntroduction to Compilers
Introduction to Compilers
 

More from Taymoor Nazmy

Cognitive systems
Cognitive  systemsCognitive  systems
Cognitive systems
Taymoor Nazmy
 
Cognitive systems
Cognitive  systemsCognitive  systems
Cognitive systems
Taymoor Nazmy
 
Artificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logicArtificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logic
Taymoor Nazmy
 
Artificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-searchArtificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-search
Taymoor Nazmy
 
Lec 2-agents
Lec 2-agentsLec 2-agents
Lec 2-agents
Taymoor Nazmy
 
Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-
Taymoor Nazmy
 
Image processing 2
Image processing 2Image processing 2
Image processing 2
Taymoor Nazmy
 
Image processing 1-lectures
Image processing  1-lecturesImage processing  1-lectures
Image processing 1-lectures
Taymoor Nazmy
 
Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--
Taymoor Nazmy
 
Software Engineering Lec 8-design-
Software Engineering Lec 8-design-Software Engineering Lec 8-design-
Software Engineering Lec 8-design-
Taymoor Nazmy
 
Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-
Taymoor Nazmy
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
Taymoor Nazmy
 
Software Engineering Lec 4-requirments
Software Engineering Lec 4-requirmentsSoftware Engineering Lec 4-requirments
Software Engineering Lec 4-requirments
Taymoor Nazmy
 
Software Engineering Lec 3-project managment
Software Engineering Lec 3-project managmentSoftware Engineering Lec 3-project managment
Software Engineering Lec 3-project managment
Taymoor Nazmy
 
Software Engineering Lec 2
Software Engineering Lec 2Software Engineering Lec 2
Software Engineering Lec 2
Taymoor Nazmy
 
Software Engineering Lec 1-introduction
Software Engineering Lec 1-introductionSoftware Engineering Lec 1-introduction
Software Engineering Lec 1-introduction
Taymoor Nazmy
 
Lec 6-
Lec 6-Lec 6-
presentation skill
presentation skillpresentation skill
presentation skill
Taymoor Nazmy
 
Lec 4
Lec 4Lec 4
Lec 3
Lec 3Lec 3

More from Taymoor Nazmy (20)

Cognitive systems
Cognitive  systemsCognitive  systems
Cognitive systems
 
Cognitive systems
Cognitive  systemsCognitive  systems
Cognitive systems
 
Artificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logicArtificial intelligent Lec 5-logic
Artificial intelligent Lec 5-logic
 
Artificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-searchArtificial intelligent Lec 3-ai chapter3-search
Artificial intelligent Lec 3-ai chapter3-search
 
Lec 2-agents
Lec 2-agentsLec 2-agents
Lec 2-agents
 
Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-Artificial intelligent Lec 1-ai-introduction-
Artificial intelligent Lec 1-ai-introduction-
 
Image processing 2
Image processing 2Image processing 2
Image processing 2
 
Image processing 1-lectures
Image processing  1-lecturesImage processing  1-lectures
Image processing 1-lectures
 
Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--Software Engineering Lec 10 -software testing--
Software Engineering Lec 10 -software testing--
 
Software Engineering Lec 8-design-
Software Engineering Lec 8-design-Software Engineering Lec 8-design-
Software Engineering Lec 8-design-
 
Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-Software Engineering Lec 7-uml-
Software Engineering Lec 7-uml-
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
Software Engineering Lec 4-requirments
Software Engineering Lec 4-requirmentsSoftware Engineering Lec 4-requirments
Software Engineering Lec 4-requirments
 
Software Engineering Lec 3-project managment
Software Engineering Lec 3-project managmentSoftware Engineering Lec 3-project managment
Software Engineering Lec 3-project managment
 
Software Engineering Lec 2
Software Engineering Lec 2Software Engineering Lec 2
Software Engineering Lec 2
 
Software Engineering Lec 1-introduction
Software Engineering Lec 1-introductionSoftware Engineering Lec 1-introduction
Software Engineering Lec 1-introduction
 
Lec 6-
Lec 6-Lec 6-
Lec 6-
 
presentation skill
presentation skillpresentation skill
presentation skill
 
Lec 4
Lec 4Lec 4
Lec 4
 
Lec 3
Lec 3Lec 3
Lec 3
 

Recently uploaded

pol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdfpol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdf
BiplabHalder13
 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
Sarojini38
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapitolTechU
 
How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
Celine George
 
Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024
Friends of African Village Libraries
 
managing Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptxmanaging Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptx
nabaegha
 
Slides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptxSlides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptx
shabeluno
 
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptxScience-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Catherine Dela Cruz
 
Talking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual AidsTalking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual Aids
MattVassar1
 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
khabri85
 
The Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teachingThe Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teaching
Derek Wenmoth
 
Opportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive themOpportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive them
EducationNC
 
Interprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdfInterprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdf
Ben Aldrich
 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
ShwetaGawande8
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
 
8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity
RuchiRathor2
 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
Kalna College
 
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
Kalna College
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Kalna College
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
Infosec
 

Recently uploaded (20)

pol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdfpol sci Election and Representation Class 11 Notes.pdf
pol sci Election and Representation Class 11 Notes.pdf
 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
 
How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17How to Download & Install Module From the Odoo App Store in Odoo 17
How to Download & Install Module From the Odoo App Store in Odoo 17
 
Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024Library news letter Kitengesa Uganda June 2024
Library news letter Kitengesa Uganda June 2024
 
managing Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptxmanaging Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptx
 
Slides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptxSlides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptx
 
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptxScience-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
 
Talking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual AidsTalking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual Aids
 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
 
The Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teachingThe Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teaching
 
Opportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive themOpportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive them
 
Interprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdfInterprofessional Education Platform Introduction.pdf
Interprofessional Education Platform Introduction.pdf
 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
 
8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity8+8+8 Rule Of Time Management For Better Productivity
8+8+8 Rule Of Time Management For Better Productivity
 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
 
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...220711130095 Tanu Pandey message currency, communication speed & control EPC ...
220711130095 Tanu Pandey message currency, communication speed & control EPC ...
 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
 
How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...How to stay relevant as a cyber professional: Skills, trends and career paths...
How to stay relevant as a cyber professional: Skills, trends and career paths...
 

Plc part 2

  • 1. Course code: CS213 Course title : (Programming Languages Concepts) PART: 2 Prof. Taymoor Mohamed Nazmy Dept. of computer science, faculty of computer science, Ain Shams uni. Ex-vice dean of post graduate studies and research Cairo, Egypt 1
  • 2. Describing syntax and semantics 2
  • 3. Where are we? High-level Programming Languages Logic Functional Imperative Concepts • specification (syntax, semantics) • variables (binding, scoping, types, …) • statements (control, selection, assignment,…) Implementation • compilation (lexical & syntax analysis) Assembly Language Machine Language Object Oriented You are here 3
  • 4. Syntax and semantics • Syntax - the form or structure of the expressions, statements, and program units. • Semantics - the meaning of the expressions, statements, and program units. • Ex: • while (<Boolean_expr>)<statement> • The semantics of this statement form is that when the current value of the Boolean expression is true, the embedded statement is executed. • The form of a statement should strongly suggest what the statement is meant to accomplish. 4
  • 5. Compiler processing steps of PL • compilers have several steps of processing to do before their programs are runnable: - Reads the individual characters of the source code you give it. - Sorts the characters into words, numbers, symbols, and operators. - Takes the sorted characters and determines the operations they are trying to perform by matching them against patterns, and making a tree of the operations. - Iterates over every operation in the tree made in the last step, and generates the equivalent binary. 5
  • 6. 17-6 Language Components • Lexicon, Syntax, Semantics • All languages, including computer languages have vocabulary, grammar and meaning. In computer science and linguistics, these concepts are referred to as lexicon, syntax and semantics, respectively. • The lexicon of a computer language is its total inventory of words and symbols. An item in the lexicon is called a lexeme, which is the basic unit of meaning in a computer program. • Lexemes are made up of smaller units called characters that have no inherent meaning by themselves.
  • 7. The Compiler check the correctness of the language then translate it by • Lexical analysis – (or scanning), involves reading the individual characters of the computer program, building each lexeme and identifying the token to which it belongs. It can detects inputs with illegal tokens • Parsing – Or syntax analysis, the Parser (syntactical analyzer) takes the sequenceof tokens and generates a tree representation, the Abstract Syntax. This tree is analyzed by the type checker and is then used to generate the intermediate representation. It can detects inputs with ill-formed parse trees • Semantic analysis – Catches all remaining errors, then the compiler translates the program statement into the equivalent machine code instructions, a process called code generation. 7
  • 8. Syntax and semantics as a parts of Compiler Architecture Analysis of input program (front-end) character stream Lexical Analysis Code Generation Optimization Intermediate Code Generation Semantic Analysis Syntactic Analysis annotated AST abstract syntax tree token stream target language intermediate form intermediate form Synthesis of output program (back-end) Symbol Table Error handler 8
  • 9. Lexical rules • Words are not elementary. They are constructed out of characters belonging to an alphabet. Thus the syntax of a language is defined by two sets of rules: lexical rules and syntactic rules. • Lexical rules specify the set of characters that constitute the alphabet of the language and the way such characters can be combined to form valid words. 9
  • 10. What is Lexical Analysis? - The lexical analyzer deals with small-scale language constructs, such as names and numeric literals. The syntax analyzer deals with the large-scale constructs, such as expressions, statements, and program units. - The syntax analysis portion consists of two parts: 1. A low-level part called a lexical analyzer (essentially a pattern matcher). 2. A high-level part called a syntax analyzer, or parser. The lexical analyzer collects characters into logical groupings and assigns internal codes to the groupings according to their structure. 10
  • 11. Lexical Analyzer in Perspective • LEXICALANALYZER – Scan Input – Remove white space, … – Identify Tokens – Create Symbol Table – Insert Tokens into AST – Generate Errors – Send Tokens to Parser 11
  • 12. Token • In programming, a token is a single element of a programming language. There are five categories of tokens: • 1) constants, • 2) identifiers, • 3) operators, • 4) separators, • and 5) reserved words. • For example, the reserved words "new" and "function" are tokens of the JavaScript language. Operators, such as +, -, *, and /, are also tokens of nearly all programming languages. 12
  • 13. 13
  • 14. Lexical analyzers extract lexemes from a given input string and produce the corresponding tokens. Sum = oldsum – value /100; Token Lexeme IDENT sum ASSIGN_OP = IDENT oldsum SUBTRACT_OP - IDENT value DIVISION_OP / INT_LIT 100 SEMICOLON ; Lexemes vs token 14
  • 15. 15
  • 16. Parser • A parser is a compiler or interpreter component that breaks data into smaller elements for easy translation into another language. • Parsing, syntax analysis, or syntactic analysis is the process of analysing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar. • A parser takes input in the form of a sequence of tokens or program instructions and usually builds a data structure in the form of a parse tree or an abstract syntax tree. 16
  • 17. Parse Tree: a+b*c <exp> * <exp> <exp> <exp> + <exp> b c a Parse Tree: ((a+b)*c) <exp> <exp> + <exp> ( <exp> ) <exp> * <exp> ( <exp> ) a b c 17
  • 18. Error Management or handler • Errors can occur at all phases in the compiler • Invalid input characters, syntax errors, semantic errors, etc. • Good compilers will attempt to recover from errors and continue. 18
  • 19. Abstract Syntax Tree • The parse tree is used to recognize the components of the program and to check that the syntax is correct. • As the parser applies productions, it usually generates the component of a simpler tree (known as Abstract Syntax Tree). A syntax tree shows the structure of a program by abstracting away irrelevant details from a parse tree. Each node represents a computation to be performed; The children of the node represents what that computation is performed on. 19
  • 20. Abstract Syntax Trees E E * E 15 ( E ) E + E 3 4 Times Int 15 Plus Int 3 Int 4 Parse tree Abstract syntax tree 15*(3+4)E for Expression 20
  • 21. Semantic analyzer • The semantic analyzer uses the syntax tree and the information in the symbol table to check the source program for semantic consistency with the language definition. • It also gathers type information and saves it in either the syntax tree or the symbol table, for subsequent use during intermediate-code generation. 21
  • 22. • The semantics consist of: • Runtime semantics: behavior of program at run time. • Static semantics: checked by the compiler. 22
  • 23. SEMANTIC ANALYZER(CONT.) 6 The semantic analyzer does the following: Checks the static semantics of thelanguage. Annotates the syntax tree with typeinformation, as shown in example a.:= x + y * 2.5; := real id a real + real id x real * real inttoreal literal 2.5 real id y integer Annotated syntax tree 23
  • 24. STATIC SEMANTICS 2 4 Declaration of variables and constants before use. i.e. int x; x=3; Calling functions that exist (predefined in a library or defined by the user) i.e. n = Max(4,7); int Max(int x, int y) { int z; if(x > y) z = x; else z = y; return z; } 24
  • 25. STATIC SEMANTICS 2 5 Passing parameters properly. Type checking, i.e. int x, y; x= 3; y = 2.5; performs an error, cause 2.5 is not int it is float data type. Static semantics can not be checked bythe parser. 25
  • 26. Symbol table • symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is associated with information relating to its declaration or appearance in the source. • Symbol table stores the information related about the symbol. • During early phases (lexical and syntax analysis) symbols are discovered and put into the symbol table • During later phases symbols are looked up to validate their usage. 26
  • 27. 27 Symbol Table • A “Dictionary” that maps names to info the compiler knows about that name. • What names? – Variable and procedure names – Literal constants and strings • What info? Textual name Data type Declaring procedure Lexical level of declaration If array, number and size of dimensions If procedure, number and type of parameters
  • 28. Symbol Table Management • Typical symbol table activities: 1) To store the names of all entities in a structured form at one place. 2) To verify if a variable has been declared. 3) To implement type checking, by verifying assignments and expressions in the source code are semantically correct. 4) To determine the scope of a name (scope resolution). 5) Add a new name 6) Add information for a name 7) Access information for a name 8) Determine if a name is present in the table 9) Remove a name 28
  • 29. 29
  • 30. Optimizers • Intermediate code is examined and improved. • Can be simple: – changing “a:=a+1” to “increment a” – changing “3*5” to “15” • Can be complicated: – reorganizing data and data accesses for cache efficiency • Optimization can improve running time by orders of magnitude, often also decreasing program size. 30
  • 31. Code Generation • Generation of “real executable code” for a particular target machine. • It is completed by the Final Assembly phase • Final output can either be – assembly language for the target machine – object code ready for linking 31
  • 32. 32 Compilation process Source code (character stream) Lexical analysis Parsing Token stream Abstract syntax tree (AST) Semantic Analysis if (b == 0) a = b; if ( b ) a = b ;0== if == b 0 = a b if == int b int 0 = int a lvalue int b boolean Decorated AST int ; ;
  • 33. 33 Compilation process Intermediate Code Generation Optimization Code generation if == int b int 0 = int a lvalue int b boolean int ; CJUMP == MEM fp 8 + CONST MOVE 0 MEM MEM fp 4 fp 8 NOP + + CJUMP == CONST MOVE 0 DX CX NOPCX CMP CX, 0 CMOVZ DX,CX
  • 35. Why Backus-Naur form (BNF) • BNF is a metalanguage which is used to explain computer languages. • In the world of computing, there are several widely used metalanguages are Backus Naur Form (BNF), Extended Backus Naur Form (EBNF), Augmented Backus Naur Form (ABNF). BNF is essential in compiler construction 35
  • 36. Backus-Naur form (BNF) • BNF is a meta-language. A meta-language is a language that is used to describe other languages. The Backus Naur Form is designed in a set of derivation rules expressed as, • <symbol> ::= __expression__ • We describe BNF first, and then we show how it can be used to describe the syntax of a simple programming language. • The symbols • ::=, < , > , * , + , ( , ) , and | • are symbols of the metalanguage: they are metasymbols. 36
  • 37. BNF symbols • < > indicate a nonterminal that needs to be further expanded, e.g. <variable> • Symbols not enclosed in < > are terminals; they represent themselves, e.g. if, while, • The symbol ::= means is defined as • The symbol | means or; it separates alternatives, 37
  • 38. • <integer> ::= <digit> | <digit><digit> • Here, both <integer> and <digit> are Non- Terminals and will give an output like, • <integer> ::= 5 • <integer> ::= 86 38
  • 39. BNF for as language descriptor • <program> ::= <stmts> <stmts> ::= <stmt> <stmts> ::= <stmnt> ; <stmnts> • <stmt> ::= <var> = <expr> • <var> ::= a | b | c | d • <expr> ::= <term> + <term> | <term> - <term> • <term> ::= <var> | const 39
  • 40. • e.g1. <while_stmt> ::= while <logic_expr> do <stmt> • This is a rule; it describes the structure of a while statement. • e.g2. • if-then-else-statement ::= if <test> then <statement> else <statement> • This is a rule; it describes the structure of if statement 40
  • 41. BNF and Parse Trees <program> <stmts> <stmt> <var> = <expr> a <term> + <term> <var> const b A parse tree is a hierarchical representation of BNF 41
  • 42. 42 BNF and Parsing source file Scanner Parser input stream parse tree sum = x1 + x2; sum = x1 + x2 ; sum = + x1 x2 tokens Regular expressions define tokens BNF rules define grammar elements
  • 44. Imperative programming • Imperative programming based on Von Neumann’s computer model. It describes a sequence of steps that change the state of the computer. • Imperative programming explicitly tells the computer "how" to accomplish a specific task . 44
  • 45.
  • 46. Comparing imperative, functional and object oriented paradigms 46
  • 47.
  • 48. What is a Type? • A type is a qualifier that is used by the compiler  Machine languages do not have types • The type of a variable or constant tells the compiler: – How much space the object occupies – What operations on the object mean
  • 49. What is a Type? • Given an address in RAM, what does it mean?  Could be anything! • Types tell the compiler – Which instruction to apply Integer addition, floating pt addition – How to increment pointers Array references, fields
  • 50. Data Types  Data Type:  In computer science and computer programming, a data type or simply type is a classification identifying one of various types of data, A data type is used to: Identify the type of a variable when the variable is declared Identify the type of the return value of a function Identify the type of a parameter expected by a function  Types of Data Type:  primitive data types  non-primitive data types 50
  • 51. • Primitive Data Type: include floating-point, integer, enumerated type, double and many other topics from this portion. • Non Primitive Data Type consists of: • Composite Data Type: It may includes array, union, record and tagged union data type. • Abstract Data Type: Like stack, queue, graph, tree etc. 51
  • 52. 52
  • 53. Data Type Examples • Predefined: – type: int – elements: …, -2, -1, 0, 1, 2, … – operations: +, -, *, /, %, … • User-defined: – type: complex – elements: 1+3i, -5+8i, … – operations: newComplex, add, distance, … 53
  • 54. • Other examples of data types • Boolean (e.g., True or False) • Character (e.g., a) • Date (e.g., 03/01/2016) • Double (e.g., 1.79769313486232E308) • Floating-point number (e.g., 1.234) • Integer (e.g., 1234) • Long (e.g., 123456789) • Short (e.g., 0) • String (e.g., abcd) • Void (e.g., no data) 54
  • 55. Size and Range of Integer Data 55
  • 56. Decimal Integer  It consists of 0-9 digits, preceded by an optional – or + sign.  Valid example of decimal integer are : 123 , -321, 0 , 654321, +78  Embedded spaces, comma and non digit characters are not permitted between digits.  15 750, 20,000, $1000 are Illegal 56
  • 57. Floating Point Types  Floating point numbers are stored in 32 bits with 6 digits of precision.  When the accuracy provided by float is not sufficient double data type is used. It uses 64 bits giving a precision of 14 digits.  When you want to extend more precision you can use the long double data type. It uses 80 bits 57
  • 58. Void Types  Void type has no values.  Void type does not return any values.  These are used to specify the return values from the function when they don‟t have any value to return 58
  • 60. 60
  • 61. 61
  • 62. 62
  • 64. Records • A (possibly heterogeneous) aggregate of data elements in which the individual elements are identified by names 64
  • 65. Pointers int x = 20; int *p; p = &x; *p = 20; Declares a pointer to an integer & is address operator gets address of x * dereference operator gets value at p 65 A pointer is a variable holding an address value
  • 66. Pointers int x = 20; int *p; p = &x; *p = 20; *p refers to the value stored in x. p x20 A pointer is a variable holding an address value 66
  • 67. Declarations • Constants and variables must be declared before they can be used. • A constant declaration specifies the type, the name and the value of the constant. • A variable declaration specified the name and possibly the initial value of the variable. • When you declare a constant or a variable, the compiler 1. Reserves a memory location in which to store the value of the constant or variable. 2. Associates the name of the constant or variable with the memory location. (You will use this name for referring to the constant or variable.) 67
  • 68.
  • 69. Variables • A variable is an abstraction of a memory cell • Variables can be characterized by several attributes: – Name – Address – Value – Type – Lifetime – Scope
  • 70. Variables • Address – the memory address with which it is associated – A variable may have different addresses at different times during execution – e.g., local variables in subprograms – A variable may have different addresses at different places in a program – e.g., variable allocated from the runtime stack – Aliases • If two variable names can be used to access the same memory location • harmful to readability (program readers must remember all of them) • How aliases can be created: – Pointers, reference variables, Pascal variant records, C and C++ unions, and FORTRAN EQUIVALENCE
  • 71. Variables • Type – determines the range of values of variables and the set of operations that are defined for values of that type • int type in Java specifies a value range of –2147483648 to 2147483647 and arithmetic operations for addition, subtraction, division, etc – in the case of floating point, type also determines the precision (single or double)
  • 72. Variables • Value – the contents of the memory cells with which the variable is associated – Abstract memory cell - the physical cell or collection of cells associated with a variable • The l-value of a variable is its address • The r-value of a variable is its value
  • 73. slide 73 Variables: Locations and Values • When a variable is declared, it is bound to some memory location and becomes its identifier – Location could be in global, heap, or stack storage • l-value: memory location (address) • r-value: value stored at the memory location identified by l-value • Assignment: A (target) = B (expression) – Destructive update: overwrites the memory location identified by A with a value of expression B
  • 74. slide 74 Variables and Assignment • On the RHS of an assignment, use the variable’s r-value; on the LHS, use its l-value – Example: x = x+1 – Meaning: “get r-value of x, add 1, store the result into the l-value of x” • Example: x=x*y means “compute rval(x)*rval(y) and store it in lval(x)”
  • 75.
  • 77. Introduction • The central feature of imperative languages are variables • Variables are abstractions for memory cells in a Von Neumann architecture computer • Attributes of variables – Name, Type, Address, Value, … • Other important concepts – Binding and Binding times – Strong typing – Type compatibility rules – Scoping rules 77
  • 78. Preliminaries • Name: representation for something else – E.g.: identifiers, some symbols • Binding: association between two things; – Name and the thing that it names • Scope of binding: part of (textual) program that binding is active • Binding time: point at which binding created – Generally: point at which any implementation decision is made. 78
  • 79. Names (Identifiers) • Names are not only associated with variables – Also associated with labels, subprograms, formal parameters, and other program constructs • Design issues for names: – Maximum length? – Are connector characters allowed? (“_”) – Are names case sensitive? – Are the special words: reserved words or keywords? 79
  • 80. Names • Length – Language examples: • FORTRAN I: maximum 6 • COBOL: maximum 30 • FORTRAN 90 and ANSI C (1989): maximum 31 – Ansi C (1989): no length limitation, but only first 31 chars significant • Ada and Java: no limit, and all are significant • C++: no limit, but implementors often impose one • Connector characters – C, C++, and Perl allows “_” character in identifier names – Fortran 77 allows spaces in identifier names: Sum Of Salaries and SumOfSalaries refer to the same identifier 80
  • 81. Names • Case sensitivity – C, C++, and Java names are case sensitive – Disadvantages: • readability (names that look alike are different) • writability (must remember exact spelling) – Java: predefined names are mixed case (e.g. IndexOutOfBoundsException) – Earlier versions of Fortran use only uppercase letters for names 81
  • 82. Case Sensitive or Case Insensitive? foobar == FooBar == FOOBAR ? C-basedlanguages:case sensitive C convention: variable namesonly lower caseletters Pascal:case insensitive Javaconvention: CamelCaseinstead ofunder_scores 82
  • 83. Names • Special words – Make program more readable by naming actions to be performed and to separate syntactic entities of programs – A reserved word is a special word that cannot be used as a user-defined name 83
  • 84. Special Words keyword:identifier with special meaningin certaincontexts reserved word: specialword that cannot beusedasaname Integer Apple Integer = 4 type name Fortran Integer Real Real Integerpackage example; class User { private String name; public String get_name { return name; } } Java 84
  • 85. Binding • 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
  • 86. 86
  • 87. Binding Times • Possible binding times: 1. Language design time e.g., bind operator symbols to operations 2. Language implementation time e.g., bind floating point type to a representation 3. Compile time e.g., bind a variable to a type in C or Java 4. Load time e.g., bind a FORTRAN 77 variable to a memory cell (or a C static variable) 5. Runtime e.g., bind a nonstatic local variable to a memory cell 87
  • 88. 88
  • 89. Storage Binding • Storage Bindings – Allocation • getting a cell from some pool of available memory cells – Deallocation • putting a cell back into the pool of memory cells • Lifetime of a variable is the time during which it is bound to a particular memory cell – 4 types of variables (based on lifetime of storage binding) • Static • Stack-dynamic • Explicit heap-dynamic • Implicit heap-dynamic 89
  • 90. 90 Type Systems • A language’s type system specifies which operations are valid for which types • The goal of type checking is to ensure that operations are used with the correct types – Enforces intended interpretation of values, because nothing else will! • Type systems provide a concise formalization of the semantic checking rules
  • 91. Type Checking • Type checking ensures that the operands and the operator are of compatible types • Generalized to include subprograms and assignments • Compatible type is either – legal for the operator, or – language rules allow it to be converted to a legal type • Coercion – Automatic conversion • Type error – Application of an operator to an operand of incorrect type • Nearly all type checking can be static for static type bindings • Type checking must be dynamic for dynamic type bindings 91
  • 92. 92 Kinds of Type Checking • Three kinds of languages: – Statically typed: All or almost all checking of types is done as part of compilation (C, Java, Cool) – Dynamically typed: Almost all checking of types is done as part of program execution (Scheme) – Untyped: No type checking (machine code)
  • 93. 93
  • 94. Also called lexicalscoping. Ifa variable name's scope isa certain function, then itsscope isthe program textof the function definition:withinthat text, the variable name exists, and is bound to itsvariable, but outside that text, the variable name does not exist. 94
  • 95. Indynamic scoping (ordynamic scope), ifa variable name's scope is a certain function, then its scopeisthe time-period duringwhich the function is executing. While the function isrunning,the variable name exists, and isbound to itsvariable, but after the function returns,the variable name does not exist. 95
  • 97. LHS and RHS • LHS = Left Hand Side  Means replace contents  Set value where this thing is stored • RHS = Right Hand Side – Means value – Evaluate expression, function, etc. – Arrive at a value to store in LHS
  • 98. Constants • Fixed values such as numbers, letters, and strings are called “constants” - because their value does not change • Numeric constants are as you expect • String constants use single-quotes (') or double-quotes (") >>> print 123 123 >>> print 98.6 98.6 >>> print 'Hello world' Hello world 98
  • 99.
  • 100. Sentences or Lines x = 2 x = x + 2 print x Variable Operator Constant Reserved Word Assignment Statement Assignment with expression Print statement 100
  • 101. Assignment Statements • We assign a value to a variable using the assignment statement (=) • An assignment statement consists of an expression on the right hand side and a variable to store the result x = 3.9 * x * ( 1 - x ) 101
  • 102. x = 3.9 * x * ( 1 - x ) 0.6x Right side is an expression. Once expression is evaluated, the result is placed in (assigned to) x. 0.6 0.6 0.4 0.93 A variable is a memory location used to store a value (0.6). 102
  • 103. x = 3.9 * x * ( 1 - x ) 0.6 0.93x Right side is an expression. Once expression is evaluated, the result is placed in (assigned to) the variable on the left side (i.e. x). 0.93 A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.93). 103
  • 104. Order of Evaluation • When we string operators together - it must know which one to do first • This is called “operator precedence” • Which operator “takes precedence” over the others x = 1 + 2 * 3 - 4 / 5 ** 6 104
  • 105. Operator Precedence Rules • Highest precedence rule to lowest precedence rule • Parenthesis are always respected • Exponentiation (raise to a power) • Multiplication, Division, and Remainder • Addition and Subtraction • Left to right Parenthesis Power Multiplication Addition Left to Right 105
  • 106. Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> 106
  • 107. Parenthesis Power Multiplication Addition Left to Right >>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 Note 8/4 goes before 4*5 because of the left-right rule. 107
  • 108. 108
  • 110. Arithmetic Expressions can either be integer expressions or real expressions. Sometimes a mixed expressions can also be formed which is a mixer of real and integer expressions. 110
  • 111. Expressions • An expression is a sequence of operands and operators that reduces to a single value. – Example: 2 * 5 • Operators – An operator is a language-specific syntactical token that requires an action to be taken. • Operand – A operand receives an operator’s action. – The operands of multiply are the multiplier and the multiplicand. 111
  • 112. => OPERATORS: “An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables” =>The objects of the operation(s) are referred to as Operands. Ex: a + b operands Operator 112
  • 113. Example ---------------------- 3 + 5 2 - 4 Num * 5 Sum / Count Count % 4 ----------------------- Count ++ Count -- Operator ---------------- + - * / % ---------- ++ -- Definition ---------------- Addition Subtraction Multiplication Division (quotient) Division (remainder) ----------------------- Increment Decrement Arithmetic operators 113
  • 114. Meaning ---------------------- Store 5 in Num Num = Num + 5 Num = Num - 5 Num = Num * 5 Num = Num / 5 Num = Num % 5 Operator ---------------- == += -= *= /= %= Example ---------------- Num = 5 Num += 5 Num -= 5 Num *= 5 Num /= 5 Num %= 5 Assignment operators 114
  • 115. • Integer Expressions are formed by connecting integer constants and/or integer variables using integer arithmetic operators. • The following are valid integer expressions : • int I,J,K,X,Y,Z,count; • A) k - x • B) k + x – y + count • C) –j + k * y • D) z % y 115
  • 116. • Real Expressions are formed by connecting real constants and/or real variables using real arithmetic operators. • The following are valid real expressions: • float qty,amount,,value; • double fin,inter; const bal=250.53; • i) qty/amount • ii) (amount + qty*value)-bal • iii) fin + qty* inter • iv) inter – (qty * value) + fin 116
  • 117. The process of converting one predefined type into another is called Type Conversion. C++ facilitates the type conversion . 117
  • 118. Boolean expression • Boolean expression is used expression in a programming language that produces a Boolean value when evaluated, that is one of true or false. • A Boolean expression may be composed of a combination of the Boolean constants true or false, Boolean-typed variables, Boolean-valued operators, and Boolean-valued functions. 118
  • 119. Example ---------------------- ! ( Num1 < Num2 ) (Num1 < 5 ) && (Num2 > 10 ) (Num1 < 5 ) || (Num2 > 10 ) Operator ---------------- ! && || Definition ---------------- NOT AND OR Logical operators 119
  • 120. 120
  • 121. Example ---------------------- Num1 < 5 Num1 <= 5 Num2 > 3 Num2 >= 3 Num1 == Num2 Num1 != Num2 Operator ---------------- < <= > >= == != Definition ---------------- Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to Relational operators 121
  • 122. End of Part 2 122
  翻译: