Answer the question
In order to leave comments, you need to log in
Is the array copy logic correct?
The task is to create a two-dimensional array with 3 rows and 5 columns, then transfer the values to a new array with 5 columns and 3 rows.
The code itself:
using System;
class TwoArray
{
static void Main()
{
int[,] numbs = new int[3, 5];
Random rand = new Random();
int[] numb = new int[numbs.Length];
for (int i = 0, z = 0; i < numbs.GetLength(0); i++)
{
for (int j = 0; j < numbs.GetLength(1); j++, z++)
{
numbs[i, j] = rand.Next(0, 100);
Console.Write(numbs[i, j] + " ");
numb[z] = numbs[i, j];
}
Console.WriteLine();
}
Console.WriteLine();
int[,] numbs2 = new int[5, 3];
for (int i = 0, z = 0; i < numbs2.GetLength(0); i++)
{
for (int j = 0; j < numbs2.GetLength(1); j++, z++)
{
numbs2[i, j] = numb[z];
Console.Write(numbs2[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
Answer the question
In order to leave comments, you need to log in
If you need to preserve the order of the elements, then just use the ready- made Array.Copy method:
Otherwise, you can use loops.
for (int i = 0, z = 0; i < numbs2.GetLength(0); i++)
{
for (int j = 0; j < numbs2.GetLength(1); j++)
{
numbs2[i, j] = numbs[j, i];
Console.Write(numbs2[i, j] + " ");
}
Console.WriteLine();
}
And if so:
using System;
class TwoArray
{
static void Main()
{
int[,] numbs = new int[3, 5];
Random rand = new Random();
int[,] numbs2 = new int[5, 3];
for (int i = 0, z = 0; i < numbs.GetLength(0); i++)
{
for (int j = 0; j < numbs.GetLength(1); j++, z++)
{
numbs[i, j] = rand.Next(0, 100);
Console.Write(numbs[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 0; i < numbs2.GetLength(0); i++)
{
for (int j = 0; j < numbs2.GetLength(1); j++)
{
numbs2[i, j] = numbs[j, i];
Console.Write(numbs2[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question