Kallie
Kallie

Reputation: 316

2D array printing C#

I want to print a 2D array, I tried using the following code, but it's only printing the first row of the array, why is it doing that and not printing the whole array in one line?

for (int x = 0, y = 0; y < 3; y++)
{
    for (; x < 3; x++)
        Console.Write("{0}, ", arr[x, y]);
}

Upvotes: 0

Views: 134

Answers (5)

Will Smith
Will Smith

Reputation: 1935

You have defined x=0 in the outer loop. This means once the inner loop has ran once x will always be 3

Try:

for (int y = 0; y < 3; y++)
{
    for (int x = 0; x < 3; x++)
        Console.Write("{0}, ", arr[x, y]);
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Just use a simple foreach loop:

foreach (var item in arr)
  Console.Write("{0}, ", item);

foreach loop will do with multidimensional arrays as well.

Upvotes: 1

Abhishek
Abhishek

Reputation: 7035

Column based printing.

for (int y = 0; y < 3; y++)
{
    for (int x = 0; x < 3; x++)
        Console.Write("{0}, ", arr[x, y]);
    Console.Write("\n"); //added for better formatting
}

or

If you don't care about formatting,

foreach(var arrEle in arr)
   Console.Write(arrEle+" ");

The problem , with your code is that you aren't initializing x for every y. That is the reason, we have to declare/initialize in inner for-loop.

Upvotes: 2

dsolimano
dsolimano

Reputation: 8986

x is only set to 0 once at the start of the outer loop, so in the second two iterations of the outer loop, x=3 and the inner loop test fails. Try this:

for (int y = 0; y < 3; y++)
{
    for (int x = 0; x < 3; x++)
        Console.Write("{0}, ", arr[x, y]);
}

Upvotes: 1

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

Try this:

for (int x = 0; x < 3; x++)
{
    for (int y = 0; y < 3; y++)
    {
        Console.Write("{0}, ", arr[x, y]);
    }
}

Upvotes: 2

Related Questions