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

Slides:



Advertisements
Similar presentations
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Advertisements

Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 2 Data Types, Declarations, and Displays
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
2440: 211 Interactive Web Programming Expressions & Operators.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 4.8The do/while Repetition Structure The do/while repetition structure –Similar to the while structure –Condition for repetition tested after the body.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (Switch, do-while, break) Outline 4.7The.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
OPERATORS.
C Operators. CONTENTS C OPERATORS TYPES OF OPERATOR UNARY BINARY TERNARY ARITHMATIC RELATIONAL LOGICAL.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Lecture #6 OPERATORS AND ITS TYPES By Shahid Naseem (Lecturer)
CHAPTER 1.3 THE OPERATORS Dr. Shady Yehia Elmashad.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Operators & Expressions
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Bill Tucker Austin Community College COSC 1315
Operators & Expressions
CompSci 230 S Programming Techniques
C++ Programming Language Lecture 4 C++ Basics – Part II
Chapter 4 – C Program Control
Chapter 7: Expressions and Assignment Statements
Operators and Expressions
Chap. 2. Types, Operators, and Expressions
University of Central Florida COP 3330 Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
Relational Operations
Chapter 7: Expressions and Assignment Statements
Chapter 4 - Program Control
Introduction to C Programming
Operators and Expressions
Introduction to Programming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
All the Operators 22-Nov-18.
Introduction to C++ Programming
Chapter 4 - Program Control
All the Operators 4-Dec-18.
Introduction to C Programming
C Operators, Operands, Expressions & Statements
Chapter-3 Operators.
Introduction to Programming – 4 Operators
Chapter 3 Operators and Expressions
2.6 The if/else Selection Structure
Chapter 2: Introduction to C++.
C++ Programming Lecture 3 C++ Basics – Part I
Engineering Problem Solving with C++ An Object Based Approach
All the Operators 6-Apr-19.
All the Operators 13-Apr-19.
Herbert G. Mayer, PSU CS Status 7/19/2015
Chapter 4 - Program Control
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
OPERATORS in C Programming
Operator King Saud University
DATA TYPES There are four basic data types associated with variables:
Chapter 1 c++ structure C++ Input / Output
Lecture 9: Implementing Complex Logic
OPERATORS in C Programming
Presentation transcript:

C++ Programming Language Lecture 4 C++ Basics – Part II By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

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

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

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

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

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

The Hashemite University Example Output The Hashemite University

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

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

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

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

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

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

The Hashemite University Example Output The Hashemite University

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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: 12 12 10 10 The Hashemite University

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

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

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

The Hashemite University Example Output The Hashemite University

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