# Elements of C++ Programs C++ is a high level language. A program called a compiler translates C++ programs into machine language program called (object.

Post on 23-Dec-2015

217 views

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. Source program linker Exe file compiler Object program 1 /
- Slide 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. 2
- Slide 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. 3
- Slide 4
- Here are some examples of valid identifiers: Areaaa_sd12e 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-40Minus sign (-) is not allowed cost_in_$ Special symbols such as $ are not allowed intInt is reserved word. two*fourCharacter * is not allowed. JoesCharacter is not allowed. c++Plus sign (+) is not allowed. 4
- Slide 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) 5
- Slide 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 25 11-76 654 0 1+653 -896 The following integer numbers are invalid for the reasons stated 12,87Commas are not allowed. 76.98A decimal point can not appear in an integer number 10 30Blank spaces are not allowed. 2E10 An exponent is not allowed - 34 Blank spaces are not allowed between the sign and the number 6
- Slide 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.250.35 -245.12 45..87 +2.58 -.25 7
- Slide 8
- The following floating-point numbers are invalid for the reasons stated. 78,542Commas are not allowed. - 4.25Blank spaces are not allowed between the sign and the number. Floating Point values can have an exponent. A number like 5.346 x 10 14 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 10 20 can be written as 3.8E+203.8E200.38E2138E19 8
- Slide 9
- The following floating-point numbers are not valid for the reasons stated. 9E4.3The exponent must be an integer - 16E4. The exponent must be an integer 8.3 E 4Blank 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
- Slide 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: Bb3+* 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
- Slide 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 11
- Slide 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). 12
- Slide 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. 13
- Slide 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() 14
- Slide 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; 15
- Slide 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 ; 16
- Slide 17
- 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
- Slide 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 18
- Slide 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 ; 19
- Slide 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 20
- Slide 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 21
- Slide 22
- Example: Given the variable declarations: Intnum, mark ; floatrate ; booltest ; char ch ; string name ; Consider The following assignments 22
- Slide 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 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
- Slide 24
- Expressions: Arithmetic expressionBoolean expression Arithmetic expression Simple Arithmetic expression Compound Arithmetic expression 24
- Slide 25
- a- Simple arithmetic expressions meaningoperator addition+ subtraction- multiplication* Division/ modulus% 25
- Slide 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) 26
- Slide 27
- 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) 27 Integer division: 16 / 3 = 5 (integer / integer = integer) Modulus:(for integers only) 17 % 5 = 2 (17 / 5= 33 * 5 =1517 15 = 2) 5 % 7 = 5 (5 / 7 = 00 * 7 = 05 0 = 5) 9 % 0 (error) 3.2 % 2 (error)(3.2 is float)
- Slide 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++ ;orcount-- ; 28
- Slide 29
- ++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 = 9 a = 10 ;b = a-- ; the result will be: a = 9 and b = 10
- Slide 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 30
- Slide 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 ; 31 Solution: a. z = x++ - y ;b. z = ++x y ; c. z = --x y ;d. z = x-- - y ;
- Slide 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 ; 32
- Slide 33
- Equivalent statementExampleOperator x = x + 3 ;x += 3 ;+= x = x 3 ;x -= 3 ;-= x = x * yx *= y ;*= x = x / y ;x /= y ;/= x = x % y ;x %= y ;%= The following table shows all the available abbreviated assignment operators in C++ 33
- Slide 34
- 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: Associativelyoperatorprecedence Innermost firstParentheses: ()1 Right to left++ --2 Left to right* / %3 Left to right+ -4 Right to left = += -= *= /= %=5 34 B- compound arithmetic expressions:
- Slide 35
- The following table contains some examples of compound arithmetic expressions: (a + b) / (c + d) + x * y1. x * pow(y,6) /(z * z + 4)2. X / (a % b) 2 * a3. 35
- Slide 36
- 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.
- Slide 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: (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
- Slide 38
- 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
- Slide 39
- (b) 5.0 *(2.0 / (4.0 *2.0)) 1 2 3 1) 8.0 2) 0.25 3) 1.25 39
- Slide 40
- c) (50 / 4) % (7 % 7) 12 3 1) 12 2) 0 3) Error 40
- Slide 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 41
- Slide 42
- Relational operators in C++ are shown in the following list: MeaningRelational Operator Equal to== Not equal to!= Less than< Less or equal Greater or equal to>= 42
- Slide 43
- 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 != -2True I + 2.5 < j + 11True i + j == 10False i * j = = -15Error (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
- Slide 44
- b. Boolean Expressions with logical operators: We can form more complicated Boolean expressions by using the following three logical operators: MeaningLogical operator and&& or|| not! 44
- Slide 45
- 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) X && yyx True False True FalseTrueFalse
- Slide 46
- X || yyx True FalseTrue False !xx falsetrue false 46
- Slide 47
- Precedence of all operators: AssociativelyoperatorPrecedence Innermost first()1 Right to left++ -- !2 Left to right* / %3 Left to right+ -4 Left to right >=5 Left to right== !=6 Left to right&&7 Left to right||8 Right to left= += -= *= /= %=9 47
- Slide 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) j ; 0 will be stored in k
- Slide 53
- 53 The standard library functions in C++ The following table lists the names and the description of some important C++ standard library functions. Res. type Arg. type meaningfunctionHeader file float Absolute value of xfabs(x) Int Absolute value of iabs(i) float square root of x (x>=0)sqrt(x) float Sine of x (in rad)sin(x)cmath
- Slide 54
- Res. type Arg. type meaningfunctionHeader file float cosine of x (in rad)cos(x) float Tangent of x (in rad)tan(x) float Inverse sine of x (in rad)asin(x) float Inverse cosine of x (in rad)acos(x) float Inverse tangent of x (in rad)atan(x) float Exponent of x (base e)exp(x) float Hyperbolic sine of xsinh(x) 54
- Slide 55
- Res. type Arg. type meaningfunctionHeader file float Hyperbolic cosine of xcosh(x) float Hyperbolic tangent of xtanh(x) float Natural logarithm of x (base e)log(x) float Common logarithm of x (base 10) log10(x) float X to the power ypow(x,y) float Rounds upceil(x) float Rounds downfloor(x) 55
- Slide 56
- Examples fabs(-6.5) = 6.5fabs(-15/4.0) = 3.75abs(-14)=14 sqrt(4.0)=2.0sin(2.0)=0.90929asin(0.90929)=2.0 pow(2,4)=16.0ceil(3.3)=4.0ceil(3.7)=4.0 floor(10.2)=10.0floor(10.8)=10.0floor(-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 float z ; Z = sqrt(16.0) * 3 ; 56

Recommended

View more >