Programming Fundamentals/Displaying Array Members
Overview
[edit | edit source]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.
Discussion
[edit | edit source]Accessing Array Members
[edit | edit source]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[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 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."[1]
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[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
[edit | edit source]- 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.[2]
- flexible coding
- Using the size of an array to determine the number of loop iterations required.