Document 7925897

Download Report

Transcript Document 7925897

Escape Sequence Characters
\n
\r
\t
\v
\b
\\
\”
\’
\?
\ddd
\xdd
new line
carriage return
horizontal tab
vertical tab
backspace
backslash
double quotation mark
single quotation mark
Question mark
ASCII code in octal format
ASCII code in hexadecimal format
Northeastern University
1
Flow Control 1
Decision 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)
Northeastern University
2
Decision Statements
• Boolean (Logic) Expressions
–
–
–
–
Operations on Boolean Variables
Binary: && (AND), || (OR)
Unary: ! (NOT or INVERSION)
Truth Table in C++
A
0
0
non-zero
non-zero
B
0
non-zero
0
non-zero
A && B A || B
0
0
0
1
0
1
1
1
A
0
non-zero
!A
1
0
– Strictly speaking, Boolean algebra has only TRUE (1) or
FALSE (0) but no non-zero.
Northeastern University
3
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.
Northeastern University
4
Arithmetic Expressions
– 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: ! ( ) [ ] --> , .
Northeastern University
5
• Operator Precedence
An 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.
Northeastern University
6
Operators
Associativity
function calls
right to left
() ++(postfix) --(postfix)
! +(unary) ++(prefix) --(prefix) &(unary) *(unary)
* / %
+(binary) -(binary)
< <= > >=
== !=
left to right
right to left
left to right
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
Northeastern University
7
• Precedence and associativity of operators
C++ 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
Northeastern University
8
• 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.
Northeastern University
9
Example
int
double
x = y + u;
v = x + y;
x, y;
u, v;
/* y+u is evaluated as double first. */
/* result is converted to int before assigned to x. */
/* 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 */
Northeastern University
10
Type Casting
• Syntax
– (data_type) Identifier
– data_type(Identifier)
– static_cast<data_type>(Identifier)
Northeastern University
11
• 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 ;
Northeastern University
12
– 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 a
if (a < 0 || a > 5)
cout << “a is out of range.\n”;
else
cout << “You have entered ” << a << endl;
Northeastern University
13
• 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.
Northeastern University
14
– 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();
}
Northeastern University
15
– 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.
Northeastern University
16
• 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)
;
Northeastern University
17
• 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)
Northeastern University
18
– 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.
Northeastern University
19
• Logical assignments
The 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
Northeastern University
20
• Nested if and multiple alternative decisions
Sometimes, 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.
Northeastern University
21
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;
Northeastern University
22
• 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.
Northeastern University
23
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”;
Northeastern University
24
– 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”;
Northeastern University
25
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”;
Northeastern University
26
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;
Northeastern University
27
case label2:
statement1;
statement2;
…
break;
…
case labelN:
statement1;
statement2;
…
break;
default:
statement1;
statement2;
…
break;
/* optional here */
}
Northeastern University
28
– 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.
Northeastern University
29
Switch (input) {
case ‘e’:
case ‘E’;
email();
break;
case ‘n’:
case ‘N’:
news();
break;
case ‘q’:
case ‘Q’:
quit();
break;
default:
re_input();
}
Northeastern University
30
– 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
Northeastern University
31
– 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;
Northeastern University
32
Homework
• Homework #1
– Page 105, #1
– Page 106, #6
• Finish reading chapters 1 and 2
Northeastern University
33