课程链接:https://ocw.mit.edu/courses/e...
L.02 Flow of Control
1. Motivation
Alter the order in which a program's statements are excuted, the control flow.
2. Contorl Structure
2.1 Conditionals
- Relational operator:
>, < , ==, !=, <=, etc.
- Logical operator:
&&(and), ||(or), !(not)
2.1.1 if, if-else and else if
if
conditional:
if(condition){ statement 1 statement 1 ...}if(condition) statement only 1
if-else
conditional:
if(condition){ statement 1 statement 2 ...}else{ statement 3 statement 4}if(condition) statement only 1aelse statement only 1b
if-else if
conditional:
if(condition){ statement 1 statement 2 ...}else if(condition){ statement 3 statement 4}
2.1.2 switch
May or may not excute certain statements.
switch(expression){ case constant1: statementA1 statementA2 ... break; case constant2: statementB1 statementB2 ... break; ... default: statementZ1 statementZ2 ...}
2.2 Loops
2.2.1 while and do-while
while (condition){ statement 1 statement 2 ...}while (condition) statement only 1
do{ statement 1 statement 2 ...}while(condition);
Note: Statement 1&2 in do-while
will be excuted one time at least.
2.2.2 for
for (initialization; condition; incrementation){ statement 1; statement 2;}// the counter already defined, no need to get a new onefor (; i<10; i=i+1){ statement;}// From 0 to 9, 10 times in totalfor (int i=0; i<10; i=i+1){ statement;}
2.2.3 Equivalent loops
for(initialization; condition; increment){ statement;}// Rewriteinitialization;while(condition){ statement; increment;}