Parallel arrays involve having at least two arrays with a one-to-one correspondence between their elements.
Each element in the first array corresponds to an element in the second array, and both arrays must have the same length.
This concept can extend to any number of arrays.
Arrays do not need to be of the same type (e.g., an int array and a string array).
This approach bypasses the usual C requirement that all elements in an array must be of the same type.
Case Study: Gordon's Bakery
Gordon needs to print each employee's name along with the number of hours they worked.
Implementation
A loop is needed to iterate over both arrays.
A for loop is appropriate because the number of elements is known in advance, and elements can be accessed using the index.
A for-each loops are not appropriate because it only operates on a single array and cannot satisfy the need to iterate through two arrays at the same time.
The loop condition uses the length of one of the arrays (e.g., hours.length), assuming both arrays have the same length.
Inside the loop, both the employee's name and hours worked are outputted, separated by a tab character for readability.
Code Example
The program iterates through the names and hours arrays, printing each name and corresponding hours.
Example: Yooray worked twenty hours.
Improvements
Error Handling
Check if the arrays have different lengths to avoid runtime errors due to out-of-bounds access.
If lengths differ, print an error message and exit the method.
Code Example
An if statement checks if the arrays have different lengths.
If they differ, an error message is printed.
Testing
Focus on the number of elements in both arrays.
Absence case: both arrays are empty.
Boundary case: each array contains a single element.
Multiple values: arrays contain multiple corresponding values (as in the case study).
Arrays with different lengths: test cases where there are more hours than names, and vice versa.
Issues with Parallel Arrays
There is no built-in way to enforce the one-to-one correlation between arrays.
The only requirement is that the arrays have the same number of elements, but there's no guarantee of maintaining the same order.
Sorting arrays separately can lead to a loss of correlation.
Example: Sorting the hours array numerically and the names array alphabetically disrupts the original association.
Code Example
Originally, UA worked twenty hours, but after sorting, he appears to have worked fifty hours.
Testing
This scenario is covered in the third test case, when testing multiple values.
Advantages of Parallel Arrays
Improve the functionality and readability of arrays.
Provide better presentation for the user.
Disadvantages of Parallel Arrays
They are still just an example of using multiple one-dimensional arrays.
While they are useful and more complex than a single array, they remain inherently simplistic and carry certain risks.
Multidimensional arrays offer a tighter integration between data elements.