Presentation is loading. Please wait.

Presentation is loading. Please wait.

Flow of Control.

Similar presentations


Presentation on theme: "Flow of Control."— Presentation transcript:

1 Flow of Control

2 Flow of Control C is a sequential language
statements in a program are executed one after another To change flow of control, use choice instructions: if, switch iterative instructions: while, for OR recursion you may need operators

3 Operators for them < > <= >= == != Relational Operators
1 if the specified relationship is true, and 0 if false. i < 7 > j > 5 <= k <= 4 >= p >= 3 ==  if (x == 4) evaluates to true (or 1) if x is equal to four. if (x = 4) is taken to be true because (x = 4) evaluates to a nonzero value (4). The expression also assigns the value 4 to x. != nChoice != 'Y' TRUE means any value other than 0

4 Relational Operators Expressions Evaluates as (3 == 3) && (4 != 3)
(3 == 3)  && (4  !=  3) True (1) because both operands are true (4 > 2) || (7 < 11) True (1) because (either) one operand/expression is true (3 == 2)  &&  (7 == 7) False (0) because one operand is false  ! (4 == 3) True (1) because the expression is false NOT(FALSE) = TRUE NOT(TRUE) = FALSE The logical OR (||) should not be confused with the bitwise OR (|) operator. For example:    1 || 4 evaluates to 1 (or True || True = True) while    1 | 4 (0001 | 0100 = 0101) evaluates to 5

5 some trivial examples

6 some tricky examples

7 short-circuit the evaluation stops as soon as the outcome is known
expr1 && expr2 if expr1 is evaluated to be false, expr2 needs not be evaluated expr 1 || expr 2

8 The Compound Statement
A compound statement is a series of declarations and statements surrounded by braces { } { int a, b, c; a += b += c; printf (“a = %d, b = %d, c = %d\n”, a, b, c); } a compound is usually called “block” expression statements a + b + c; ; /* empty statement */

9 if statement if (expr) (then) statement | block
statement can be an empty one same for else statement

10

11

12 Iterative Statements while, for, and do statements
provide iterative action goto, break, continue, return statements cause an unconditional transfer SE people hate these (except return)

13

14 for statements comma operators
for ( sum = 0, i = 1 ; i <= n ; ++I ) sum += i; for (sum = 0, i = 1 ; i <= n ; sum += i, ++i)

15 do statement a variant of while statement do { statements } while expr
the block is executed first, and then the expr is evaluated you should be able to convert do statement to while statement, and vice versa

16

17 goto statement jump to a label it is considered harmful, but .....
goto label; label: /* label is an identifier */ it is considered harmful, but .....

18

19 break statement an exit from a loop

20 continue statement stop the current iteration and goto the next iteration

21 switch statement

22 conditional operators
x = (y < z) ? y : z if (y < z) x = y; else x = z; equals


Download ppt "Flow of Control."

Similar presentations


Ads by Google