Ans.: The user will input a 2-D array (matrix) and we need to convert it to a 1-D array. We will create 1-D array column wise.
- input: { { 1, 2, 3 }, { 4, 5, 6 } }, output: 1 4 2 5 3 6
internal static void MultiToSingle(int[,] array)
int width = array.GetLength(0);
int height = array.GetLength(1);
int[] single = new int[width * height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
single[index] = array[x, y];
Console.Write(single[index] + " ");
This question can also be asked to form 1-D array row wise. In this case just swap the sequence of thefor loops as below. The output will be 1 2 3 4 5 6 for the input matrix mentioned above.
for (int x = 0; x < width; x++ )
for ( int y = 0; y < height; y++)
single[index] = array[x, y];
Console.Write(single[index] + " ");
No comments:
Post a Comment