Implementation: Algorithm specification Traversing a 1D Array

Algorithms are created to allow users to tell a computer how to solve a problem. Understanding how to construct three of the most common algorithms is a critical skill for budding software developers.

Part ofComputing ScienceSoftware design and development

Traversing a 1D Array

To traverse an array means to access each element (item) stored in the array so that the data can be checked or used as part of a process.

In most high-level languages, it is necessary to create a variable that will track the position of the element currently being accessed. This variable is often referred to as a loop counter.

When used in high-level languages, the name given to the loop counter is usually ‘i’ or ‘counter’.

Traversing an array within upper and lower bounds

If a loop is set to repeat ten times (from 0 to 9) then:

  • during the first iteration the loop counter will hold the value 0
  • during the second iteration it will hold 1
  • during the third iteration it will hold 2 and so on

This lets the program access the elements stored in the array in order.

In the Reference Language example shown below, a variable named ‘i’ is used to track the position of the element being accessed during each iteration of the loop.

This code will count the number of times that a grade ‘A’ is found in the allGrades array.

Line 1 DECLARE allGrades INITIALLY [A, B, B, D, F, C, A, A, C, B]
Line 2	DECLARE a_total INITIALLY 0
Line 3	FOR i FROM 0 TO 9 DO
Line 4 IF allGrades [i]= 'A' THEN
Line 5 SET a_total TO a_total + 1
Line 6 END IF
Line 7	END FOR

The example below uses the same code again but this time with the loop counter as ‘counter’ rather than ‘i’.

Line 1	DECLARE allGrades INITIALLY [A, B, B, D, F, C, A, A, C, B]
Line 2	DECLARE a_total INITIALLY 0
Line 3	FOR counter FROM 0 TO 90 DO
Line 4 IF allGrades [counter]='A' THEN
Line 5 SET a_total TO a_total +1
Line 6 END IF
Line 7	END FOR

Traversing an array without upper and lower bounds

In Reference Language, it is also possible to traverse an array without stating the upper and lower bounds of the array.

Rather than setting the loop to repeat 0 to 9 times, a variable is stated that is used to identify each item in the array.

The loop construct begins with FOR EACH… and ends with END FOR EACH. In this example, the variable ‘grade’ will represent whichever value is held in the next element of the array. If there are no more values to traverse over, the loop will end.

Line 1	DECLARE allGrades INITIALLY [A, B, B, D, F, C, A, A, C, B]
Line 2	FOR EACH grade FROM allGrades DO
Line 3 IF grade = 'A'THEN
Line 4 SET a_total TO a_total +1
Line 5 END IF
Line 6	END FOR EACH