E N D
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 Object program Source program Exe file
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.
4 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 letter max 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.
5 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)
6 1- The Integer (int) Data Type An integer (int) contains neither a decimal point nor an exponent. Several valid integer numbers are shown below • 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
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
8 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
9 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.
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.
11 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”
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()
15 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;
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 ;
17 The following declarations give some examples of invalid declarations: • Int a,b,c; • float a,d; No identifier can have more than one declaration. No identifier can have more than one declaration b) Const int k = 10 ; Int I, j, k ; c) Const float else = 13.6 ; Else is a reserved word Ch is a character while “May” is a string. d) Const char ch = “May” ;
18 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
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 ; y = 43.9 ; ch = ‘f’ ;
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 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 Invalid.only a variable can appear on the left of = 6.8 = rate ; Invalid. only a variable can appear on the left of = Num + 5 = mark ; Invalid. Z is Undeclared identifier Z = rate ; Invalid. The exponent must be an integer Rate = 2E3.5
24 Expressions: Arithmetic expression Boolean expression Arithmetic expression Compound Arithmetic expression Simple Arithmetic expression
25 a- Simple arithmetic expressions
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: • 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++
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:
35 The following table contains some examples of compound arithmetic expressions:
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. • المعاملات الحسابية لا يمكن أن تظهر بالتتابع ولكن يمكن استخدام الأقواس للفصل بينهما
37 • 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: • 17 % 5 + ++x / 2 + 10 – 3 where x= 7 • (b) 5.0 *(2.0 / (4.0 *2.0)) • (c) (50 / 4) % (7 % 7)
38 Solution: (a) 17 % 5 + ++x/2 + 10 – 3 1) 8 1 2) 2 3) 4 4) 6 2 3 5) 16 6) 13 Final result 4 5 6
(b) 5.0 *(2.0 / (4.0 *2.0)) 39 1) 8.0 1 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:
43 Example Suppose that i and j are integer-type variables where i = 5 and j = -3 Several Boolean expressions are shown below. ExpressionValue 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.
44 b. Boolean Expressions with logical operators: We can form more complicated Boolean expressions by using the following three logical operators:
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 (one-operand) operator. The following tables summarize the results of applying && , || and ! To Boolean values (Truth tables)
47 Precedence of all operators:
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: • ++x * y • !Test || ((y+z) <= (x – z)) • !x == y + 4 * x
49 Solution: 1) 5.0 • ++x * y 2) 35.0 1 2
50 2) !Test || ((y+z) <= (x – z)) 1 2 1) 10.0 2) 1.0 3 4 3) False 4) True 5) True 5