Program Flow

Back in the good old days, program execution began at the top of the code and proceeded a line at a time towards the bottom. With modern multi-tasking, event-driven environments, this tends not to be the case, but some of these techniques can still be used within individual procedures and functions.

There are two main ways of controlling the flow within a program - we can other repeat sections of the program until a process is completed, or we can jump to another section of the program to perform another function. The final method, used with modern graphical user interfaces, to control flow using the user's input.

Looping

Looping is the name given to repeated commands within a program - the commands can either be repeated a pre-determined number of times, or they can be repeated until a certain condition occurs.

For...

The most common type of loop is the for loop, which seems to exist in most programming languages, including BASIC, C/C++, JavaScript and Pascal. For loops have associated with them an integer variable which is either incremented or decremented between two limits - this determines the number of times that the code within the loop is executed. For example, the following loops count from 1 to 10, printing the numbers as they go:

VisualBASIC

dim loop_counter as integer

for loop_counter = 1 to 10

	print loop_counter

next loop_counter

JavaScript

var loop_counter;

for(loop_counter=1;loop_counter<=10;loop_counter++)
{
	document.write(loop_counter);
}

Note that you can actually use the variable within the loop - it's particularly useful when used as an array index (see the variables page). You can even change the value of the variable you use as a loop counter, although generally this isn't considered to be good practice.

You don't need to start at 1 and count upwards one at a time - you can count in any size step and in either direction. For example, to count down from 100 to 0 in fives, you could use

for n = 100 to 0 step -5
or
for(n = 100, n >= 0; n = n - 5)

While...

Another type of loop repeats a section of code, not a pre-determined number of times, but while a particular condition exists. Both BASIC and JavaScript/C/C++ have a while... loop - some languages also have a repeat...until loop which behaves in a similar way (except that the condition will be reversed).

Here is a simple while... loop that counts to 10 and prints the results:


VisualBASIC

dim loop_counter as integer

loop_counter = 1

while loop_counter <= 10

	print loop_counter
	loop_counter = loop_counter + 1

wend

JavaScript

var loop_counter;

loop_counter = 1;

while(loop_counter<=10)
{
	document.write(loop_counter);
	loop_counter++;
}

Of course, this isn't a particularly worthwhile use of while... as it does the same thing as the for loops above. A better (but more complex) example is shown below.

Nesting

It is possible to put one loop inside another - this is known as nesting. Nested for loops are useful for drawing tables or rectangular arrays - e.g. the Puzzle page uses two nested for loops to plot the rows of tiles onto the page. The Lottery page uses two nested for loops and a while loop to choose the balls - the code for this is shown below:

VisualBASIC

Sub choose()
   
	Dim ball_no as integer
	Dim previous as integer
	Dim unique as boolean
       
	For ball_no = 1 To 6
	
		unique = false

		while unique = false

			ball(ball_no) = int(rnd()*49) + 1
			unique = true

			for previous = 1 to (ball_no - 1)

				if ball(previous) = ball(ball_no) then unique = false

			next
		wend
	Next
   
End Sub

JavaScript

function choose()
{
	var ball_no, previous, unique;
        
	for (ball_no = 0; ball_no < 6; ball_no++)
	{

		unique = false;

		while (unique == false)
		{

			jball[ball_no] = Math.round(Math.random() * 49) + 1;
			unique = true;

			for (previous = 0; previous < ball_no; previous++)
			{

				if (jball[previous] == jball[ball_no]) unique = false;

			}
		}
   	}
}

The outside loop (with the counter ball_no) is used to iterate through the six balls, to generate the six values. The inner loops ensure that the six values are unique - repeatedly generating pseudorandom numbers and checking them against the numbers drawn previously until a new (i.e. non-duplicate) value is found.

Conditional Branching

Another way to control program flow is to use conditional branching - that is, to perform an action or jump to another section of the program, depending on some sort of condition.  This is also known as selection, or making a decision.

The most common way to do this is using an if... then... else... construct. The exact syntax of this varies according to the programming language you're using, but generally the code would look something like this:

VisualBASIC

Function odd(x as integer)

	if x AND 1 then

		odd = true

	else

		odd = false

	end if

End Function

JavaScript

function odd(x)
{
	if(x & 1)
	{
		return true;
	}
	else
	{
		return false;
	}
}

The function odd() takes an argument, x, and returns whether or not x is an odd number (using bitwise AND - represented by & in JavaScript). Note that JavaScript (and similarly C and C++) doesn't use . The else part is optional - if there is no alternative action, then you can miss it out.

Case/Switch

The if... command can also be nested, but if there are more than two alternative, you may be better using another method, such as the switch() function in C/C++, which has the following syntax:

switch (x)
{
	case 0:
		...
		break;

	case 1:
		...
		break;

	...

	default:
		...
		break;
}

Arrays

Arrays can also be used for selection, as I explain in this TES Subject Genius article.

Events

With modern graphical user interfaces, program flow is often controlled through the use of events. That is to say that functions and procedures are initiated by user actions, such as one of the following:

There are many more events than this, and their names can change according to your environment. Each event has an associated function that is called when the event occurs - these functions can then call others.

For someone who started programming before GUIs became popular, this idea can take a bit of getting used to, as there doesn't tend to be any flow of control through the program as a whole, and the user can choose to click buttons or perform action in any order. This makes testing more critical, of course, and you should take account of all possible permutations in both your code and test plan.

Scratch supports different forms of structures for repetition - it could be a good introduction to the idea of loops for KS3 Computing students.  I have created some Scratch examples that use different programming techniques.