简体   繁体   English

C#使用Foreach循环以矩阵格式打印2D数组

[英]C# Printing a 2D Array in Matrix Format Using a Foreach Loop

I am trying to create an array that will print out times tables. 我正在尝试创建一个将打印时间表的数组。 The first column is the 1 times table, the second is the 2 times table and so on. 第一列是1倍表,第二列是2倍表,依此类推。 The user is asked for an input that will determine the number of rows and columns. 要求用户输入将确定行数和列数的输入。 I want to print the array in matrix format using a foreach loop. 我想使用foreach循环以矩阵格式打印数组。 It works fine when I use a for loop but I would like to know how to achieve the same output using a foreach loop. 当我使用for循环时,它工作正常,但我想知道如何使用foreach循环实现相同的输出。

Shown is the code: 显示的代码是:

int rows;
int columns;

Console.WriteLine("Enter the number of rows");
rows = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the number of columns");
columns = Convert.ToInt32(Console.ReadLine());

int[,] multiDim = new int[rows, columns];

for (int p = 0; p < multiDim.GetLength(0); p++)
{
    for (int k = 0; k < multiDim.GetLength(1); k++)
    {
       multiDim[p, k] = (p + 1) * (k + 1);
    }
    Console.WriteLine();
    Console.ReadLine();            
}

foreach (int i in multiDim)
    {
        Console.Write(i + " ");

        if (i == multiDim.GetLength(1))
        {
            Console.WriteLine();
        }
    }

    Console.ReadLine();

When I enter a value for rows that is above 2 the program does does not print the array in a proper array format. 当我输入大于2的行的值时,程序不会以正确的数组格式打印数组。 For example when I have 3 rows and 5 columns the output is: 例如,当我有3行5列时,输出为:

1 2 3 4 5 1 2 3 4 5

2 4 6 8 10 3 6 9 12 15 2 4 6 8 10 3 6 9 12 15

I have read similar questions bu they do not seem to help. 我看过类似的问题,但它们似乎无济于事。 All help is appreciated.Thanks in advance. 感谢所有的帮助。

Your code is looping over the values of the array, rather than the indexes. 您的代码正在遍历数组的值,而不是索引。 This means that it just happens to work initially since your values line up well. 这意味着,由于您的值排列良好,它刚开始就可以工作。

I would suggest switching to using Jagged Arrays instead of Multidimensional arrays. 我建议切换到使用锯齿数组而不是多维数组。 This way you can do foreach (row in multiDim) , then foreach (cell in row) 这样,您可以先执行foreach (row in multiDim) ,然后执行foreach (row in multiDim) foreach (cell in row)

If you still need to use a multidimensional array, then you need some form of counter which keeps track of the position of the array you are in. This is why a regular for loop is better to use for this scenario rather than a foreach loop. 如果仍然需要使用多维数组,则需要某种形式的计数器来跟踪您所在的数组的位置。这就是为什么常规for循环比foreach循环更适合用于此方案的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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