2D array printing C# - 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]);
}

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

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.

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]);
}

Just use a simple foreach loop:
foreach (var item in arr)
Console.Write("{0}, ", item);
foreach loop will do with multidimensional arrays as well.

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]);
}

Related

Index out of range for multi dimensional array

I'm getting the error that the index for my array is out of range.
I define a 3D array like this:
Button[, ,] posAr_ItemManager = new Button[maxRows, maxColumns, maxCategories];
Where maxRows, maxColumns and maxCategories are all constant integers.
I then want to loop through this whole array, i do it using nested loops as shown here:
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; i < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; i < posAr_ItemManager.GetLength(2); z++)
{
if (posAr_ItemManager[i,j,z] != null)
{
Button but = posAr_ItemManager[i, j, z];
but.Width = itemWidth;
but.Height = itemHeight;
but.SetValue(Canvas.LeftProperty, itemPanelX + (i + 1) * butSpacing + i * itemWidth);
but.SetValue(Canvas.TopProperty, itemPanelY + (i+1)*butSpacing + i* itemHeight);
}
}
}
}
When I run the program it gives the out of range error where I check if the item is not equal to null.
I have no idea why it does it as I thought my declaration of the 3D array is correct and the nested loop as well? thanks in advance!
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; j < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; z < posAr_ItemManager.GetLength(2); z++)
look very carefully at the middle tests. Also, consider hoisting the GetLength tests so you only do them once per dimension. Perhaps:
int rows = posAr_ItemManager.GetLength(0), columns = posAr_ItemManager.GetLength(1),
categories = posAr_ItemManager.GetLength(2);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
for (int cat = 0; cat < categories; cat++)
You're using "i" to check if the loop is over in each of the dimensions. Change it to corresponded i,j,z.
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; **j** < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; **z** < posAr_ItemManager.GetLength(2); z++)

How to apply DRY principle to repeated C# for loops

I keep going through a two dimensional array and would like to stop repeating the same nested for loops
for (int x = 0; x < width; x++) {
for (int y =0; y < height; y++) {
// Do some stuff
}
}
Is there a way to DRY-out the nested for loops to something more along the lines of
iterateThroughMatrix ( doSomeStuff )
iterateThroughMatrix ( doSomethingElse )
iterateThroughMatric ( doSomeOtherStuff )
void iterateThroughMatrix ( doSomething ) {
for (int x = 0; x < width; x++) {
for (int y =0; y < height; y++) {
// doSomething here
}
}
}
You need something like this:
void iterateThroughMatrix(Action<int, int> doSomething)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
doSomething(x, y);
}
}
}
You can use any delegate that has two integers, but Action<int, int> is built-in and ready to go.

How to assign value in two dimensional array

How to assign value in two dimensional array in c#
My Code is
int[,] matarix = new int[4, 5];
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 5; y++)
{
matarix[x, y] = x+"-"+y;
}
}
i tried above code but its showing error "can't implicitly convert string to int"
How to do it ? Thanks
You're on the right track. Just assign a value.
int[,] matarix = new int[4, 5];
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 5; y++) {
matarix[x, y] = VALUE_HERE;
}
}
One recommendation I would make, would be to use Array.GetLength instead of hard coding your for loops. Your code would become:
int[,] matarix = new int[4, 5];
for (int x = 0; x < matarix.GetLength(0); x++) {
for (int y = 0; y < matarix.GetLength(1); y++) {
matarix[x, y] = VALUE_HERE;
}
}
You pass in one of the array's dimensions, and it tells you how many indices exist for that dimension.
This is a template I usually use for filling up two dimensional arrays.
Its one line and easy to change.
int[,] Foo = new int[4,5];
for(int i=0;i < Foo.Length; i++, Foo[i % Foo.GetLength(0),i / Foo.GetLength(1)] = 0; // Or value to assign
Also please do note that your array is holding integers while you are giving it strings (the "" converts it to a string, while x - y keeps it integer)
Hope it helps

Initializing a jagged array in c# gives index out of range exception

field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
for (int y = 0; y < 3; y++)
{
field[x][y] = new int[3];
}
}
For some reason the above code is giving me out of range exception but the following works fine:
field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
}
for (int y = 0; y < input.Height; y++)
{
for (int x = 0; x < input.Width; x++)
{
field[x][y] = new int[3];
field[x][y][0] = random.Next(0, output.Width);
field[x][y][1] = random.Next(0, output.Height);
field[x][y][2] = MaskFunctions.DSCALE;
}
}
Can anyone point out what am i doing wrong?
Also: Is there a difference between out of range and out of bound exception?
Your inner loop goes from 0 to 3, instead of 0 to input.Height. This will produce an out of range exception when input.Height < 3.
You probably meant to do this:
field = new int[input.Width][][];
for (int x = 0; x < input.Width; x++)
{
field[x] = new int[input.Height][];
for (int y = 0; y < input.Height; y++)
{
field[x][y] = new int[3];
}
}

Need help saving map

I need help with my map editor, I'm stuck on saving it. When I save, after I put some grass on map, it gets grass everywhere in map file.
Here's variables:
mapMaximumX: maximum of the map in X (it is set as 500)
mapMaximumY: maximum of the map in Y (it is also set as 500)
mapTiles[index]: this is a list with class, each class has ID (0 = empty, 1 = grass, 2 = water), X and Y
if (Keyboard.GetState().IsKeyDown(Keys.F1))
{
for(int y = 0; y < mapMaximumY; y++)
{
for (int x = 0; x < mapMaximumX; x++)
{
if (MapTiles[i3].X == x && MapTiles[i3].Y == y)
{
}
else
{
MapTiles.Add(new Class1(0, x * 32, y * 32));
}
if (i3 < MapTiles.Count)
{
i3++;
}
}
}
TextWriter file = new StreamWriter("map1.MAP");
for (int y = 0; y < mapMaximumY; y++)
{
for (int x = 0; x < mapMaximumX; x++)
{
file.Write(MapTiles[i2].ID + ", ");
}
file.Write(file.NewLine);
}
i2 = 0;
System.Windows.Forms.MessageBox.Show("Saved!");
file.Close();
}
Full code is here, if u need it:
http://pastebin.com/qrWbuPtb
Thanx.
file.Write(MapTiles[i2].ID + ", ");
i2 never changes within your loop, so whatever i2 is will always be what's used to write your output.
You need to be using X and Y from your loops in determining which cell to write out.

Categories

Resources