Home > Blockchain >  How can I make nested loop by using only one for loop?
How can I make nested loop by using only one for loop?

Time:01-14

I saw this code from stack overflow

int[,] matrix = new int[5, 10];     
int row = matrix.GetLength(0);
int col = matrix.GetLength(1);      

for (int i = 0; i < row * col; i  )
{
    matrix[i / col , i % col] = i   1;
}

and someone say that it`ll make nested loop. I was trying to crack this code, but I cannot. somebody please explain how this code works.

CodePudding user response:

If you have two nested for loops, one from 0 to row and one from 0 to col, the two loops will together execute row * col times. So you can replace the nested loops by a single loop that runs from 0 to row * col, and that’s exactly what’s been done here.

The only thing you need to do then is to find the separate loop indices of the nested loops (let’s call them j and k) from the single loop index i.

The way to do this is to consider a row * col table filled with the numbers 0…row * col. How do we find the row and column index (j and k, respectively) for a given entry i? Well, the code you’ve posted tells us:

int j = i / col // row index
int k = i % col // col index

CodePudding user response:

Technically, this code has no nested loop, per se. However, it counts from 0 to 5 * 10 - 1, and in each iteration calculates the row and column indexes. The following is probably better understandable:

for (int i = 0; i < row * col; i  )
{
    int rowIndex = i / col; // divide by column count = row index
    int colIndex = i % col; // modulo by column count = column index
    Console.WriteLine($"i: {i} => row: {rowIndex}, col: {colIndex}");
    matrix[rowIndex, colIndex] = i   1;
}

Write down the actual numbers and you will see for yourself that for iterations 0 to 9 you will get rowIndex == 0 and colIndex having values 0 to 9, then for iterations 10 to 19 you get rowIndex == 1 and colIndex having values 0 to 9 etc.

A nested-loop variant would, naturally, look like this:

for (int rowIndex = 0; rowIndex < row; rowIndex  )
{
  for (int colIndex = 0; colIndex < col; colIndex  )
  {
    int i = rowIndex * col   colIndex; // back-calculate 'i'
    Console.WriteLine($"i: {i} => row: {rowIndex}, col: {colIndex}");
    matrix[rowIndex, colIndex] = i   1;
}

The one-loop version has the nested look unrolled and replaced with mathematical operations (division, modulo) instead.

  •  Tags:  
  • Related