C# program to convert a two-dimensional array into a one-dimensional array

Here, we are going to learn how to convert a two-dimensional array into a one-dimensional array in C#?
Submitted by Nidhi, on August 22, 2020

Here we will create a class that contains two arrays TwoD and OneD of integer elements. Then we convert TwoD into OneD array by coping all element and then we print both arrays. The TwoD array will be printed in a matrix format and then print elements of the OneD array.

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.

```//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.

What's New (MCQs)

Top Interview Coding Problems/Challenges!

IncludeHelp's Blogs

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates