How to convert a one-dimensional array to a two-dimensional array in C#

1 Answer

0 votes
using System;

class Program
{
    static void Main() {
        int[] arr = {3, 5, 6, 9, 0, 1, 7, 8, 2, 4, 11, 12}; 
        int rows = 3;
        int cols = 4;
        int index = 0;
        int[,] arr2d = new int[rows, cols];
            
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                arr2d[i, j] = arr[index];
                index++;
            }
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                Console.Write(arr2d[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}





/*
run:
  
3 5 6 9 
0 1 7 8 
2 4 11 12 

*/

 



answered Sep 5, 2021 by avibootz
...