0

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.

2
  • @Camilo Your edit didn't help my question. I got an output which I showed. Do you get the correct output when you run the code? Commented Oct 15, 2017 at 23:51
  • Oops, sorry, thought that was unintentional, as formatting is not the easiest on this site. Commented Oct 15, 2017 at 23:52

1 Answer 1

1

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)

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that solved my problem. Can explain why my original code didn't give the desired output?
You were only printing a new line if i was equal to multiDim.GetLength(1). In your code, when i was 10, it didn't print a new line, it only printed one when it was 5
Thanks. I thought I was evaluating the index, but I was really evaluating the value?
I just realised that i was the value of the array, not an index. So my answer is not actually correct. I'll edit my post with that detail in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.