Structured Programming  «Prev  Next»
Lesson 3An unstructured program
Objective Identify the disadvantages of unstructured programs

Example Unstructured Program

Before digging into structured programming, let us have a look at an unstructured program.
Here is a program written in the BASIC programming language which averages the numbers that are input:

5 LET S = 0  
10 MAT INPUT V 
20 LET N = NUM 
30 IF N = 0 THEN 99 
40 FOR I = 1 TO N 
45 LET S = S + V(I) 
50 NEXT I 
60 PRINT S/N 
70 GO TO 5 
99 END

Example 1: Simple example of an infinite loop in Basic.
10 PRINT "INFINITE LOOP"
20 GOTO 10

Computer Science: Structured Approach Using C++

Example 2:

Second example of an infinite loop in Visual Basic:

dim x as integer
do while x < 5
  x = 1
  x = x + 1
loop

Explanation of Example 2:
This creates a situation where x will never be greater than 5, because at the beginning of the loop code x is given the value of 1, hence, the loop will always end in 2 and the loop will never break. This can be fixed by moving the x = 1 instruction outside the loop. Essentially what this infinite loop does is to instruct a computer to keep on adding 1 to 1 until 5 is reached. Since 1+1 always equals 2, the condition will not be fulfilled.

The important point to appreciate in these 2 unstructured examples is, that while both programs perform exactly the same task (that is they are infinite loops), the code must be written so that a structured walkthrough will be possible.
This principle becomes more pronounced as the program increases in size. Large programs without structure are much more difficult and expensive to develop and maintain than structured programs, and thus are often referred to as spaghetti code.
In the next lesson we will examine pseudocode. This is used to describe the logic of a program in a way that is independent of any particular programming language.