简体   繁体   中英

In C#, How can I iterate through a entire 2D Array and count the number of 0s?

I've been trying to iterate through an entire 2D array and count the number of 0s. How can I do this?

I'm sure I have to use the following to make the program work:

  • Use an outer for loop to iterate through the rows of the array
  • Use an inner for loop to iterate through the columns of the array
  • if matrix[row,col] == 0 , increment a variable
  • To get the number of rows of the 2D array, use the method matrix.GetLength(0) , and to get the number of columns of the array, use the method matrix.GetLength(1)

Here's what I have attempted so far:

public int Test9(int[,] matrix)
{
    int b = 0;
    for (int i = 0; i < matrix.GetLength(0); i++)
        for (int j = 0; j < matrix.GetLength(1); i++)
        {
             b = matrix[i, j];
        }
}

This is how you can do it..

 public int Test9(int[,] matrix)
    {
       int zeroCounter = 0;
       for (int i = 0; i < matrix.GetLength(0); i++)
        for (int j = 0; j < matrix.GetLength(1); j++)
        {
                if(matrix[i, j] == 0)
                {
                    zeroCounter++;
                }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM