9.6 Arrays with Multiple Dimensions


9.6 Arrays with Multiple Dimensions

Arrays with more than one dimension can be defined to solve mathematical problems with matrices, computer games, and so on. Two-dimension arrays are easier to understand and matrices are the most common type of problems. These are mathematical structures with values arranged in columns and rows. Two index values are required, one for the rows and one for the columns.

To define a two-dimensional array, two numbers are defined, each in a pair of brackets. The first number defines the range of values for the first index (for the rows) and the second number defines the range of values for the second index (for the columns).

For example, the definition of a two-dimensional array named matrix with a capacity of 15 rows and 20 columns in KJP code is:

       constants          integer ROWS = 15          integer COLS = 20       variables          float matrix array [ROWS] [COLS]          . . . 

To reference the elements of a two-dimensional array, two indices are required. For example, the following KJP code sets all the elements of array matrix to 0.0:

          for j = 0 to COLS - 1 do            for i = 0 to ROWS - 1 do               set matrix [i][j] = 0.0            endfor          endfor 

For this initialization of array matrix, two loop definitions are needed, an outer loop and an inner loop (this is also known as nested loops). The inner loop varies the row index and outer loop varies the column index. The assignment statement sets the value 0.0 to the element at row i and column j.




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net