Reputation: 3
I've been trying to print this code just the way I've written the array, a 3x3 box with numbers that I will later insert into it. All seems correct but I keep getting this message when I try to write my loop:
Cannot implicitly convert type 'int[,]' to 'int[][]'
static void Main(string[] args)
{
Console.Title = "Quadrado Mágico";
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkBlue;
Random ran = new Random();
Console.Clear();
int[][] quadrado = new int [3,3] { { 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 } };
for(int fila = 0; fila < quadrado.Length; fila++) {
for(int coluna = 0; coluna < quadrado[fila].Length; coluna++) {
Console.WriteLine(quadrado[fila][coluna] + "\t");
}
Console.WriteLine();
}
Console.ReadKey();
}
Upvotes: 0
Views: 125
Reputation: 40
static void Main(string[] args)
{
Console.Title = "Quadrado Mágico";
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkBlue;
Random ran = new Random();
Console.Clear();
const int f = 3;
const int c = 3;
int[,] quadrado = new int[f, c]
{
{0, 0, 0}, {0, 0, 0}, {0, 0, 0}
};
for (int fila = 0; fila < f; fila++)
{
for (int coluna = 0; coluna < c; coluna++)
{
Console.WriteLine(quadrado[fila, coluna] + "\t");
}
Console.WriteLine();
}
Console.ReadKey();
}
Upvotes: 0
Reputation: 2192
This code works. You need to change the int[][] to int[,]
Then you need to use GetUpperBound(0) and (1) to get the length of each of the arrays.
static void Main(string[] args) { Console.Title = "Quadrado Mágico"; Console.BackgroundColor = ConsoleColor.DarkCyan; Console.Clear(); Console.ForegroundColor = ConsoleColor.DarkBlue; Random ran = new Random(); Console.Clear();
int[ , ] quadrado = new int[3, 3] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
// ... Loop using the GetUpperBounds.
for (int fila = 0; fila <= quadrado.GetUpperBound(0); fila++)
{
for (int coluna = 0; coluna <= quadrado.GetUpperBound(1); coluna++)
{
// Display the element at these indexes.
Console.WriteLine(quadrado[fila, coluna]);
}
Console.WriteLine();
}
Console.ReadKey();
}
Upvotes: 2
Reputation: 1017
Change the following
int[][] quadrado = new int [3,3] { { 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 } };
to
int[,] quadrado = new int[3, 3] { { 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 } };
Upvotes: -1