Control flow is important in code. It is necessary to make decisions such as "if x is true, do this, otherwise, do something else". There are two types of control flow which we will discuss: conditionals and loops.

Conditionals allow the programmer to express logic in their programs.

If/Else

If statements allow the programmer to express decision:

The <expression> is evaluated first, and if found to be true (i.e. non-zero) then <statement-block-1> is executed. Note that a statement block can be either a single statement, or multiple statements enclosed in braces, e.g.: { <statement1>; <statement2>; }. If <expression> is found to be false (zero) then <statement-block-2> is executed, the "else" clause is optional, since in many cases we do not need to execute an alternative statement if the expression is false. Further you can test more than one expression using the "else if" statements.

Switch/Case

An alternative to long "else if" blocks is the "switch" statement. The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer or char values.

The case labeled <default> is executed if none of the other cases are satisfied. Example:

The "break" statement causes an immediate exit from the switch. The cases serve as labels, so after the code for one case is done, execution will fall through to the next unless you break out of the switch. "break" can also be used to exit a while, for, or do loop.

 
©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement