Going with the Flow

So far, all the programs we've seen simply compute answers to some problem. In fact, they all engage in the same computations regardless of what input is given. One of the most powerful features of a computer, however, is its ability to make decisions. That is to change it's course of action according to the results of some computations. (Of course, we may also make decisions based on the input directly; we're just doing a trivial computation and looking at that result.) Throughout Part 3, we'll be looking at decision making in programs and at their expression in C.

Flow of Control

In order to better understand this type of decision making we want to take a look at the concept of flow of control. If we have a code segment like:

x = y + z ;
printf( "%d\n", x ) ;
y = z * 2 ;

we say that the control flows from one statement directly to the next. This is illustrated in the following flow chart:

[Straight line flow chart]

Such straight-line or linear control flow will be the driving force in a program unless we introduce some mechanisms to break in that flow.

Two-Way Control Branching

The first alternative mode of control flow that we'll look at is the two-way decision. The flow chart for this mode of control looks like:

[Two-way branch flow chart]

The idea here is that we first test the condition in the diamond. If the condition is true, then control flows down the left branch of the diagram. If it is false, then control flows down the right branch of the chart. Either way, the control flow joins back up at the bottom of the diagram and continues downward.

Which blocks are executed in this flow chart if a=12 and b=7:

[Large nested branch flow chart]