Reputation: 316
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
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
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
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
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
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