Programming Fundamentals/Displaying Array Members
To display all array members, get the value of each element using a
for loop and output the element using index notation and the loop control variable.
Accessing Array Members
Let's say we want to create an integer array named "ages" with five values of 49, 48, 26, 19, and 16. 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 a terrible method for arrays that contain hundreds or thousands of values due to having to type out each element. 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 get the value of 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 repetition with abstractions, or repetition of the same data. Instead, programmers should use data normalization to avoid redundancy.
- flexible coding
- Using the size of an array to determine the number of loop iterations required.