To display all array members, visit each element using a
for loop and output the element using index notation and the loop control variable.
Accessing Array Members
Assume an integer array named ages with five values of 49, 48, 26, 19, and 16, respectively. In pseudocode, this might be written as:
Declare Integer Array ages
Assign ages = [49, 48, 26, 19, 16]
To display all elements of the array in order, we might write:
While this works for short arrays, it is not very efficient, and quickly becomes overwhelming for longer arrays. One of the principles of software development is don’t repeat yourself (DRY). Violations of the DRY principle are typically referred to as WET solutions, which is commonly taken to stand for either “write everything twice”, “we enjoy typing” or “waste everyone’s time”.
Rather than repeating ourselves, we can use a for loop to visit each element of the array and use the loop control variable as the array index. Consider the following pseudocode:
Declare Integer Array ages Declare Integer index Assign ages = [49, 48, 26, 19, 16] For index = 0 to 4 Output ages[index] End
This approach is much more efficient from a programming perspective, and also results in a smaller program. But there is still one more opportunity for improvement. Most programming languages support a built-in method for determining the size of an array. To reduce potential errors and required maintenance, the loop control should be based on the size of the array rather than a hard-coded value. Consider:
Declare Integer Array ages Declare Integer index Assign ages = [49, 48, 26, 19, 16] For index = 0 to Size(ages) - 1 Output ages[index] End
This method allows for flexible coding. By writing the for loop in this fashion, we can change the declaration of the array by adding or subtracting members and we don’t need to change our for loop code.
- don’t repeat yourself
- A principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions, or repetition of the same data, using data normalization to avoid redundancy.
- flexible coding
- Using the size of an array to determine the number of loop iterations required.
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming