Matthew
Matthew

Reputation: 15

Which is better, a single for loop or double for loop to iterate through 2-D array? C++

Let's say that I have a 9-by-9 2-D array. Is there a difference between looping through with a single loop or multiple loops?

for (int i = 0; i < 81; i++)
  currentEdit[i / 9][i % 9] = 0;

VS.

for (int i = 0; i < 9; i++)
   for (int j = 0; j < 9; j++)
      currentEdit[i][j] = 0;

Upvotes: 1

Views: 532

Answers (1)

Rodrigo
Rodrigo

Reputation: 81

The right choice is multiple loops. Keep in mind that it will perform much less operations since it does not have to divide or calculate the module to access the array position.

This is the right choice:

for (int i = 0; i < 9; i++)
   for (int j = 0; j < 9; j++)
      currentEdit[i][j] = 0;

Upvotes: 2

Related Questions