Branching and Looping




Document: Software Engineering 1: Course Notes

next A Shady Character?
up Chapter 2 pp. 11-19
previous Making a statement!

Branching and Looping

So far we have two kinds of statement: "expression" statements, and "block" or "compound" statements. Expression statements are just executed. The (simple) statements within a block are executed in simple sequence. As yet we have no way of making the execution of a program depend on, or vary in sympathy with, a logical value determined at execution time.

There are two principle kinds of variation we typically might want: branching (or, as Alcock says, selection) and looping. In branching we have alternative things we might want our program to do; in looping we want to do a particular thing repeatedly - over and over again. C provides several different ways of achieving both of these effects; but for the time being, it is sufficient to have at least one way of doing each in our C armoury, and that is what Alcock now introduces. He presents the if - else kind of statement to achieve branching, and the for statement to achieve looping or "iteration".

Examine the formats which Alcock specifies for the if-else and for statements very carefully. Notice that, in each case, the statement format contains one or more other statements as components nested within it. In the case of an if statement, the nested statement is to be executed if and only if the expression value fed into the if is "true" (non-zero); in the case of if-else exactly one or the other of the nested statements will be executed depending on whether the expression is classified as "true" or "false"; and in the case of the for, the nested statement is what gets executed repeatedly.

My point here is to draw your attention to the fact that the nested statement is grammatically, or "syntactically", allowed to be any kind of statement at all.

So, as Alcock shows in his example, the statement nested within an if can, itself, be another if statement (complete with a further, nested, statement); equally, the nested statement could be a for statement or, indeed, a compound statement. The latter means that, with one if statement, we can control execution of a whole block of statements - simply by enclosing them in braces to make a single compound statement.

Furthermore, the nesting of statements within statements can, in theory, be made as deep as we like! However, in practice, programs get rather difficult for human beings to understand if statements get nested too deeply within each other - so don't get carried away with this!




Document: Software Engineering 1: Course Notes

next A Shady Character?
up Chapter 2 pp. 11-19
previous Making a statement!



McMullin@ugmail.eeng.dcu.ie
Wed Apr 12 19:40:14 BST 1995