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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.55188715,"math_prob":0.9991861,"size":962,"snap":"2022-40-2023-06","text_gpt3_token_len":373,"char_repetition_ratio":0.13987474,"word_repetition_ratio":0.16086957,"special_character_ratio":0.44802496,"punctuation_ratio":0.20425531,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9979312,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-02-04T12:57:25Z\",\"WARC-Record-ID\":\"<urn:uuid:e90d1686-e1aa-4bf3-bf87-343800e84000>\",\"Content-Length\":\"34461\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:784f9c82-7cbb-4f4c-a403-7fe67c5d5701>\",\"WARC-Concurrent-To\":\"<urn:uuid:071256d6-611d-4654-913e-3e43295ab924>\",\"WARC-IP-Address\":\"135.125.207.217\",\"WARC-Target-URI\":\"https://www.cerix.it/matrix-loop-techniques/\",\"WARC-Payload-Digest\":\"sha1:T7AURSDCVZAOV2YTG2MEAX5X4NBNOR6N\",\"WARC-Block-Digest\":\"sha1:KCZZ6VN4TAH6O7KVEEARUH6FWIZBY77E\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764500126.0_warc_CC-MAIN-20230204110651-20230204140651-00545.warc.gz\"}"}