The source code to convert the two-dimensional array into a one-dimensional array in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//Program to convert the two-dimensional array
//into a one-dimensional array in C#
using System;
class Demo
{
int row, col;
int[,] TwoD;
int[] OneD;
Demo(int r, int c)
{
row = r;
col = c;
TwoD = new int[row, col];
OneD = new int[row * col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
TwoD[i, j] = i + j;
}
}
}
public void ConvertTwoDArrayToOneDArray()
{
int index = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
OneD[index++] = TwoD[i, j];
}
}
}
public void PrintTwoArray()
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Console.Write(TwoD[i, j]+"\t");
}
Console.WriteLine();
}
}
public void PrintOneDArray()
{
for (int i = 0; i < row * col; i++)
{
Console.WriteLine(OneD[i]);
}
}
public static void Main(string[] args)
{
Demo D = new Demo(2, 2);
Console.WriteLine("TwoD Array(Matrix) is: ");
D.PrintTwoArray();
D.ConvertTwoDArrayToOneDArray();
Console.WriteLine("OneD Array after conversion: ");
D.PrintOneDArray();
}
}
Output:
TwoD Array(Matrix) is:
0 1
1 2
OneD Array after conversion:
0
1
1
2
Press any key to continue . . .
Explanation:
In the above program, we created a class Demo that contains two arrays OneD and TwoD. Here we initialized TwoD array and also instantiate OneD array in the constructor of Demo class.
The Demo class contains ConverTwoDArrayToOneDArray() method to convert TwoD array into OneD array by assigning all elements. Here we also created PrintTwoArray() and PrintOneArray() methods.
The PrintTwoDArray() method will print elements of the TwoD array in the form of the matrix, and PrintOneDArray() will print all elements of the OneD array on the console screen.
Program:
The source code to convert the two-dimensional array into a one-dimensional array in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class Demo that contains two arrays OneD and TwoD. Here we initialized TwoD array and also instantiate OneD array in the constructor of Demo class.
The Demo class contains ConverTwoDArrayToOneDArray() method to convert TwoD array into OneD array by assigning all elements. Here we also created PrintTwoArray() and PrintOneArray() methods.
The PrintTwoDArray() method will print elements of the TwoD array in the form of the matrix, and PrintOneDArray() will print all elements of the OneD array on the console screen.