Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace...

33
1 Northeastern University \n new line \r carriage return \t horizontal tab \v vertical tab \b backspace \\ backslash \” double quotation mark \’ single quotation mark \? Question mark \ddd ASCII code in octal format \xdd ASCII code in hexadecimal format Escape Sequence Characters

Transcript of Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace...

Page 1: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

1

Northeastern University

\n new line

\r carriage return

\t horizontal tab

\v vertical tab

\b backspace

\\ backslash

\” double quotation mark

\’ single quotation mark

\? Question mark

\ddd ASCII code in octal format

\xdd ASCII code in hexadecimal format

Escape Sequence Characters

Page 2: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

2

Northeastern University

Flow Control 1Decision Statements

• Boolean Expressions– Evaluate to TRUE (1) or FALSE (0) only. C++ uses integer to

represent Boolean variables, 0 for FALSE and 1 for TRUE. However, any non-zero integer is regarded TRUE in C++.

• Relational Operations– Comparison between numerical quantities– Evaluate to TRUE (1) if relation is satisfied and FALSE (0)

otherwise.– > (greater than), >= (greater than or equal to)– < (less than), <= (less or equal to)– == (equal to), != (not equal to)

Page 3: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

3

Northeastern University

Decision Statements

• Boolean (Logic) Expressions– Operations on Boolean Variables– Binary: && (AND), || (OR)– Unary: ! (NOT or INVERSION)– Truth Table in C++

– Strictly speaking, Boolean algebra has only TRUE (1) or FALSE (0) but no non-zero.

A B A && B A || B0 0 0 00 non-zero 0 1

non-zero 0 0 1non-zero non-zero 1 1

A ! A0 1

non-zero 0

Page 4: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

4

Northeastern University

Decision Statements

– The AND (&&) operator evaluates to true only when both operands are TRUE. If the first operand is FALSE, we don’t need to know the second operand for evaluation. Similarly, the OR (||) operator evaluates to FALSE only when both operands are FALSE. If the first operand is TRUE, we don’t need to know the second one. This is called short-circuit evaluation.

Page 5: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

5

Northeastern University

– Assignment operator =• The equal sign = assigns the value of the variable on its right to the

memory location of the variable on its left. Unlike in mathematics where x = x + 1 is meaningless, in C++, the same expression means take the present value stored in the memory location corresponding to the identifier x, add 1 to it and store the result back to the same memory location. (x = x + 1 is usually written as x += 1 in C++).

– Arithmetic Operators• + - * / % (modulus, i.e. positive remainder of integer division)

– Relational operators (return 1 if true and 0 if false):• == (equal to) ; != (unequal) ; <= ; >= ; < ; > ; && (and) ;

|| (or) ; ?: (conditional operator)

– Assignment Operators• = += -= /= %= &= |= ^= >>= <<=

– Shift Operators: << >>

– Bitwise Operators: ~ & |

– Others: ! ( ) [ ] --> , .

Arithmetic Expressions

Page 6: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

6

Northeastern University

• Operator PrecedenceAn expression may contain multiple operators, operator precedence

defines the order that operators in an expression are evaluated when multiple operators are present. The operator precedence in C++ is largely the same as the convention used in arithmetic, i.e.:

1. Function calls in an expression

2. Multiplication (*) and division (/) are performed in sequence

3. Addition (+) and subtraction (-).

Operator precedence can be overwritten by using parentheses. It does no harm to put parentheses to force the sequence of the operation you want to perform when you are uncertain of the operator precedence.

Page 7: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

7

Northeastern University

Operators Associativity

function calls right to left

() ++(postfix) --(postfix) left to right

! +(unary) ++(prefix) --(prefix) &(unary) *(unary) right to left

* / % left to right +(binary) -(binary) left to right

< <= > >= left to right

== != left to right

&& left to right

|| left to right

?: right to left

= += -= *= /= etc… right to left

, (comma operator) left to right

Page 8: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

8

Northeastern University

• Precedence and associativity of operatorsC++ allows concantenation of operators. Precedence rule

defines the order of operators and associativity defines the sequence of operation (from left to right or from right to left).

Examples:1. = is right associative, a = b = 5; a = (b = 5);

2. * and / , are left associative, a *b / c; (a * b) / c;

3. int a = 4, b = 5;

double c, d;

c = a / b * 2.0; /* c = 0.0 */

d = 2.0 * a / b; /* d = 1.6 */

4. < and > have higher precedence than &&,

a > b && a < c (a > b) && (a < c)

5. + has higher precedence than >, a + b > 0 (a + b) > 0

Page 9: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

9

Northeastern University

• Type of expression and conversion– The data type of the result of an expression such as x+y is the

same as x and y if x and y are the same type

– If x is int and y is double or vice versa, then the int is converted to double first before operation, the result is double

– General rule for mixed-type expressions: the “smaller” operand is promoted (converted) to the biggest-range data type (normally double) before evaluation, e.g.: x is int and y is char, then y is promoted to int first and x+y evaluates to an int result.

– If an assignment operator is used to assign the result of an expression to another variable, the expression is evaluated first according to the above conversion rule and the result is assigned to the value. Another conversion occurs if necessary.

Page 10: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

10

Northeastern University

int x, y;

double u, v;

x = y + u; /* y+u is evaluated as double first. */

/* result is converted to int before assigned to x. */

v = x + y; /* x+y evaluated as int first. */

/* result is converted to double before assigned to v. */

• Conversion from double to int may result in loss of precision, e.g.: if y + u = 2.4, x will be evaluated to 2.

• We can overwrite default conversion rule by casting, e.g. x and y can be cast as double before evaluation.V = (double)x + (double)y;

x = 3;

y = 5;

u = x/y; /* u = 0.0, this is a common mistake */

v = (double)x / (double)y /* v = 0.6 */

Example

Page 11: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

11

Northeastern University

Type Casting

• Syntax– (data_type) Identifier

– data_type(Identifier)

– static_cast<data_type>(Identifier)

Page 12: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

12

Northeastern University

• if statement– Syntax: if (condition)

statement ;– The statement following the condition is executed only when

the condition is satisfied, e.g. :

if (i == 0)

cout << “i is zero”;

• if-else statement– Syntax: if (condition)

statement1 ;

else

statement2 ;

Page 13: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

13

Northeastern University

– If condition is satisfied, execute statement1, otherwise execute statement2.

– Example:if (a > b)

cout << “a is bigger than b.\n”;

else

cout << “a is not bigger than b.\n”;

– We can use Boolean operators to set “compound conditions”, e.g.: validating the range of certain input aif (a < 0 || a > 5)

cout << “a is out of range.\n”;

else

cout << “You have entered ” << a << endl;

Page 14: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

14

Northeastern University

• Compound statement

Sometimes a simple statement after the if test condition is not enough to accomplish our job. We can use compound statement to achieve more complicated tasks.– A compound statement is a sequence of statements

enclosed in open and closed braces, e.g.:if (a > b) {

c = a - b;

cout << “a is bigger than b by ” << c << endl; }

else

cout << “a is smaller than or equal to b.\n”;

– A compound statement defines a new level of variable scope. You can declare local variables for the compound statement within the braces.

Page 15: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

15

Northeastern University

– Local variables in the compound statement are only visible by the compound statement. However, local variables in the same function are also visible to the compound statement. Example:int x, y;

………

if (T > 37.0) {

double fah;

fah = T*1.8 + 32;

cout << “Patient is on fever. The equivalent body temperature in

Farenheit is ” << fah << endl; }

else {

cout << “Body temperature is fine.\n”;

discharge();

}

Page 16: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

16

Northeastern University

– x and y are visible by the whole function. fah is only visible to the compound statement in which it is declared. Memory space for fah is allocated when the compound statement is reached and returned to the OS when the compound statement is finished.

– Use indentation for compound statements to enhance readability. Indentation is for human readers only. The compiler only recognizes the braces, not the indentation.

– The indentation format used in the examples is the AT&T Bell Lab’s programming style.

Page 17: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

17

Northeastern University

• Alternative to compound statement– Use a comma separated list of expressions.– The comma operator basically does nothing. Expressions

separated by comma evaluates from left to right.– Not as clear and readable as compound statement.

Example:

if (a > b)

c = a - b, a *= 2

• Empty statement

A single semicolon “;”. No operation. Mostly used in for loops. Example:

if (a > b)

;

Page 18: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

18

Northeastern University

• More on C++ syntax and common mistakes

Since C++ treats Boolean variables as integers and allows mixing of operators, it is easy to make some mistakes.– Do not confuse == (equality) with = (assignment)

if (a == 5) statement; is interpreted as :

(1) a == 5 evaluates to 1 if condition is satisfied, 0 otherwise.

(2) if (1 /* non-zero */), statement is executed.

if (a = 5) statement; is interpreted as :

(1) 5 is assigned to variable a first

(2) if (5 /* non-zero */), statement is executed (ALWAYS)

– if (a != 0) can be written as if (a)

Page 19: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

19

Northeastern University

– if (0 <= x <= 4) is syntactically correct but not always logically correct. Use associativity and precedence rules, the sequence of operations in the parenthesis is:(0 <= x) <= 4, when x > 4, the final result must be 1 (TRUE).

• Correct expression: if (0 <= x && x >= 4)

– The ! (NOT) operator has higher precedent than relational operators, so ! 4 > 5 is interpreted as (!4) > 5 which is 0 instead of ! (4 > 5) which is 1.

– To represent both x and y are greater than z, write

(x > z) && (y > z), NOT x && y > z which is actually

x && (y > z)– Although the parentheses in (x > z) && (y > z) are not

required, the expression is more readable if the parentheses are included.

Page 20: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

20

Northeastern University

• Logical assignmentsThe expression following the assignment operator represents logic ideas. As we said, the logic variable is nothing but an integer variable or bool variable.

Examples:even = n%2 == 0;

is_letter = (‘A’ <= ch && ch <= ‘Z’) || (‘a’ <= ch && ch <= ‘z’);

in_range = n > -10 && n < 10

Page 21: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

21

Northeastern University

• Nested if and multiple alternative decisionsSometimes, we need to make more than two decisions.

Syntax: if (condition1)

statement1;

else if (condition2)

statement2;

……

else if (conditionN)

statementN;

else

default_statement;

• One and only one statement will be executed.

• The last else and the default statement are optional.

Page 22: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

22

Northeastern University

Example: Increment the counters num_pos, num_new or num_zero depending on the sign of the input value x.

Implementation 1:

if (x > 0)

num_pos += 1;

else if (x < 0)

num_neg += 1;

else /* x == 0 */

num_zero += 1;

Implementation 2:

if (x > 0)

num_pos += 1;

if ( x < 0)

num_neg += 1;

if (x == 0)

num_zero += 1;

Page 23: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

23

Northeastern University

• Both implementations give the same result.

• Implementation 1 is clearer and more efficient.

• The three if conditions in implementation 2 are examined for every x. However, if x is positive, the other two else conditions are not examined. So the program runs faster.

• Use indentation properly to enhance readability.

• In nested if-else structure, the else statement always matches the last incomplete if statement regardless of indentation.

• Order of conditions can be important in certain situations.

Page 24: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

24

Northeastern University

Example:if (income <= 15000)

cout << “Lower class.\n”;

else if (income <= 55000)

cout << “Middle class.\n”;

else /* income > 55000 */

cout << “Upper class.\n”;

A guy with annual income $10000 will be classified as lower class by the above code. If we reorder the conditions:

if (income <= 55000)

cout << “Middle class.\n”;

else if (income <= 15000)

cout << “Lower class.\n”;

else

cout << “Upper class.\n”;

Page 25: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

25

Northeastern University

– The second if is never used in the reordered code. The condition income <= 15000 is included in the condition income <= 55000. Only mutually exclusive conditions can be placed in arbitrary order.

Example: Use compound statement to overwrite the default if-else paring. Consider the following code:

a = 4;

b = 4;

if (a == 4)

if (b == 4)

cout << “Both a and b are 4.\n”;

else

cout << “a is not 4.\n”;

Page 26: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

26

Northeastern University

In spite of the indentation, the else statement is associated with the second if. Therefore:

a == 4 and b == 2 output: “a is not 4”

a == 2 and b == 2 output: “no text”

Correction 1:

if (a == 4) {

if (b == 4)

cout << “Both a and b are 4.\n”;

}

else

cout << “a is not 4.\n”;

Page 27: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

27

Northeastern University

Correction 2:

if (a == 4 && b == 4)

cout << “Both a and b are 4.\n”;

else if (a != 4)

cout << “a is not 4.\n”;

– Multiple decisions using the switch statement• Useful when the selection is based on the value of a single variable or of

a simple expression called the control expression• Syntax: switch (expression) { /* usually a variable */

case label1:

statement1;

statement2;

break;

Page 28: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

28

Northeastern University

case label2:

statement1;

statement2;

break;

case labelN:

statement1;

statement2;

break;

default:

statement1;

statement2;

break; /* optional here */

}

Page 29: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

29

Northeastern University

– When a match between the value of the control expression and the case label is found, the statements following the case label are executed until a break statement is found. The break keyword skips the rest of the switch options.

– Omission of the break keyword before the next case label will cause the execution of the statements following the next case label. This is called execution fall through. It is a useful feature in C++ programming.

Example:In this example, the user types in a character input. Different functions are called according to the input character. Functions e_mail(), news(), quit(), re_input() are defined somewhere in the program.

Page 30: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

30

Northeastern University

Switch (input) {

case ‘e’:

case ‘E’;

email();

break;

case ‘n’:

case ‘N’:

news();

break;

case ‘q’:

case ‘Q’:

quit();

break;

default:

re_input(); }

Page 31: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

31

Northeastern University

– Limitations: labels can only be integers or characters (i.e. something that can be evaluated to an integer).

– The statements in the default sections are executed when there is no match with all the labels. Although the default section is optional, it is recommended that a default section is always included whenever possible.

– Remember to put the break statement at the end of each alternative to prevent fall through.

• Conditional Operator ?:– Ternary operator with syntax:

expression1 ? expression2 : expression3

Page 32: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

32

Northeastern University

– Evaluates expression1 first. If it is non-zero (true), expression2 is evaluated and the result of expression2 is the value of the conditional expression as a whole.

– If expression1 evaluates to zero (false), expression3 is evaluated. The result of expression3 is then the value of the whole conditional expression.

Example:

if (y < z)

x = y;

else

x = z;

can be equivalently written as:

x = (y < z) ? : y : z;

Page 33: Northeastern University 1 \nnew line \rcarriage return \thorizontal tab \vvertical tab \bbackspace \\backslash \”double quotation mark \’single quotation.

33

Northeastern University

Homework

• Homework #1– Page 105, #1– Page 106, #6

• Finish reading chapters 1 and 2