Chapter 7: Advanced Control Flow

Chapter Goals

Multiple Alternatives

Multiple Alternatives (Coins Flowchart)

Multiple Alternatives (coins6.cpp)

Multiple Alternatives

Multiple Alternatives (richter.cpp)

Nested Branches

        The two-level decision process is reflected in two levels of if statements.

Nested Branches (tax.cpp)


Boolean Operations


 The && and || operators are computed using lazy evaluation.

DeMorgan's Law


The for Loop

The for Loop (Syntax 7.1: for Statement)

Syntax 7.1 : for Statement

for (initialization_expression; condition; update_expression) statement
Example:
for (int i = 1; i <= 10; i++) sum = sum + i;
Purpose: Execute the initialization statement. While the condition remains true, execute the statement and update the expression.

The for Loop (forfac.cpp)


The do Loop

The do Loop (sqroot.cpp)

The do Loop (Syntax 7.2: do/while Statement)

Syntax 7.2: do/while Statement

do statement while (condition);
Example:
do x = sqrt(x); while (x >= 10);
Purpose: Execute the statement, then test the condition, and repeat the statement while the condition remains true.

Nested Loops

Nested Loops (table.cpp)

Nested Loops


Processing Text Input

Processing Text Input (words.cpp)


Simulations

Simulations (dice.cpp)

Simulations


Simulations (Buffon Needle Experiment)

Simulations (buffon.cpp)


The point of this program is not to compute pi (after all, we needed the value of pi in the deg2rad function). Rather, the point is to show how to a physical experiment can be simulated on the computer.