2D arrays

11.5.2.1 use the technical terms associated with arrays including upper and lower bounds 
11.5.2.3 write program code using 1D and 2D arrays 

Two dimentional arrays (Matrix)

A two-dimensional array (2D array) is an array where each element is represented by a one-dimensional array.

Each element of a two-dimensional array has two indices: row number (i) and column number (j).

Programmers usually indicate the line number of the variable i , the number of the column of the variable j.

You can get the value of an element by two indexes. For example,

arr[2][3]

A two-dimentional arra is used to create a table of data in rows and columns with the same data type.

Create 2D Array

We can create the two-dimensional array shown above:

$grid= array(
    array("", "", "", "A", ""),
    array("", "", "", "", " C "),
    array("", "", "", "", ""),
    array("", "", "B", "", ""),
    array("", "", "", "", "") );

An array $grid we can visually represent in a table:

$grid[0][3] = 'A'
$grid[3][2] = 'B'
$grid[1][4] = 'C'

2D iteration

Nested loops are used to iterate over all elements of a two-dimensional array.

FOR i = 0 to N

      FOR j = 0 to N 
            ...
     endFOR

endFOR
Examples:

Fill 2D array random number (PHP)

for ($row = 0; $row < 6; $row++){
      for ($col = 0; $col < 5; $col++) {
            $grid[$row][$col]=rand(1, 100);
      }
}

Output 2D array in table (PHP)

echo "<table border=1>";  
for ($row = 0; $row < 6; $row++) {
    echo "<tr>";
      echo "<td>Row number $row </td>";
      for ($col = 0; $col < 5; $col++) {
            echo "<td align=center>".$grid[$row][$col]."</td>";
      }
      echo "</tr>";
}
echo "</table>";

Next line

print "<br>";

 


Questions:


Exercises:


Tasks:

Категория: Algorithms | Добавил: bzfar77 (09.02.2023)
Просмотров: 2234 | Теги: array, nested loops, php | Рейтинг: 5.0/1
Всего комментариев: 0
avatar