rws - 9 months ago 54

Java Question

Does the for loop below in java visit all indexes of adjacencyMatrix or does it only do

`adjacencyMatrix[1][1];`

adjacencyMatrix[2][2];

adjacencyMatrix[3][3];

adjacencyMatrix[4][4];

etc.

`for (int i = 1; i <= number_of_nodes; i++)`

for (int j = 1; j <= number_of_nodes; j++)

adjacencyMatrix[i][j] = adjacency_matrix[i][j];

Thanks

Answer

This will *not* visit all indexes of the array because array indexes begin at 0, not 1. In other words, the first element of the 2D array would be *adjacencyMatrix[0][0]* so you should start both of your iterations from 0.

If the array has a length of 5, the largest index would therefore be four so be careful how far you iterate.

**For example, if you did:**

```
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
```

*Then it would visit:*

```
adjacencyMatrix[1][1];
adjacencyMatrix[1][2];
adjacencyMatrix[2][1];
adjacencyMatrix[2][2];
etc...
```

**If you did:**

```
for (int i = 1; i <= number_of_nodes; i++)
adjacencyMatrix[i][i] = adjacency_matrix[i][i];
```

*Then it would visit:*

```
adjacencyMatrix[1][1];
adjacencyMatrix[2][2];
adjacencyMatrix[3][3];
adjacencyMatrix[4][4];
```