For loops and arrays are a great way of simplifying your code. Consider the task of displaying which students did better on which test.

Name

Test 1

Test 2

Bert

8

3

Fiona

5

7

Sally

7

6

George

7

7

Fred

5

4

We previously had the code -

Function compareTests(name As String, test1 As Number, test2 As Number)
    If test1 > test2 then
        PRINT name + " did better on test 1"
    else if test1 < test2 then
        PRINT name + " did better on test 2"
    Else
        PRINT name + " did equally well on both tests"
    End if
End function
compareTests("Bert", 8,3)
compareTests("Fiona", 5,7)
compareTests("Sally", 7,6)
compareTests("George", 7,7)
compareTests("Fred", 5,4)

We can further simplify this by first storing all of the values into arrays first.

Array

Position

1

2

3

4

Names array

5

Value

Bert

Fiona

Sally

George

Fred

Array

Position

1

2

3

4

Test1 array

5

Value

8

5

7

7

5

Array

Position

1

2

3

4

Test2 array

5

Value

3

7

6

7

4

 

compareTests(names(1), Test1(1), Test2(1))

compareTests(names(2), Test1(2), Test2(2))

compareTests(names(3), Test1(3), Test2(3))

compareTests(names(4), Test1(4), Test2(4))

compareTests(names(5), Test1(5), Test2(5))

Finally we can then write a FOR loop to go through the array.

FOR I=1 to 5

compareTests(names(I), Test1(I), Test2(I))

NEXT

Now that we have the above for loop it is a easy task to increase the number of students. All that would happen is that the FOR I=1 to 5 would change to FOR I=1 to 200 if 200 students were considered.