1.5 Flow controls
Flow controls refer to the controls of orders of statements/instructions of programs to be executed. Flow controls determine the next statement (in source code program) or instruction (in executable program) to be executed.
C provides the three basic flow control structures:
- sequence
- selection
- repetition
1.5.1 Sequence
The sequence control executes program instructions in the linear order of their appearances in the program. Sequence control is the default program flow control in programs. That is, a sequence of statements in source code programs will be executed one after another in linear order by sequence control.
Example:
int a = 10;
int b = 20;
int c = a + b;
When executing the above program fragment, it will first write value 10 to variable a
, then write 20 to b
, then compute a+b
and write result of a+b
10 to c.
1.5.2 Selection
A selection control (also called decision or branching) is to alter the default flow of sequential order of instructions, enabling to jump from one instruction to another depending on a condition.
C provides four decision control statements:
1.5.3 Repetition
A repetition control (also called loop) statement sets to execute a block of statements over and over again until a certain condition is satisfied. Each cycle of executing the block of statements is called an iteration. C provides three repetition statements.
The difference between while and do-while loops is that a while loop statement executes the conditions first, if a true value is derived, it executes the loop block, and so on. A do-while statement executes the loop block fist, then checks the conditions. If a true value is derived, then it executes the loop block again, and so on.
1.5.4 Other control statements
C also provides additional control statements break
, continue
, and a more flexible control statement goto
.
The goto statement is a flexible and powerful flow control statement provided by C. goto statement can be used to do selection and repetition controls. The above program is an example of using goto statement for repetition controls.
1.5.5 Exercises
Self-quiz
Take a moment to review what you have read above. When you feel ready, take this self-quiz which does not count towards your grade but will help you to gauge your learning. Answer the questions posed below.