How to declare, initialize and print three-dimensional (3D) array of integers in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {

            int[,,] arr3D = new int[2, 2, 3];

            arr3D[0, 0, 0] = 1;
            arr3D[0, 0, 1] = 2;
            arr3D[0, 0, 2] = 3;

            arr3D[0, 1, 0] = 4;
            arr3D[0, 1, 1] = 5;
            arr3D[0, 1, 2] = 6;

            arr3D[1, 0, 0] = 7;
            arr3D[1, 0, 1] = 8;
            arr3D[1, 0, 2] = 9;

            arr3D[1, 1, 0] = 10;
            arr3D[1, 1, 1] = 11;
            arr3D[1, 1, 2] = 12;

            //''' 0,0,2 '''' 0,1,2 
            //'' 0,0,1 '''' 0,1,1 
            //' 0,0,0 '''' 0,1,0 

            //''' 1,0,2 '''' 1,1,2
            //'' 1,0,1 '''' 1,1,1 
            //' 1,0,0 '''' 1,1,0 

            int ubound0 = arr3D.GetUpperBound(0);
            int ubound1 = arr3D.GetUpperBound(1);
            int ubound2 = arr3D.GetUpperBound(2);

            Console.WriteLine("ubound0 = {0}", ubound0);
            Console.WriteLine("ubound1 = {0}", ubound1);
            Console.WriteLine("ubound2 = {0}", ubound2);
            Console.WriteLine();

            int len0 = arr3D.GetLength(0);
            int len1 = arr3D.GetLength(1);
            int len2 = arr3D.GetLength(2);

            for (int i = 0; i < len0; i++)
            {
                for (int j = 0; j < len1; j++)
                {
                    for (int k = 0; k < len2; k++)
                        Console.Write("{0, 4}", arr3D[i, j, k]);
                }
                Console.WriteLine();
            }
        }
    }
}


/*
run:
  
ubound0 = 1
ubound1 = 1
ubound2 = 2

   1   2   3   4   5   6
   7   8   9  10  11  12
 
*/

 



answered Apr 11, 2016 by avibootz
edited Jan 8, 2017 by avibootz
...