Correspondence Between Loops and Arrays

Cross-Reference

For further discussion of the correspondence between loops and arrays, see Relationship Between Data Types and Control Structures.

Loops and arrays are often related. In many instances, a loop is created to perform an array manipulation, and loop counters correspond one-to-one with array indexes. For example, these Java for loop indexes correspond to the array indexes:

Example 16-34. Java Example of an Array Multiplication

for ( int row = 0; row < maxRows; row++ ) {
   for ( int column = 0; column < maxCols; column++ ) {
      product[ row ][ column ] = a[ row ][ column ] * b[ row ][ column ];
   }
}

In Java, a loop is necessary for this array operation. But it's worth noting that looping structures and arrays aren't inherently connected. Some languages, especially APL and Fortran 90 and later, provide powerful array operations that eliminate the need for loops like the one just shown. Here's an APL code fragment that performs the same operation:

Example 16-35. APL Example of an Array Multiplication

product <- a x b

The APL is simpler and less error-prone. It uses only three operands, whereas the Java fragment uses 17. It doesn't have loop variables, array indexes, or control structures to code incorrectly.

One point of this example is that you do some programming to solve a problem and some to solve it in a particular language. The language you use to solve a problem substantially affects your solution.

cc2e.com/1616

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.10.32