Download presentation
Presentation is loading. Please wait.
Published byΚαλυψώ Σπυρόπουλος Modified over 5 years ago
1
C++ Programming Language Lecture 4 C++ Basics – Part II
By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department
2
The Hashemite University
Outline Arithmetic operators. Logical operators. Assignment operator. Increment and decrement operators. Bitwise Operators. Relational Operators. ‘Size of’ operator. Comma operator. Operators Precedence. Escape Sequences. The Hashemite University
3
Arithmetic Operators I
Addition + Subtraction - Division / Multiplication * Modulus % Arithmetic operators are binary operators (take two operands). Result of / (division) depends on the operands types. Division Result Examples: E.g: int a= 5; int b = 2; double c = a/b; c = ?? double a= 5; double b = 2; int c = a/b; c = ?? double c = 5/2; double c = 5.0/2; double c = 5/2.0; The Hashemite University
4
Arithmetic Operators II
Division Operator General Rules: Operand 1 data type Operand 2 data type Temporary result Holder data type Saved Result int integer double/float Floating point The Hashemite University
5
Arithmetic Operators III
% (modulus which finds the remainder) is applied for integer values only. So, 9%4 = 1, but 9%2.5 Syntax Error. Operators precedence: *, %, and / have the same priority which are higher than + and – (+ and – have the same priority). If multiple operators are combined which have the same priority you start implementation from left to right. Remember that parenthesis forces priority. For nested parenthesis you start with the most inner parenthesis pair. For multiple parenthesis start implementation from left to right. The Hashemite University
6
The Hashemite University
Example #include <iostream.h> int main() { int a = 9, b = 30, c = 89, d = 35, x; double e = 3, y; cout <<"(a): "<< d/a << endl; cout <<"(b): "<< d/e << endl; x = d/a; y = d/a; cout <<"(c): "<< x << endl; cout <<"(d): "<< y << endl; x = d/e; y = d/e; cout <<"(e): "<< x << endl; cout <<"(f): "<< y << endl; x = d*a + c%b - b + d/e; y = d*a + c%b - b + d/e; cout <<"(g): "<< d*a + c%b - b + d/e << endl; cout <<"(h): "<< x << endl; cout <<"(i): "<< y << endl; x = d*a + c%b - (b + d/e); y = d*a + c%b - (b + d/e); cout <<"(j): "<< d*a + c%b - (b + d/e) << endl; cout <<"(k): "<< x << endl; cout <<"(l): "<< y << endl; return 0; } The Hashemite University
7
The Hashemite University
Example Output The Hashemite University
8
The Hashemite University
Assignment Operator I = assigns the value on the right hand side to what present on the left hand side. E.g: int x = 6; Multiple assignments at the same time are allowed where implementation starts from right to left, e.g. x = y = u = 10; Common errors: 6 = x; x = y + 10 = 9; // you cannot use arithmetic operators between multiple assignments. The Hashemite University
9
Assignment Operator II
Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; Examples of other assignment operators include: d -= (d = d - 4) n += (n = n + 4) e *= (e = e * 5) f /= (f = f / 3) g %= (g = g % 9) Assignment operators associate from right to left. The Hashemite University
10
Assignment Operator III
Note that the priority of the assignment operators, i.e. +=, /=, etc., is different from the operators alone, i.e. +, /, etc. Also, they are associated from right to left. The Hashemite University
11
Equality and Relational Operators I
Greater than > Less than < Greater than or equal >= Less than or equal <= Equality operators: Equal to == Not equal to != Equality and relational operators are binary operators, used for comparison between two operands. Its result is either “true” or “false”, i.e. boolean data type. Very useful for conditional control structures, e.g. conditional if. Operator Operation Performed x>y Is x greater than y? x<y Is x less than y? x>=y Is x greater than or equal to y? x<=y Is x less than or equal to y? x==y Is x equal to y? x!=y Is x not equal to y? The Hashemite University
12
Equality and Relational Operators II
Relational operators have the same priority which is higher than the equality operators. If relational operators are associated, precedence is implemented from left to right. If equality operators are associated, precedence is implemented from left to right. Again, parenthesis forces priority. The Hashemite University
13
The Hashemite University
Example #include <iostream.h> int main() { int a = 9, b = 30, c = 89, d = 35; bool e, f; e = a > b; cout <<"(a): "<< e << endl; f = d == b; e = d == d; cout <<"(b): "<< f << endl; cout <<"(c): "<< e << endl; e = c != d; cout <<"(d): "<< e << endl; return 0; } The Hashemite University
14
The Hashemite University
Example Output The Hashemite University
15
Confusing Equality (==) and Assignment (=) Operators I
These errors are damaging because they do not ordinarily cause syntax errors. Recall that any expression that produces a value can be used in control structures. Nonzero values are true, and zero values are false Example: if ( payCode == 4 ) cout << "You get a bonus!" << endl; Checks the paycode, and if it is 4 then a bonus is awarded If == was replaced with = if ( payCode = 4 ) cout << "You get a bonus!" << endl; Sets paycode to 4 4 is nonzero, so the expression is true and a bonus is awarded, regardless of paycode. The Hashemite University
16
Confusing Equality (==) and Assignment (=) Operators II
lvalues or l-values Expressions that can appear on the left side of an equation Their values can be changed Variable names are a common example (as in x = 4;) rvalues or r-values Expressions that can only appear on the right side of an equation Constants, such as numbers (i.e. you cannot write 4 = x;) lvalues can be used as rvalues, but not vice versa The Hashemite University
17
The Hashemite University
Logical Operators I Logical operators allows the programmer to combine more than one condition with each other to form more complex conditions. && (logical AND) It is a binary operator. Returns true if both conditions are true. || (logical OR) Returns true if either of its conditions are true. ! (logical NOT or logical negation) Reverses the truth/falsity of its condition (reverse the meaning of a condition). Returns true when its condition is false. It is a unary operator, only takes one condition. Logical operators used as conditions in loops, e.g. for and while, and conditional statements, e.g. if/else. The Hashemite University
18
The Hashemite University
Logical Operators II Truth tables: A B A && B true false A B A ||B true false A !A true false The Hashemite University
19
The Hashemite University
Logical Operators III Short-circuit evaluation: This concept is used when evaluating a complex condition that contains && or || operators. Evaluation starts from left to right, if one sub-condition evaluates to false in && evaluation will stop since the result of the whole condition will false. The situation for || is different, if one sub-condition found to be true evaluation stops since the final result of the condition will be true. This concept is very useful in reducing the program execution time. The Hashemite University
20
The Hashemite University
Logical Operators IV Operators precedence: ! has the highest priority followed by && and then || (i.e. || has the lowest priority). When any of these operators are combined, implementation starts from left to right. The Hashemite University
21
Logical Operators -- Examples
Math C++ 10 < x < 100 (x > 10) && (x < 100) x ≠ 90 !(x == 90) or x != 90 x < 0 or x > 40 (x < 0) || (x > 40) The Hashemite University
22
Increment & Decrement Operators I
Increment operator (++) - can be used instead of c += 1 (unary operator) Decrement operator (--) - can be used instead of c -= 1 (unary operator) Pre-increment/decrement When the operator is used before the variable (++c or --c) Variable is changed, then the expression it is in is evaluated. Post-increment/decrement When the operator is used after the variable (c++ or c--) Expression the variable is in executes, then the variable is changed. E.g.: If c = 5, then cout << ++c; prints out 6 (c is changed before cout is executed) cout << c++; prints out 5 (cout is executed before the increment. c now has the value of 6) The Hashemite University
23
Increment & Decrement II
When Variable is not in an expression Preincrementing and postincrementing have the same effect. ++c; cout << c; and c++; have the same effect. ++ and – cannot be applied to expressions: int x = 0; cout << ++ (x + 100); //Error Increment and decrement operators associates from right to left. The Hashemite University
24
Bitwise Operator Symbol
Bitwise Operators I Operates on individual bits of the operands, i.e. on the binary representation of the data, not on entire expressions as in logical operators. Bitwise Operator Symbol Function & AND individual bits | OR individual bits ^ XOR individual bits ~ NOT of individual bits (or complement operator, computes the one’s complement) >> Right-shift operator << Left-shift operator The Hashemite University
25
The Hashemite University
Bitwise Operators II Also, it has an assignment operator form, i.e. x = x &y x &= y, and so for all operators listed in the following table except the complement operator ~ has no assignment operator. Note that the shift operators <<, >> are the same as extraction and insertion operators. This is an example of what so called “Operators Overloading” where the operator function depends on the used operands. A^B = (~A&B) | (A&~B), which is called XOR function or gate in digital logic. Using && instead of & and || instead of | and ! Instead of ~ as bitwise operators are logical errors not syntax. The Hashemite University
26
The Hashemite University
Bitwise Operators III The right operand of the shift operators must be: Integer. Positive. Less than the number of bits used by the left operand. If the right operand of the shift operator is –ve logical error, the output is unexpected (incorrect output). If the right operand of the shift operator is floating point number (not integer) syntax error. If the right operand of the shift operator is larger than or equal the number of bits of the left operand (e.g. 32 or larger when the left operand is of type int) logical error, the output is unexpected (incorrect output). The Hashemite University
27
The Hashemite University
Bitwise Operators IV A B A & B 1 A B A | B 1 A B A^B 1 A ~A 1 The Hashemite University
28
The Hashemite University
Bitwise Operators V Operators precedence: ~ has the highest priority, followed by the shift operators (both left and right shift), then & operator, ^ operator, and finally the | operator which has the lowest priority. Associated from left to right except the ~ which is associated from right to left. Note that the priority of their assignment version, i.e. &=, |=, etc., is different from the operators alone, i.e. &, |, etc. Also, they are associated from right to left. The Hashemite University
29
The Hashemite University
‘sizeof’ Operator I It is a unary operator, i.e. Unary operators operate on only one operand, which could be: A constant value (e.g. 10, 300, ‘c’, etc.). A variable name. A data type name (e.g. int, double, etc.). Return the size in bytes of the input variable or data type as a size_t value (which is usually unsigned integer). Parenthesis are required after it only when its operand is a data type name, otherwise these parenthesis are optional (but in this case leave a single white space after sizeof operator). The Hashemite University
30
The Hashemite University
‘sizeof’ Operator II E.g: cout<<sizeof(float);//output is 4 cout<<sizeof float;//Syntax error float kk; cout << sizeof(kk); //output is 4 Or cout << sizeof kk; //output is 4 cout << sizeof 100; //output is 4 (taken as integer) cout << sizeof 1.2; //output is 8 (taken as double) cout << sizeof ‘z’; //output is 1 cout << sizeof “hello”; //output is 6 (the size of the string in addition to the ‘\0’ chracter) The Hashemite University
31
The Hashemite University
Comma Operator Accept two operands or expressions on either side (i.e. binary operator). Implementation starts from left. The value of the entire expression will be the value of the right most expression. It has the least priority among all operators. E.g; int x, y, z; cout << (x = 5, y = 8); //will print 8 y = (z, x = 7, x + 8); //y = 15 The Hashemite University
32
Operators Precedence I
Description Associativity 1 :: Scoping operator None 2 () [] -> Grouping operator Array access Member access from a pointer Member access from an object Post-increment Post-decrement left to right 3 ! ~ * & (type) sizeof Logical negation Bitwise complement Pre-increment Pre-decrement Unary minus Unary plus Dereference Address of Cast to a given type Return size in bytes right to left The Hashemite University
33
Operators Precedence II
4 ->* .* Member pointer selector Member object selector left to right 5 * / % Multiplication Division Modulus 6 + - Addition Subtraction 7 << >> Bitwise shift left Bitwise shift right 8 < <= > >= Comparison less-than Comparison less-than-or-equal-to Comparison greater-than Comparison greater-than-or-equal-to The Hashemite University
34
Operators Precedence III
9 == != Comparison equal-to Comparison not-equal-to left to right 10 & Bitwise AND 11 ^ Bitwise exclusive OR 12 | Bitwise inclusive (normal) OR 13 && Logical AND 14 || Logical OR 15 ? : Ternary conditional (if-then-else) right to left The Hashemite University
35
Operators Precedence IV
16 = += -= *= /= %= &= ^= |= <<= >>= Assignment operator Increment and assign Decrement and assign Multiply and assign Divide and assign Modulo and assign Bitwise AND and assign Bitwise exclusive OR and assign Bitwise inclusive (normal) OR and assign Bitwise shift left and assign Bitwise shift right and assign right to left 17 , Sequential evaluation operator or comma left to right The Hashemite University
36
Operators Precedence -- Notes
The complete table of operators precedence can be found in Appendix A of the textbook. Pay attention to the direction of associatively of the different operators. Operators precedence implementation and its effect are compiler dependent. E.g: int x = 1; x = x / ++x; /*The final value of x depends on how the compiler will implement the above expression.*/ The Hashemite University
37
Operators Precedence -- Examples
Evaluate the following expressions: int x = 5, y = 9, u = 30, z; z = ++x – (y-=3) + (u*=2) + u&y; //z = 0 z = y && x || u^y || ~x; // z = 1 z = y > x + u == y; // z = 0 z = u / x % y * 2 + y / 4.0 – x--; // z = 3 If you write the first expression as follows (without parenthesis) the compiler will give you a syntax error, why? z = ++x – y-=3 + u*=2 + u&y; // two syntax errors The Hashemite University
38
The Hashemite University
cout Function Ostream class. Tied to the standard output device (monitor or screen). Can display: A string. A variable value. A result of an operation (mathematical, logical, function call, etc.). Concatenating or cascading or chaining of stream insertion operators: output many values using one cout and multiple insertion operators. E.g. cout << “Hello\n” << “World\n”; The evaluation of the cascaded expressions starts from right to left but the printing on the screen starts from left to right. E.g. int x = 10; cout << x <<“\t”<< ++x << “\t”<< x++ << “\t” << x << endl; Output is: The Hashemite University
39
The Hashemite University
cin Function Istream class. Tied to the standard input device (keyboard). When reading a string cin will stop at the first white space encountered in the string or when you press enter. Cascaded extraction operator can be applied to read more than one variable from the keyboard using one statement (after entering each variable value press enter): E.g: int x, y; cout << “Enter two integers\n”; cin >> x >> y; The Hashemite University
40
The Hashemite University
Escape Sequences Escape Sequence Meaning \n new line \t horizontal tab \a bell sound (alert) \\ Backslash \" double quotation \b Backspace (place the cursor one character space back not deleting characters). \r Carriage return (place the cursor at the beginning of the current line not a new one) \0 Null character (used in strings) An escape sequence begins with a \ (backslash or called escape character) followed by an alphanumeric character. Note that the two characters of an escape sequence are construed as a single character and indicates a special output on the screen. Also, it is used to allow the usage of some characters within a character constant which are reserved for C++ (e.g. \, “). The Hashemite University
41
The Hashemite University
Example //Sample C++ Program #include <iostream.h> int main() { cout<<"one\ttwo\tthree\n"; cout << "Jordan\b\b " << endl; cout << "Jordan\b\b" << endl; cout << "Jordan\b\byy" << endl; cout << "\"Jordan\"" << endl; cout << "\\Jordan\\" << endl; cout << "Hello" << "\r" << "Bye" << endl; return 0; } The Hashemite University
42
The Hashemite University
Example Output The Hashemite University
43
The Hashemite University
Additional Notes This lecture covers the following material from the textbook: Fourth edition: Chapter 1: sections 1.22, 1.24, 1.25 Chapter 2: sections 2.11, 2.12, 2.19, 2.20 Chapter 18: section 18.7 The Hashemite University
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.