ECC 3191 Computer Programming and Usage: Basic Elements For Programming
ECC 3191 Computer Programming and Usage: Basic Elements For Programming
• Expression
• Arithmetic Conversion
• Statement
SYNTAX RULES
• The rules of a programming language are called its syntax
• Misusing a 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 correctly, but your instruction doesn`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
Structure of a C++ Program
• 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
• These characters are collected by compiler into units called tokens, which
includes
• Keywords
• Identifiers
• Constant
• Operators
• Punctuators
C++ Keywords
•Keywords are reserved words that should not be used for anything other than
their predefined purposes
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 and AREA are not the same
•Are used for naming variables, functions and other things in the program
•It is recommended to use descriptive identifiers
• Declarations
•Used to name an object
•E.g. int radius;
char c;
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);
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
• Variables in memory
Variable`s
Variable`s Variable`s identifier
Type identifier
double pi; pi
3.1415926536
Program Memory
STATEMENTS
• Causes an action to be performed in C++ program
• 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, pi is a constant value, equals to 3.14159
•Using constant, the syntax is
const datatype CONSTANTNAME = VALUE;
•E.g.
const double PI = 3.14159;
•Common error:
#define PI 3.142;
…….
area = PI*r*r;
•Actual evaluation
area = 3.142; *r*r; (WRONG)
#include <iostream>
using namespace std;
int main ()
{
const double PI = 3.14159;
double radius, area, circum;
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
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 23-Mar-17
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
23-Mar-17
FORMATTED INPUT
• Purpose: read value from one or more variables from the input
• Syntax
• Examples
23-Mar-17
FORMATTED OUTPUT
• Purpose : Display message on the monitor screen
• Syntax
• Examples
23-Mar-17
• Output field can be set uing 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
23-Mar-17
• 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
23-Mar-17
• showpoint
• can be used with setprecision(n) to specify the number of digits after the
decimal point
• Numbers are padded with trailing zeros if there`s no fractional part
• setw (width)
• specify number of columns of the output
23-Mar-17
OPERATORS AND PUNCTUATORS
• Arithmetic operators
+ addition
- subtraction
* multiplication
/ division
% modulus
• Equality operators
== is equal
!= not equal
23-Mar-17
• Relational operators
> greater than
< less than
>= greater than or equal
<= less than or equal
• Punctuators: () {} , ;
23-Mar-17
OPERATORS PRECEDENCE AND
ASSOCIATIVITY
• Operators have rules of precedence and associativity that determine
precisely how expressions are evaluated
• Associativity --> determines the order in which two or more operands with
the same precedence will be evaluated
23-Mar-17
Operator type Operator Execution Order
Primary Expression Operators () [] . -> expr++ expr-- left to right
* & + - ! ~ ++expr --expr
Unary Operators right to left
(typecast) sizeof()
*/%
+-
>> <<
< > <= >=
== !=
Binary Operator left to right
&
^
|
&&
||
Ternary Operators ?: right to left
= += -= *= /= %= >>= <<= &= ^=
Assignment Operators right to left
!=
Comma , left to right 23-Mar-17
• 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”
23-Mar-17
EXPRESSION
• Sequence of operands and operators that reduces to a single value
e.g. 2 + 5
• binary expressions
• Formed by operand-operator-operand combination
• E.g. additive: a + 7, and multiplicative: 6/2
23-Mar-17
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
23-Mar-17
• 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
23-Mar-17
• 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;
23-Mar-17
• Example:
int a, b, c = 0;
a = ++c;
b = c++;
cout << a << b << ++c << c++ << endl;
23-Mar-17
• Example
x = a * 4 + b / 2 - c * b;
y = --a * (3 + b) / 2 - c++ * b;
What is the new value of each variable after eexecuting the above
expressions?
23-Mar-17
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
• change value of variable
• left oeprand must be a single value
23-Mar-17
• 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 is actually equals to x = x * y
• Example
• x *= y + 3 evaluated as x = x * (y + 3)
23-Mar-17
• Example 1
int a, b = 2, c = 3;
a = b + c;
• Example 2
a=b=c=0; equivalent to a=(b=(c=0));
k += 2; k=k+2;
j *= k + 3; j=j * (k+3);
23-Mar-17
typedef OPERATOR
• Allows programmer to associate a type with an identifier
• Uses:
• have type names that reflect the intended use
23-Mar-17
sizeof OPERATOR
• a unary operator to find the number of bytes needed to store an object in
memory
23-Mar-17
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
• e.g. short a=2000;
int b;
b=a;
• Promotional hierarchy
char - short - int - unsigned int - long int - unsigned long int - float - double -
long double
23-Mar-17
• Explicit type conversion
• Known as casting
• Uses cast expression operator
• Type is converted by the programmer
• Example
• (float) a
• (float) (x + y)
• (float) (a / 10)
• (float) a/10
23-Mar-17