1 / 43

C++ Programming Language Lecture 4 C++ Basics – Part II

C++ Programming Language Lecture 4 C++ Basics – Part II. By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department. Outline. Arithmetic operators. Logical operators. Assignment operator. Increment and decrement operators. Bitwise Operators. Relational Operators.

kjohnson
Download Presentation

C++ Programming Language Lecture 4 C++ Basics – Part II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Programming LanguageLecture 4C++ Basics – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

  2. 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 • Arithmetic operators: • Addition + • Subtraction - • Division / • Multiplication * • Modulus % • Arithmetic operators are binary operators (take two operands). • Result of / (division) depends on the operands types. • Division Result Examples: The Hashemite University

  4. Arithmetic Operators II • Division Operator General Rules: 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. Example The Hashemite University

  7. Example Output The Hashemite University

  8. 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 -= 4 (d = d - 4) n += 4 (n = n + 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (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 • Relational Operators: • 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. 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. 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. 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. 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) • It is a binary operator. • 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. Logical Operators II • Truth tables: The Hashemite University

  19. 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. 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 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++; cout << 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 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. The Hashemite University

  25. 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. 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. Bitwise Operators IV The Hashemite University

  28. 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. ‘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. ‘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. 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 The Hashemite University

  33. Operators Precedence II The Hashemite University

  34. Operators Precedence III The Hashemite University

  35. Operators Precedence IV 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. 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: 12 12 10 10 The Hashemite University

  39. 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. Escape Sequences • 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. 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. Example Output The Hashemite University

  43. 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

More Related