Transcript Slide 1

Elements of C++ Programs
‫محمد ناجى‬/‫د‬
C++ is a high level language. A program called a compiler
translates C++ programs into machine language program
called (object program). A program in a high-level language
is called a source program. After compilation the object
program is linked with external files or library files through
linker resulting in an executable file (with extension exe)
which can be run directly at any computer.
linker
compiler
Source program
Object program
Exe file
1
2
The C++ Character set:
C++ uses the letters A to Z (both upper-and lowercase), the
digits 0 to 9, and a certain set of special symbols like
{ } ( ) [ ] # // “ ‘ = < > << >> + - * / % -++ += -= *= /= %= <= >= == != && || ! &
, ;
Reserved Words
There are certain reserved words that have special
meaning to the C++ compiler and can not be used or
redefined by the programmer for any purpose other that
meaning. All C++ reserved words use only lowercase
letters.
For example: int – do - return - char - goto - if - else - false are reserved words.
3
Naming program elements: Identifiers:
Identifiers are used in C++ to name things such as variables
and functions.
Syntax rules for identifiers:
1- an identifier must start with a letter.
2- an identifier must consist only of a combination of letters
and digits. Special characters, except the underscore
( _ ), are not allowed
3- a C++ reserved word can not be used as an identifier.
4- if an identifier is longer than 1024 characters, only the first
1024 are valid
5- C++ is a case-sensitive language. Uppercase and
lowercase are different.
Here are some examples of valid identifiers:
Area a
a_s
d12e exam_1_final
Here are some examples of invalid identifiers:
2morrow
max Time
Identifier must start with a letter
Blanks are not allowed in identifiers.
box-40
Minus sign (-) is not allowed
cost_in_$
Special symbols such as $ are not allowed
int
Int is reserved word.
two*four
Joe’s
Character * is not allowed.
Character ’ is not allowed.
c++
Plus sign (+) is not allowed.
4
Data and Data Types
There are five predefined data types:
1- Integer (for integers)
2- Float (for real numbers having decimal points)
3- Boolean (for values of True and False)
4- Char (for single character value)
5- String (for representing sequences of characters)
5
1- The Integer (int) Data Type
6
An integer (int) contains neither a decimal point nor an
exponent.
Several valid integer numbers are shown below
25 11
-76
654
0
1
+653
-896
The following integer numbers are invalid for the reasons stated
12,87
76.98
10 30
Commas are not allowed.
A decimal point can not appear in an integer
number
Blank spaces are not allowed.
2E10
An exponent is not allowed
- 34
Blank spaces are not allowed between the
sign and the number
7
The range of int values for 16 bit width is from -32768 to
32767, but the range for 32 bit width is from -2147483648
to 2147483647.
2- The Floating-Point (Float) Data Type
Floating-point numbers have an integer part and a fractional
part, with a decimal point in between. Either the integer part
or the fractional part, but not both, may be missing.
Several valid floating point numbers are
shown below:
20.0
110.25
0.35
-245.12
45.
.87
+2.58
-.25
The following floating-point numbers are invalid for the
reasons stated.
78,542
Commas are not allowed.
-
4.25
Blank spaces are not allowed between the sign
and the number.
Floating Point values can have an exponent. A number like
5.346 x 1014 can be written as 5.346E14. The letter E means
“ times 10 to the power of”. The number preceding the
letter E does not need to include a decimal form. The
exponent itself must be either a positive or negative integer.
Example:
The number 3.8 x 1020 can be written as
3.8E+20
3.8E20
0.38E21
38E19
8
9
The following floating-point numbers are not valid for the
reasons stated.
9E4.3
-16E4.
8.3 E 4
The exponent must be an integer
The exponent must be an integer
Blank spaces are not allowed.
The magnitude of a floating-point number can range
from a minimum value of approximately 3.4E-38 to a
maximum value 3.4E38.
10
3- The Character (char) Data Type
Data type Char represents an individual character value
such as, a letter, a digit, or a special symbol:
‘B’
‘b’
‘3’
‘+’
‘*’
‘&’
‘#’
‘‘
We can perform the common arithmetic operations on the
type Char data. This means that if i is an integer variable,
then the statement:
i = ‘A’ + ’B’ will result in the number 195 to be stored in i
because the ASCII for A is 97, while the ASCII for B is 98
We can compare characters. For example we can write
‘B’ > ‘A’ since A comes before B in the ASCII character set.
Also, we can write ‘a’ > ‘A’ since the uppercase letters
comes before the lowercase letters in the ASCII character
set.
4- The String Data Type
A string is a sequence of characters, such as name,
word, or sentence, enclosed in double quotes.
When entering a string value to be read by a program,
omit the double quotes.
For example, the following are strings in C++:
“computer programming” “speed” “76554” “Box#20”
“(a+b)/(c+d)”
In C++ a string must be entered entirely on one line. If we
split a string in more than one line, the C++ compiler issues
an error message at the first line in the form
“UNTERMINATED STRING”
11
12
5- The boolean (bool) Data Type
The Boolean data type consists of just two possible values:
True and False.
In C++, True is represented by 1, while false is
represented by 0. in C++ all values other than zero are
considered true. We can perform arithmetic operations
on Boolean data type. In addition, this data can not be
read in, but it can be printed out.
If i is an integer variable The statement
i = false + true
will result in 1 to be stored in i (false means zero and True
means one).
13
Declarations:
By using declaration we tell the computer what an identifier
represents.
In general, declaration falls into two classes:
Constant declaration and variable declarations
As a general rule in C++ you must declare or define every
identifier (constant or variable) before it is used. It is
considered good practice to group and put all constant
declarations before the main function heading, and
variable declarations afterwards, at the beginning or
within the body of main function.
14
A- Constant Declarations:
The general form of a constant declaration is expressed as
follows:
Const Data Type
Name = value;
Example:
Const float pi = 3.14159;
Cons int psum = 300;
[value is 300]
Const int nsum = - psum + 5
[value is -295]
Const char star = ‘*’;
[value is symbol *]
Const string month = “may”;
[value is string may]
Const bool flag = true;
Int main()
B- variable Declarations:
The general form of a variable declaration is expressed as
follows:
Data type Name ;
Or if there are several variables of the same type, the
general form is:
Data Type Name1, Name2,……., NameN;
For example if we need to define three float variables x, y,
and z, we can declare each variable with a separate
statement as follows:
Float x;
Float y;
Float z;
15
16
We can declare them in one statement:
Float x, y, z ;
Example
Main int ()
{
Int number , total_mark;
Float length , width;
String month ;
Char flag ;
The following declarations give some examples of invalid
declarations:
a) Int a,b,c;
float a,d;
b) Const int k = 10 ;
Int I, j, k ;
No identifier can have
more than one declaration.
No identifier can have
more than one declaration
c) Const float else = 13.6 ;
Else is a reserved word
d) Const char ch = “May” ;
Ch is a character while
“May” is a string.
17
Assignment statements:
The general form is:
Variable = expression ;
The assignment
operator
Can be constant, another variable
or the result of an operation or
some operations.
When an assignment statement is executed, the expression
on the right-hand side of the assignment operator is
evaluated, and the result is assigned to the variable on the
left hand side
18
19
In general, the variable type on the left-hand side of the
assignment operator should be of the same type as the item
on the right hand side
Example:
Int num1, num2 ;
Float x, y ;
Char ch ;
The following are appropriate assignment statements:
Num1 = 23; num2 = 34 ;
X = 34.6 ;
ch = ‘f’ ;
y = 43.9 ;
20
Type correction:
Storing an integer number into a float variable generally
does not cause loss of information. An integer number
such as 34 can be represented in float form as 34.0. on
the other hand, storing a float number, such as 23.8, into
an integer variable can cause loss of information because
the signed number will be 23
21
For example, if we consider the declaration:
Float x ;
Int y ;
If we write the following assignment in a program:
X = 19 ;
Y = 46.9 ;
These statements cause type correction. As a result, x is
assigned the value 19.0, while y is assigned the value 46
22
Example:
Given the variable declarations:
Int
num, mark ;
float rate ;
bool test ;
char ch ;
string name ;
Consider The following assignments
23
Valid. ‘d’ will be stored in ch (ASCII of d is 100)
ch = 100 ;
Test = ‘B’ ;
Valid. Test is true since ASCII of B is 66 (any
value other than zero will be converted to one)
Ch = s ;
Invalid. Undeclared identifier (s)
num = “true” ;
Invalid. C++ can not convert string to integer
Ch = “firstn” ;
Invalid. C++ can not convert string to character
6.8 = rate ;
Invalid.only a variable can appear on the left of =
Num + 5 = mark ;
Invalid. only a variable can appear on the
left of =
Z = rate ;
Invalid. Z is Undeclared identifier
Rate = 2E3.5
Invalid. The exponent must be an integer
24
Expressions:
Arithmetic expression
Boolean expression
Arithmetic expression
Simple Arithmetic
expression
Compound Arithmetic
expression
25
a- Simple arithmetic expressions
operator
meaning
+
addition
-
subtraction
*
multiplication
/
Division
%
modulus
26
Examples:
8 + 3 = 11
(integer + integer = integer)
6.3 + 3.4 = 9.7 (float + float = float)
8 + 2.4 = 10.4 (integer + float = float)
10 – 7 = 3 (integer – integer = integer)
9.4 – 3.1 = 6.3 (float – float = float)
5.8 – 2 = 3.8 (float – integer = float)
5 * 4 = 20 (integer * integer = integer)
1.2 * 1.1 = 1.32 (float * float = float)
2.2 * 4 = 8.8 (float * integer = float)
27
Integer division:
16 / 3 = 5 (integer / integer = integer)
Float division:
1.32 / 1.1 = 1.2 (float / float = float)
3.3 / 3 = 1.1 (float / integer = float)
10 / 2.5 = 4.0 (integer / float = float)
Modulus:(for integers only)
17 % 5 = 2
(17 / 5= 3
3 * 5 =15
17 – 15 = 2)
5%7=5
(5 / 7 = 0
0*7=0
5 – 0 = 5)
9%0
(error)
3.2 % 2
(error)
(3.2 is float)
28
Increment and decrement operators:
++
increment
--
decrement
There are unary operators that take a single variable
name as an operand. We can use them only on
variables, not on constants or expressions.
The ++ and – operators can be applied either in a prefix
position (before the variable) as in
++count ;
or
--count
Or in a postfix position (after the variable), as in
Count++ ;
or
count-- ;
29
++count ; (or count++ ;) is equivalent to the statement
count = count +1 ;
--count ; (or count-- ;) is equivalent to the statement
count = count – 1 ;
We must be careful when using the increment and decrement in
statements. If the ++ or – operator is in a prefix position, the
variable is modified, and then the new value is used in
evaluating the rest of the expression.
On the other hand, if these operators are in a postfix position,
the old value of the variable is used to evaluate the rest of the
expression. For example:
a = 10 ;
b = --a ;
will result:
a = 9 and b = 9
a = 10 ;
b = a-- ; the result will be: a = 9 and b = 10
30
Example:
If the values of the integer variables m and n are 25 and 7
m % n++ evaluates to 25 % (7++) = 25 % 7 = 4
m % ++n evaluates to 25 % (++7) = 25 % 8 = 1
++m – n-- evaluates to (++25) – (7--) = 26 – 7 = 19
31
Example:
Write a single statement, using the increment or
decrement operators which is equivalent to each of
the following pair of statements:
a. z = x – y;
b. x = x + 1 ;
x=x+1;
z=x–y;
c. x = x – 1 ;
d. z = x – y ;
z=x–y;
x=x–1;
Solution:
a. z = x++ - y ;
b. z = ++x – y ;
c. z = --x – y ;
d. z = x-- - y ;
32
Abbreviated assignment operators:
C++ allows simple assignment statements to be
abbreviated. In fact any statement in the form”
Identifier = identifier operator expression ;
Can be written as abbreviated assignment statement in
the form:
Identifier operator = expression ;
33
The following table shows all the available abbreviated
assignment operators in C++
Operator
Example
Equivalent statement
+=
x += 3 ;
x=x+3;
-=
x -= 3 ;
x=x–3;
*=
x *= y ;
x=x*y
/=
x /= y ;
x=x/y;
%=
x %= y ;
x=x%y;
34
B- compound arithmetic expressions:
When an expression contains multiple arithmetic and
assignment operators, it becomes necessary to specify the
order in which the various operations are carried out.
The precedence groups of different operators and their
associatively are given in the following table:
precedence
operator
Associatively
1
Parentheses: ()
Innermost first
2
++ --
Right to left
3
* / %
Left to right
4
+ -
Left to right
5
= += -= *= /= %=
Right to left
35
The following table contains some examples of
compound arithmetic expressions:
1.
2.
3.
ab
 xy
cd
6
xy
z2  4
x
 2a
a mod b
(a + b) / (c + d) + x * y
x * pow(y,6) /(z * z + 4)
X / (a % b) – 2 * a
C++ rules for evaluating compound arithmetic
expressions
36
A. parentheses rule: nested parentheses expressions must
be evaluated from the inside out. With the innermost expression
evaluated first.
‫فى حالة وجود أقواس متداخلة فإنه ينفذ التعبيرات فى األقواس الداخلية أوال ثم ينتقل الى‬
(‫األقواس الخارجية)يتحرك من الداخل الى الخارج‬
Left associative rule: operators in the same expression and
at the same precedence level (such as * and /) are evaluated
from left to right.
‫اذا تساوت أولويتان فإنه ينفذ من اليسار الى اليمين‬
Arithmetic operators can not appear consecutively. For
example a*-b is not allowed, but a*(-b) is valid.
‫المعامالت الحسابية ال يمكن أن تظهر بالتتابع ولكن يمكن استخدام األقواس للفصل بينهما‬
Arithmetic operators can not be implied. Thus, the
expression 4x + 8y is incorrect, but the expression
4*x+8*y is valid
Example: calculate the values of the following
expressions:
(a)17 % 5 + ++x / 2 + 10 – 3
(b) 5.0 *(2.0 / (4.0 *2.0))
(c) (50 / 4) % (7 % 7)
where x= 7
37
38
Solution:
(a) 17 % 5 + ++x/2 + 10 – 3
1) 8
1
2) 2
3) 4
2
4) 6
3
5) 16
6) 13
4
5
6
Final result
39
(b) 5.0 *(2.0 / (4.0 *2.0))
1
1) 8.0
2) 0.25
3) 1.25
2
3
40
c) (50 / 4) % (7 % 7)
1) 12
2) 0
1
2
3) Error
3
41
Boolean Expressions:
Boolean Expressions is an expression whose value is either
True or False.
a. Boolean Expressions with relational operators.
The general form of these expressions is:
Arithmetic expression
Relational
Arithmetic expression
Or variable or constant
operator
Or variable or constant
42
Relational operators in C++ are shown in the following list:
Relational Operator
Meaning
==
Equal to
!=
Not equal to
<
Less than
<=
Less or equal
>
Greater than
>=
Greater or equal to
43
Example
Suppose that i and j are integer-type variables where
i = 5 and j = -3
Several Boolean expressions are shown below.
Expression
J != -2
Value
True
I + 2.5 < j + 11
True
i + j == 10
False
i * j = = -15
Error (since blanks are not
allowed to separate a two
character operator
Note: there is no need to enclose each expression in
parentheses because the arithmetic operators have higher
precedence than the relational operators.
b. Boolean Expressions with logical operators: 44
We can form more complicated Boolean
expressions by using the following three logical
operators:
Logical operator
Meaning
&&
and
||
or
!
not
45
The result of the Boolean expression is either True or
False. The (&&) and (||) operators are binary (two
operand) operators. The (!) Operator is a unary (oneoperand) operator.
The following tables summarize the results of applying &&
, || and ! To Boolean values (Truth tables)
x
True
True
False
False
y
True
False
True
False
X && y
True
False
False
False
46
x
True
True
False
False
x
true
false
y
True
False
True
False
X || y
True
True
True
False
!x
false
true
Precedence of all operators:
Precedence
1
2
3
4
5
6
7
8
9
operator
()
++ -- !
* / %
+ < <= > >=
== !=
&&
||
= += -= *= /= %=
47
Associatively
Innermost first
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
48
Example:
The values for the variables x, y, z, and test are given by:
x = 4.0 y = 7.0 z = 3.0
test = false.
Write the sequence of computation steps to find the final result
for each of the following Boolean expressions:
1) ++x * y
2) !Test || ((y+z) <= (x – z))
3) !x == y + 4 * x
49
Solution:
1)++x * y
1) 5.0
2) 35.0
1
2
2) !Test || ((y+z) <= (x – z))
1
2
1) 10.0
2) 1.0
3
4
3) False
4) True
5) True
5
50
51
3) !x == y + 4 * x
1
2
1) False
2) 16.0
3) 23.0
3
4
4) False
52
Hint:
In C++, zero is considered false, and all other values are
considered true, although true is usually represented by
1. Thus if an expression is false, it is equal to zero, and if
an expression is equal to zero, it is false. If a statement is
true, all you know is that it is nonzero, and any nonzero
statement is true.
For example, assume I, j are two integer variables that
contain 2,3 respectively, assume also that k is an integer
variable.
K = i< j ;
1 will be stored in k
K=i>j;
0 will be stored in k
53
The standard library functions in C++
The following table lists the names and the description of
some important C++ standard library functions.
Header
file
function
meaning
Arg.
type
Res.
type
<cmath> fabs(x)
Absolute value of x
float
float
<cstdlib> abs(i)
Absolute value of i
Int
Int
<cmath> sqrt(x)
square root of x (x>=0)
float
float
cmath
Sine of x (in rad)
float
float
sin(x)
54
Header file function
meaning
Arg.
type
Res.
type
<cmath>
cos(x)
cosine of x (in rad)
float
float
<cmath>
tan(x)
Tangent of x (in rad)
float
float
<cmath>
asin(x)
Inverse sine of x (in rad)
float
float
<cmath>
acos(x)
Inverse cosine of x (in rad)
float
float
<cmath>
atan(x)
Inverse tangent of x (in rad)
float
float
<cmath>
exp(x)
Exponent of x (base e)
float
float
<cmath>
sinh(x)
Hyperbolic sine of x
float
float
55
Header file
function
meaning
Arg.
type
Res.
type
<cmath>
cosh(x)
Hyperbolic cosine of x
float
float
<cmath>
tanh(x)
Hyperbolic tangent of x
float
float
<cmath>
log(x)
Natural logarithm of x (base e)
float
float
<cmath>
log10(x)
Common logarithm of x (base
10)
float
float
<cmath>
pow(x,y)
X to the power y
float
float
<cmath>
ceil(x)
Rounds up
float
float
<cmath>
floor(x)
Rounds down
float
float
56
Examples
fabs(-6.5) = 6.5
fabs(-15/4.0) = 3.75
abs(-14)=14
sqrt(4.0)=2.0
sin(2.0)=0.90929
asin(0.90929)=2.0
pow(2,4)=16.0
ceil(3.3)=4.0
ceil(3.7)=4.0
floor(10.2)=10.0
floor(10.8)=10.0
floor(-10.8)=-11.0
to use a standard function place an # include
directive near the top of your program, specifying
the appropriate header file. For example
# include <cmath>
float z ;
Z = sqrt(16.0) * 3 ;