C
C#2y ago
idris_2020

✅ How can I print a 2D array

I have a 2D array, how can i print each row of the array, on console
24 Replies
idris_2020
idris_20202y ago
The array will not get bigger or small, I just need to change the contents
int[,] cinemaSeats =
{
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
};
int[,] cinemaSeats =
{
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
};
this is the array
Jester
Jester2y ago
print it like 0000000 0000000 0000000 etc?
idris_2020
idris_20202y ago
yeah i made code but only prints first row
Jester
Jester2y ago
show me
Anton
Anton2y ago
with two for loops
idris_2020
idris_20202y ago
Console.Write("| ");
for (int i = 0; i < cinemaSeats.Length; i++)
{
Console.Write(cinemaSeats[i,i]);
if (i < cinemaSeats.Length - 1)
{
Console.Write(" | ");
}
}
Console.Write("| ");
for (int i = 0; i < cinemaSeats.Length; i++)
{
Console.Write(cinemaSeats[i,i]);
if (i < cinemaSeats.Length - 1)
{
Console.Write(" | ");
}
}
Jester
Jester2y ago
ah yes youre printing out only a diognal [i,i] do you see the problem?
idris_2020
idris_20202y ago
i tried i by itself but doesnt work
Jester
Jester2y ago
you need [0,1] [0,2] [0,3] [1,0] [1,1] [1,2] etc not [0,0] [1,1] [2,2] like youre doing now
idris_2020
idris_20202y ago
yeah so would i need to like iterate i make another for loop?
Jester
Jester2y ago
yes a loop for x and a loop for y
Aimbot
Aimbot2y ago
for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { int element = array[i, j]; Console.WriteLine(element); } }
idris_2020
idris_20202y ago
yeah im doing that rn
Jester
Jester2y ago
dont spoil everything
Aimbot
Aimbot2y ago
And why did you create array in this way?
Jester
Jester2y ago
why not?
idris_2020
idris_20202y ago
basically i need to make a cinema seat booking program (as you can tell from the array name) 0 represents an empty seat and the seats are 6x8
Aimbot
Aimbot2y ago
I didn't, look at the printing
Jester
Jester2y ago
okay if you used an array like bool[][] which is an array of bool arrays instead of a 2d array then i would suggest for (bla bla length) // goes trough the array of arrays Console.WriteLine(string.Join(null, seats[i])); // prints the whole array
Aimbot
Aimbot2y ago
int[,] array = new int[6, 8];
int[,] array = new int[6, 8];
Jester
Jester2y ago
yeah ok that would also set the whole thing to 0
Aimbot
Aimbot2y ago
You can have other default values too
idris_2020
idris_20202y ago
i need them to be stored at different values even if they all start at 0 done ty for help
Accord
Accord2y ago
Closed!