Displaying Array Members
Overview
To display all array members, visit each element using a for
loop and output the element using index notation and the loop control variable.
Discussion
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[5]
Assign ages = [49, 48, 26, 19, 16]
To display all elements of the array in order, we might write:
Output ages[0]
Output ages[1]
Output ages[2]
Output ages[3]
Output ages[4]
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”.[1]
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[5] 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[5] 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.
Key Terms
- 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.[2]
- flexible coding
- Using the size of an array to determine the number of loop iterations required.
References
- archive.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming