How to use 1D array as 2D array in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int row = 3;
            int col = 4;

            int[,] arr2d = new int[row, col];

            arr2d[0, 0] = 100;
            arr2d[1, 1] = 11;
            arr2d[2, 2] = 22;
            arr2d[2, 3] = 8888;

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    Console.Write(arr2d[i, j] + "   ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();


            int[] arr1d = new int[row * col];

            arr1d[0 * col + 0] = 100;
            arr1d[1 * col + 1] = 11;
            arr1d[2 * col + 2] = 22;
            arr1d[2 * col + 3] = 8888;

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    Console.Write(arr1d[i * col + j] + "   ");
                }
                Console.WriteLine();
            }
        }
    }
}


/*
run:
  
100   0   0   0
0   11   0   0
0   0   22   8888

100   0   0   0
0   11   0   0
0   0   22   8888
 
*/

 



answered Jan 8, 2017 by avibootz
...