You are on page 1of 42

ECC 3191

COMPUTER PROGRAMMING AND USAGE

Basic Elements for Programming

Dr. Aidi Hizami bin Ales @ Alias


aidihizami@upm.edu.my
03-89466391
Room : 6-34
OUTLINE
• C++ Program Structure

• Formatted Input / Output

• Expression

• Typedef and sizeof operator

• 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

Global declarations int a = 1, b = 2


Example
int main ()
int main () {
{
int c;
Local definitions
c = a + b;
return 0;
Statements
} } \\ main function
• A C++ program is first constructed as a sequence of characters such as:
• Uppercase letter => 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 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

Valid Not Valid


_m not#me
id 102_SOUTH
identifier2 -minus
VARIABLES
• What is a variable?
•Named memory locations
•Have type and size
•Their values can change

• 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

char code; B code

int math; 14 math

long national_debt; 100000000000000national_debt

float payRate; 14.25 payRate

double pi; pi
3.1415926536

Program Memory
STATEMENTS
• Causes an action to be performed in C++ program

• 6 types altogether but focus on the first two

• 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;

•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
area = 3.142; *r*r; (WRONG)

•The correct evaluation is


area = 3.142*r*r;
// Calculate and displays the area and circumference of a circle

#include <iostream>
using namespace std;

int main ()
{
const double PI = 3.14159;
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
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

cin >> variable1 >> variable2 >> variable 3;

• Examples

cin >> first;


cin >> first >> middle >> last;

23-Mar-17
FORMATTED OUTPUT
• Purpose : Display message on the monitor screen

• Syntax

cout << “...” << variable1;

• Examples

cout << “Hello World!\n”;


cout << “The average value is” << ave << “\n”;

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

• left and right


• Left- and right- justified 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: () {} , ;

• Parentheses immediately following main are not punctuator

23-Mar-17
OPERATORS 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

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

• Precedence - determines the priority

• 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

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

• ++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)

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;

Note: ++ and -- cause the value of a variable in memory to change

23-Mar-17
• 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 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

• e.g. typedef char uppercase;


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

• 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

• Syntax: sizeof (object)

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

• e.g. sizeof(int); sizeof(char);

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

You might also like