C Programming/Flow Control

Objective

 * Familiarise yourself with control structures.
 * Learn how to use  statements.
 * Learn how to use the  statement.
 * Learn how to use the  loop.
 * Learn how to use the  loop.
 * Learn how to use the  loop.

if ... else
This structure lets the program perform one of two actions, depending on the value of an expression. Its basic structure is:

If a branch contains only one statement, the  are optional. You can use an  without an accompanying.

An example of if ... else in action:

Statement 2 can be an if statement, which can be used to create an if ... else if ... else structure, e.g:

switch ... case ... default
The switch statement will go to one of several locations, depending on the value of an expression. The last example can be written using a switch statement as:

A few notes:
 * The control statement (in this example the variable ) has to have integral type (character, short integer, integer bit-field, all of these signed or not, or an object of enumeration type); integral promotion will ensure the type is either   or.
 * The  statement ensures execution does not fall through to the next statement.
 * Control passes to the  label if none of the other case constants match the value of the control expression; if there is no   statement, none of the sub-statement of the switch is executed.

for loops
The  statement has the format:

is usually variable initialization;  is the condition that keeps the loop active, usually a relational expression;   is usually an increment or decrement of one or more variables. If the loop contains only one statement, the  are optional. Here is an example of the for loop in action:

,, and   can be omitted since these are optional. When  is omitted, the condition is assumed permanently true. Although you can omit parts of a for statement, you'll still need to separate the omitted parts with a semicolon.

while loops
A  loop has the following format:

is evaluated. If it is true (non-zero) the body of the loop, the, is executed;   is then re-evaluated and if true the body is executed again. Only when  is false (zero) will   be skipped and the loop terminated. If the loop contains only one statement, the  are optional.

do ... while loops
This is the format of the  iteration statement:

is executed repeatedly as long as  evaluates to anything but zero. If the loop contains only one statement, the  are optional. Here is an example of a do...while loop in action:

This will loop repeatedly, asking for input, until either  or   is entered. Note: A do...while loop is guaranteed to run at least once.