In this example, we’ll learn How to convert a 2D Array into 1D Array in C# Console App.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using System; namespace Program { class twodmatrix { int p, r; int[,] a; int[] b; twodmatrix(int x, int y) { p = x; r = y; a = new int[p, r]; b = new int[p * r]; } public void readmatrix() { for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { Console.Write("a[{0},{1}]=", i, j); a[i, j] = Convert.ToInt32(Console.ReadLine()); } } } public void printtwodimentionalarray() { for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { Console.Write("{0}\t", a[i, j]); } Console.Write("\n"); } } public void convert() { int k = 0; for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { b[k++] = a[i, j]; } } } public void printonedimentionalarray() { for (int i = 0; i < p * r; i++) { Console.WriteLine("{0}\t", b[i]); } } public static void Main(string[] args) { twodmatrix obj = new twodmatrix(2, 3); Console.WriteLine("Enter the Elements : "); obj.readmatrix(); Console.WriteLine("\nGiven 2-D Array() is : "); obj.printtwodimentionalarray(); obj.convert(); Console.WriteLine("\nConverted 1-D Array is : "); obj.printonedimentionalarray(); Console.ReadLine(); } } } |