Matrix Loop Techniques

# Matrix Loop Techniques

Lets image we have in input a Matrix (m,n) rows and columns  in the format of a 2D array.

``````int matrix[m][n] = {
{ 1, 3, 7, 0, 4 },
{ 9, 2, 5, 2, 8 },
{ 6, 2, 3, 4, 1 },
{ 1, 2, 3, 4, 5 },
{ 8, 3, 7, 4, 5 }
};
``````

## Simple Loop

A simple row by row loop

``````for (int r = 0; r < rows; r++)
{
for (int c = 0; c < clms; c++)
{
// DO SOMETHING ON THE ELEMENT (i,j)
matrix[r][c];
}
}
``````

## Columns Loop

``````    //  Traverse through all columns
for (int c = 0; c < rows; c++)
{
//iterate over the column incrementig r
for (int r = 0; r < clms; r++)
{
// DO SOMETHING
matrix[r][c]; //c is fixed during this loop
}
}
``````

## Snake Loop

``````  for (int r = 0; i < rows; r++)
{
// If current row is even, go from left to right
if (r % 2 == 0)
{
for (int c = 0; c < clms; c++)
{
// DO SOMETHING
}
}
else // If current row is odd, go from right to left
{
for (int c = clms - 1; c >= 0; c--)
{
// DO SOMETHING
}
}
}
``````

By reversing the two innermost loops, the mirror pattern can easily be obtained.