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. 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. 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.
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. For example when I have 3 rows and 5 columns the output is:
1 2 3 4 5
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.