C
C#3y 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_2020OP3y 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
Gooster
Gooster3y ago
print it like 0000000 0000000 0000000 etc?
idris_2020
idris_2020OP3y ago
yeah i made code but only prints first row
Gooster
Gooster3y ago
show me
Anton
Anton3y ago
with two for loops
idris_2020
idris_2020OP3y 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(" | ");
}
}
Gooster
Gooster3y ago
ah yes youre printing out only a diognal [i,i] do you see the problem?
idris_2020
idris_2020OP3y ago
i tried i by itself but doesnt work
Gooster
Gooster3y 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_2020OP3y ago
yeah so would i need to like iterate i make another for loop?
Gooster
Gooster3y ago
yes a loop for x and a loop for y
.
.3y 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_2020OP3y ago
yeah im doing that rn
Gooster
Gooster3y ago
dont spoil everything
.
.3y ago
And why did you create array in this way?
Gooster
Gooster3y ago
why not?
idris_2020
idris_2020OP3y 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
.
.3y ago
I didn't, look at the printing
Gooster
Gooster3y 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
.
.3y ago
int[,] array = new int[6, 8];
int[,] array = new int[6, 8];
Gooster
Gooster3y ago
yeah ok that would also set the whole thing to 0
.
.3y ago
You can have other default values too
idris_2020
idris_2020OP3y ago
i need them to be stored at different values even if they all start at 0 done ty for help
Accord
Accord3y ago
Closed!

Did you find this page helpful?