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 (known in GCSE exams at count-controlled loops), or they can be repeated until a certain condition occurs (known in GCSE exams at condition-controlled loops).

Count-Controlled Loops - 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);
}

Python

for loop_counter in range(1, 11):
	
   print(loop_counter)




Note that Python is the odd one out because it doesn't require the loop counter to be declared, and also because there is no keyword to end the repeated section - it's controlled by the indentation. Another quirk of Python is that it doesn't really count, unlike the other two examples - the Python for only loops over an iterable (such as a string or a list), like for each... in some other languages. The range() command simply creates a list for you.

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, for(n = 100, n >= 0; n = n - 5) or for n in range(100, -1, -5).

Condition-Controlled Loops - 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

   Console.WriteLine(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++;
}

Python

loop_counter = 1

while loop_counter <= 10:

   print(loop_counter)
   loop_counter += 1




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. A selection sort uses nested loops, and they're also used for producing combinations, such as packs of cards or a binary counter.

The examples below show a procedure that draws a character-based rectangle with the given dimensions:

VisualBASIC

Sub rectangle(width, height)
   
   Dim row as string
       
   for y = 1 to height

      row = ""

      for x = 1 to width:

         row = row & "#"

      Next

      Console.WriteLine(row)
   
   Next

End Sub

JavaScript

function rectangle(width, height)
{
   var row;

   for(var y = 0; y < height; y++)
   {

      row = "";

      for(var x = 0; x < width; y++)
      {

         row = row + "#";
      
      }

      console.log(row)

   }
}

Python

def rectangle(width, height):

   for y in range(height):

      row = ""

      for x in range(width):

         row += "#"

      print(row)









The outer loop, with counter y, repeats once for each row in the rectangle, which the inner loop, , with counter x, repeats once for each unit of width, adding a character as it goes.

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 (especially for GCSE), 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;
   }
}


Python

def 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;
}

Python supports a similar structure from version 3.10, but uses the keyword match rather than switch.

Arrays

Arrays can also be used for selection, as I explain in this blog.

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.