Sei sulla pagina 1di 44

ECC3005 Computer Programming

Syntax Rules
Dr. Siti Barirah Ahmad Anas
[barirah@upm.edu.my][03-89466439][Room A.04.89]
OUTLINE
Topics
- C++ Program Structure
- Formatted Input/Output
- Expression: Unary & Assignment
- Typedef and sizeof operator
- Arithmetic conversion
- Statement

Learning Outcome
Students are expected to be able to:
- Distinguish between syntax, semantics and run-time error
- Use identifiers to name elements in program
- Use variables to store data, and declare them using numeric data types
- Differentiate between const keyword and #define directives
- Write C++ programs to output message on console, read input from
keyboard and perform simple calculation
- Use operators and punctuators in expression
- Understand precedence and associativity of operators
- Understand implicit and explicit conversion of numeric data type
SYNTAX RULES

• The rules of a programming language are called its syntax


• Misusing the language is called a syntax error. The compiler
will alert you to any syntax errors, all of which must be
corrected
• If you speak the language perfectly, but your instructions
don't generate the correct answer. This is called a semantic or
logic error
• Runtime error cause a program to terminate abnormally, e.g.
wrong input keyed in by the keyboard
C++ PROGRAM STRUCTURE
• A C++ program
– Contains preprocessor directives that tells it how to
prepare program for compilation, e.g. #include
– Made of a global declaration sections with one or more
functions
– Only one function should be named as main

– All functions are divided into 2 sections:


• Definition section
– describe data to be used within the function
– Local definition
• Statement section
– Follows definition section
– Contains set of instructions, called statement
#include <iostream>
Preprocessor directives using namespace std

Global declarations int a = 1, b = 2;

Example
int main () int main ()
{ {

Local definitions int c;

c = a + b;
Statements
return 0;

} } // main function
• A C++ program is first constructed as a sequence of characters
such as:
– uppercase letters => A to Z
– lowercase letters => a to z
– digits => 0 to 9
– special characters => + - * / = ( ) { } [ ]
< > ‘ “ ! # % & _ | ^ ~ \ . , ; : ?
– white space character => blank, newline, tab

• These characters are collected by compiler into syntactic units


called tokens which are: keywords, identifiers, constant,
operators and punctuators.
C++ KEYWORDS
Keywords are reserved words that should not be used for anything other than their
predefined purposes.
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
and and_eq asm bitand bitor
bool catch class compl const_cast
delete dynamic_cast explicit export false
friend inline mutable namespace new
not not_eq operator or or_eq
private protected public reinterpret_cas static_cast
t
template this throw true try
typeid typename using virtual wchar_t
xor xor_eq
IDENTIFIERS

• Composed of a sequence of letters, digits and underscores (_)


• The first character of identifier cannot be a digit
• Cannot be a reserved word
• Case sensitive, e.g. area, Area and AREA are not the same
• Are used for naming variables, functions and other things in
the program
• Use descriptive identifiers (recommended)
• Example

Valid Not valid


_m not#me
id 102_south
identifier2 -minus
VARIABLES

• What is…
– Named memory locations
– Have a type and size
– Their values can be changed

• Declarations
– Used to name an object
– E.g. int radius;
char ch;
double area;
– Variables of the same type can be separated by commas
e.g. int i, j, k;
VARIABLE INITIALIZATION

• Initializer establishes the first value that the variable will contain
• Example:
int count = 0;
int count, sum = 0;
int count = 0, sum = 0;
int count = 0,
int sum = 0;

• A variable must be declared first before assigning a value to it.


• Declarations and definitions can be done separately or at the same time,
e.g. int radius = 5;
• Tips: C++ allows alternative syntax, e.g. int radius(5);
• E.g. declareInitialize.cpp
DATA TYPES

• Defines a set of values and a set of operations that can be


applied on those values

• Standard/fundamental data types


– char, int, double

• Derived types
– Pointer, enumerated type, union, array etc.

• E.g. 3_type.cpp
Variables in Memory

Variable’s Variable’s Variable’s


type Identifier Identifier

char code; B code


14 i
int i;
100000000000000 national_debt
long national_debt;

float payRate; 14.25 payRate

3.1415926536 pi
double pi;

program memory
STATEMENTS

• Causes an action to be performed in C++


program

• 2 types:
– Expression statement
• Expression ended with semicolon
– Compound statement
• Unit of code between the opening and closing braces
CONSTANT

• Represents permanent data that never changes during


program execution
• E.g. in previous example program, p is a constant value,
equals to 3.14159

• Using constant, the syntax is


const datatype CONSTANTNAME = VALUE;
• E.g.
const double PI = 3.14159;

• Must be declared and initialized in the same statement


const keyword and #define directives

• Common error:

#define PI 3.142;
...
area = PI*r*r;

• Actual evaluation is
area = 3.142;*r*r; WHICH IS WRONG…!!!

• The correct evaluation should be


area = 3.142*r*r;
3_constant.cpp

// Calculates and displays the area and circumference of a circle

#include <iostream>
using namespace std;

int main ()
{
const double PI = 3.14159; //try replacing this with #define

double radius, area, circum;

cout << “Enter radius> ”; // Get the circle radius


cin >> radius;

area = PI * radius * radius; // Calculate the area


circum = 2 * PI * radius; // Calculate the circumference

// Display area and circumference


cout << “The area is ” << area << endl;
cout << “The circumference is ” << circum << endl;

return 0;
}
CHARACTER SETS

• Character from the character constant comes from character


set, supplied by hardware manufacturer

• ASCII
– American Standard Code for Information Interchange
– used by most computers

• EBCIDIC
– Extended Binary Coded Decimal Interchange Code
– used only by IBM Mainframes and their clones
Table 1: ASCII Code

E.g. 3_character.cpp
ESCAPE CHARACTERS

Written in C++ Name of character Integer value


\a Alert 7
\\ Backslash 92
\b Backspace 8
\r Carriage return 13
\” Double quote 34
\f Form feed 12
\t Horizontal tab 9
\n Newline 10
\0 Null character 0
\’ Single quote 39
\v Vertical tab 11
E.g. 3_escapeChar.cpp
FORMATTED INPUT/OUTPUT

• Standard input file: keyboard


• Standard output file: monitor
• Information from input and to output file will be buffered in a
storage area

cin >>

Keyboard

Buffer
cout <<
Monitor

Memory
FORMATTED INPUT

• Purpose: read value from one/more variables from the input


• Syntax:

cin >> variable1 >> variable2 >> variable3;

• Examples:

cin >> first;


cin >> first >> middle >> last;

3_computeAverage.cpp
FORMATTED OUTPUT

• Purpose: display message on the monitor screen


• Syntax

cout << “…” << variable1 ;

• Examples

cout << “Hello World!\n”;


cout << “The average value is” << ave << endl;
• Output field can be set using stream manipulators
• Using #include <iomanip> header file
• Frequently used stream manipulators:

Operator Description
setprecision(n) Set precision of floating-point numbers
fixed Displays floating point in fixed-point notation
showpoint Cause floating-point to be displayed with decimal
point
setw(width) Specifies width of print field
left Justifies output to the left
right Justifies output to the right

• E.g. 3_streamManip.cpp
• setprecision(n)
– Specify total number of digits displayed in floating-point numbers
– Example
double num = 12.34567;
cout << setprecision(3);

– Output
12.3

• fixed
– Force a floating point numbers to be displayed in fixed number of digits
– If used with setprecision(n), then the number of digits after the decimal
point can be specified
• showpoint
– Can be used with setprecision(n) to specify the number of digits
after the decimal point
– Numbers are padded with trailing zeroes if there’s no fractional part

• setw(width)
– Specify number of columns of the output

• left and right


– Left- and right-justified the output
OPERATORS AND PUNCTUATORS
• Arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulus

• Equality operators:
== is equal
!= not equal

• Relational operators:
> greater than
< less than
>= greater than or equal
<= less than or equal

• Assignment operator: = , Shorthand assignment operators: += -= *= /= %=


• punctuators: ( ) {} , ;
• parentheses immediately following main are not punctuator
PRECEDENCE AND ASSOCIATIVITY

• Operators have rules of precedence and associativity that


determine precisely how expressions are evaluated.

• Precedence and associativity describe the order in which each


operator is evaluated by the compiler.

• Precedence  determines the priority of evaluation

• Associativity  determines the order in which two or more


operands with the same precedence will be evaluated
Table 2: Operator Precedence and Associativity

Operator Type Operator Execution Order


Primary Expression Operators () [] . -> expr++ expr-- left-to-right
* & + - ! ~ ++expr --expr
Unary Operators right-to-left
(typecast) sizeof()
* / %
+ -
>> <<
< > <= >=
== !=
Binary Operators left-to-right
&
^
|
&&
||
Ternary Operator ?: right-to-left
= += -= *= /= %= >>= <<= &=
Assignment Operators right-to-left
^= !=
Comma , left-to-right
EXAMPLE

• 1+2*3
» the value is 7
» * has higher precedence than +, causing the
multiplication to be performed first, then addition.
• (1 + 2) * 3
» the value is 9
» expressions inside parentheses are evaluated first.

• 1+2–3+4–5
» The value is -1
» binary operators – and + have the same precedence, then
use associativity rule “left to right”

• Refer table 2.
EXPRESSION
• Sequence of operands and operators that reduces to a single value e.g. 2 + 5

• Expression type – primary, unary, binary, etc.

– Primary expressions
• Identifier, constant and parenthetical expression
• E.g. a, 7 and (2 + a - 3)

– Binary expressions
• Formed by operand-operator-operand combination
• E.g. additive : a + 7 and multiplicative: 6 * 2

• Precedence – determines the priority


UNARY EXPRESSION

• Increment operator ++ and decrement operator -- are unary


operators with the same precedence as the unary plus and
minus, associate from right to left.

• Occur in either prefix or postfix position, and different effects


may occur.

• ++i and i++ causes the stored value of i in memory to be


incremented by 1

• ++i  increment i first then do expression (prefix)


• i++  do expression first then increment i (postfix)
• Example 1:
int i = 3, j = 3;
i++; // i becomes 4
j--; // j becomes 2

• Example 2:
int i = 1;
int j = ++i; // i is 2, j is 2

• Example 3:
int i = 1;
int j = i++; // i is 2, j is 1
• Example 4:
int i = 10;
int newNum = 10 * i++; is the same as
int newNum = 10 * i;
i = i + 1;
• Example 5:
int i = 10;
int newNum = 10 * ++i; is the same as
i = i + 1;
int newNum = 10 * i;
• example:
int a, b, c = 0;
a = ++c;
b = c++;
cout << a << b << ++c << c++ << endl;

3_unary.cpp

note: ++ and -- cause the value of a variable in


memory to be changed
EXAMPLE

int a = 3, b = 4, c = 5, x, y;

x = a * 4 + b / 2 - c * b;

y = --a * (3 + b) / 2 - c++ * b;

What is the new value of each variable after executing the


above expressions?
3_unaryEg2.cpp
ASSIGNMENT EXPRESSION

• Evaluates the operand on the right side of the operator (=)


and places the value in the variable on the left
a = b + c;

• Assignment operators:
= += -= /= %= >>= <<= &=
?= |=
– same precedence
– right to left associativity
– changed value of variable
– Left operand must be a single value
• Simple Assignment
– As in algebraic expression
– E.g. a = 5, b = x + 1, i = i + 1

• Compound assignment
– Shorthand notation for a simple expression
– E.g. x *= y equals to x = x * y

• Example
– x *= y + 3 evaluated as x = x * (y + 3)
EXAMPLE

• E.g.1
int a, b = 2, c = 3;
a = b + c;

• E.g. 2
a=b=c=0; equivalent to a=(b=(c=0));
k += 2; k=k+2;
j *= k + 3; j=j * (k+3);
typedef OPERATOR

• allows programmer to associate a type with an identifier

• eg: typedef char uppercase;


typedef int inches;
uppercase u;
inches length, width;

• uses:
– have type names that reflect the intended use
– Example 3_typedef.cpp
sizeof OPERATOR

• a unary operator to find the number of bytes needed to


store an object in memory.

• Syntax: sizeof(object)

• note: object can be a type, expression, an array or


structure type

• eg: sizeof(char) 3_typeSize.cpp


ARITHMETIC CONVERSION
• Used for mixed type expression
– E.g. expression with mixed type int and float

• 2 conversion types
– Implicit type conversion
• Type is automatically converted by C++ program
• Based on the promotion hierarchy

– Explicit type conversion


• Known as casting
• Uses cast expression operator e.g. (int) a
• Type is converted by the programmer
IMPLICIT CONVERSION

Long double

double

float

Unsigned long int

Long int

Unsigned int

int
The Promotion Hierarchy
short

char E.g. 3_implicit.cpp


EXPLICIT CONVERSION

• A.k.a. casting
• Example
– (float) a
– (float) (x + y)
– (float) (a / 10)
– (float) a / 10

• E.g. 3_explicit.cpp

Potrebbero piacerti anche