Post on 23-Dec-2015
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.
Source program
linker
Exe file
compiler
Object program
1محمد/ دناجى
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.
2
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.
3
Here are some examples of valid identifiers:
Area a a_s d12e exam_1_final
Here are some examples of invalid identifiers:
2morrow Identifier must start with a lettermax Time 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 Character * is not allowed.
Joe’s 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 TypeAn 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 Commas are not allowed.
76.98 A decimal point can not appear in an integer number
10 30 Blank spaces are not allowed.
2E10 An exponent is not allowed
- 34 Blank spaces are not allowed between the sign and the number
6
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
7
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
The following floating-point numbers are not valid for the
reasons stated.
9E4.3 The exponent must be an integer
-16E4. The exponent must be an integer
8.3 E 4 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.
9
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.
10
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
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).
12
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.
13
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()
14
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
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 ;
16
The following declarations give some examples of invalid declarations:
a) Int a,b,c;
float a,d;
No identifier can have more than one declaration.
b) Const int k = 10 ;
Int I, j, k ;
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
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 ; y = 43.9 ;
ch = ‘f’ ;
19
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
20
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
21
Example:
Given the variable declarations:
Int num, mark ;
float rate ;
bool test ;
char ch ;
string name ;
Consider The following assignments
22
ch = 100 ; Valid. ‘d’ will be stored in ch (ASCII of d is 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
23
Expressions:
Arithmetic expression Boolean expression
Arithmetic expression
Simple Arithmetic expression
Compound Arithmetic expression
24
a- Simple arithmetic expressions
operatormeaning
+addition
-subtraction
*multiplication
/Division
%modulus
25
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)
26
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)
27Integer division:
16 / 3 = 5 (integer / integer = integer)
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)
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-- ;
28
++count ; (or count++ ;) is equivalent to the statement
count = count +1 ;
--count ; (or count-- ;) is equivalent to the statement
count = count – 1 ;
29
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 = 9a = 10 ; b = a-- ; the result will be: a = 9 and b = 10
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
30
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 ;
31
Solution:
a. z = x++ - y ; b. z = ++x – y ;
c. z = --x – y ; d. z = x-- - y ;
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 ;
32
OperatorExampleEquivalent 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;
The following table shows all the available abbreviated assignment operators in C++
33
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:
precedenceoperatorAssociatively
1Parentheses() :Innermost first
2-- ++Right to left
3% / *Left to right
4- +Left to right
5=% =/ =* =- =+ = Right to left
34B- compound arithmetic expressions:
The following table contains some examples of compound arithmetic expressions:
1 .)a + b) / (c + d + (x * y
2 .x * pow(y,6) /(z * z + 4)
3. X / (a % b) – 2 * a
xydc
ba
4z
xy2
6
a2bmoda
x
35
36C++ rules for evaluating compound arithmetic expressions
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 where x= 7
(b) 5.0 *(2.0 / (4.0 *2.0))
(c) (50 / 4) % (7 % 7)
37
Solution:
(a) 17 % 5 + ++x/2 + 10 – 3
1
2 3
4
5
6
2) 2
3) 4
4) 6
6) 13 Final result
5) 16
1) 8
38
(b) 5.0 *(2.0 / (4.0 *2.0))
1
2
3
1) 8.0
2) 0.25
3) 1.25
39
c) (50 / 4) % (7 % 7)
1 2
3
1) 12
2) 0
3) Error
40
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
41
Relational operators in C++ are shown in the following list:
Relational OperatorMeaning
==Equal to
!=Not equal to
<Less than
<=Less or equal
>Greater than
>=Greater or equal to
42
Example
Suppose that i and j are integer-type variables where
i = 5 and j = -3
Several Boolean expressions are shown below.
Expression Value
J != -2 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.
43
b. Boolean Expressions with logical operators:
We can form more complicated Boolean expressions by using the following three logical operators:
Logical operatorMeaning
&&and
||or
!not
44
45The result of the Boolean expression is either True or
False. The (&&) and (||) operators are binary (two
operand) operators. The (!) Operator is a unary (one-
operand) operator.
The following tables summarize the results of applying
&& , || and ! To Boolean values (Truth tables)
xyX && y
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
xyX || y
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
x!x
truefalse
falsetrue
46
Precedence of all operators:
PrecedenceoperatorAssociatively
1()Innermost first
2++ -- !Right to left
3* / %Left to right
4+ -Left to right
5< <= > >=Left to right
6== !=Left to right
7&&Left to right
8||Left to right
9= += -= *= /= %=Right to left
47
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
48
Solution:
1)++x * y
1
2
1) 5.0
2) 35.0
49
2) !Test || ((y+z) <= (x – z))
1 2
34
5
1) 10.0
2) 1.0
3) False
4) True
5) True
50
3) !x == y + 4 * x
1 2
3
4
1 (False
2 (16.0
3 (23.0
4 (False
51
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.
52
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
53The standard library functions in C++
The following table lists the names and the description of some important C++ standard library functions.
Header file
functionmeaningArg. type
Res. type
<cmath>fabs(x)Absolute value of xfloatfloat
<cstdlib>abs(i)Absolute value of iIntInt
<cmath>sqrt(x)square root of x (x>=0)floatfloat
cmathsin(x)Sine of x (in rad)floatfloat
Header filefunctionmeaningArg. type
Res. type
<cmath>cos(x)cosine of x (in rad)floatfloat
<cmath>tan(x)Tangent of x (in rad)floatfloat
<cmath>asin(x)Inverse sine of x (in rad)floatfloat
<cmath>acos(x)Inverse cosine of x (in rad)floatfloat
<cmath>atan(x)Inverse tangent of x (in rad)floatfloat
<cmath>exp(x)Exponent of x (base e)floatfloat
<cmath>sinh(x)Hyperbolic sine of xfloatfloat
54
Header filefunctionmeaningArg. type
Res. type
<cmath>cosh(x)Hyperbolic cosine of xfloatfloat
<cmath>tanh(x)Hyperbolic tangent of xfloatfloat
<cmath>log(x)Natural logarithm of x (base e)floatfloat
<cmath>log10(x)Common logarithm of x (base 10)
floatfloat
<cmath>pow(x,y)X to the power yfloatfloat
<cmath>ceil(x)Rounds upfloatfloat
<cmath>floor(x)Rounds downfloatfloat
55
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;
56