c#: 2d arrays: rectangular[,]   jagged[][]

array
Arrays are a collection of like data with a single name.
Arrays can have more than one dimension.
A 2-d array has a single name, but TWO indexes.


code: RECTANGULAR 2d arrays
Two-Dimensional Arrays ====================== - Collection of a fixed number of components arranged in two dimensions - All components of the same type The syntax for declaring a two-dimensional array is:
  
      dataType[ , ] arrayName;

      int[,] array2d = new int[5,3]; // 5 rows, 3 columns 
      
      // access the 4th row, 3rd column      
      list[3,2]= 99; // where row and col are expressions yielding nonnegative integers
      
   
The two positive integers, row and col, specify the number of rows and columns in the array Two-d arrays are also called matrixes or tables or grids
  
      // Initialization in Declaration
      int [,] cats = { {2,5,4}, {6,7,8}, {9,0,2}, {5,0,0} };

   
- Elements of each row are enclosed within braces and separated by commas - All rows are enclosed within braces - If all components of row not specified, unspecified components are 0 Check if null =============
  
    // see if array has element (has been created) by comparing to "null"
    static void FillArray(int[] arr, int size)
    {
      // Create the array on demand:
      if (arr == null)
      {
          arr = new int[size];
      }
    }

   

processing 2d arrays
Processing Two-Dimensional Arrays ================================= A two-d array can be processed in 3 different ways: - Process the entire array - Process a row of the array, called row processing - Process a column of the array, called column processing When processing a particular row or column of a two-d array - We use algorithms similar to processing one-d arrays Nested loop is a standard way of manipulating 2d arrays To sum all the items in the matrix:
         
        // 5 rows  3 columns: indexes 0,0 thru 4,2
        int [,] matrix = new int[ 5, 3 ];
        
           /* 
           15  elements in 2d array
           a  b  c 
           d  e  f
           g  h  i 
           j  k  l 
           m  n  p    'a' would be matrix[0,0]
                      'b' would be matrix[0,1]
                      'e' would be matrix[1,1]
                      'i' would be matrix[2,2]
                      'k' would be matrix[3,1]
                      'p' would be matrix[4,2]           
           */
        
        Random rnd = new Random();
        int sum = 0, row, col;
        
        // assign each element a number between 1-100
        for( row = 0; row < 5; row++ ) 
        {  
           for( col = 0; col < 3; col++ )
           {
               matrix[ row, col ] = rnd.Next(1, 101);         
           }
        }
     
        
        // sum all elements in matrix
        for( row = 0; row < 5; row++ ) 
        {  
           for( col = 0; col < 3; col++ )
           {
               sum += matrix[ row, col ];         
           }
        }
        
        // output 3rd row
        row = 2; 
        for( col = 0; col < 3; col++ )
        {
           Console.Write(matrix[row, col].ToString("D3") + " "); 
        }
        Console.WriteLine();
                
                
        // output 1st column 
        col = 0;
        for( row = 0; row < 5; row++ ) 
        {  
           Console.Write(matrix[row, col].ToString("D3") + " "); 
        }
        Console.WriteLine();
                
        
        // output each element
        for( row = 0; row < 5; row++ ) 
        {  
           for( col = 0; col < 3; col++ )
           {
               Console.Write(matrix[row, col].ToString("D3") + " "); 
           }
           Console.WriteLine();
        }
      
Input =====
  
         // Inputs data in row number 4 of matrix:
         row = 4;
         for( col = 0; col< columns; col++ )
             matrix[ row , col ] = Console.ReadLine();
       
       
         // Input data in each component of the matrix      
         for( row = 0; row < rows; row++ )
             for( col = 0; col < columns; col++ )
                matrix[ row , col ] = Console.ReadLine();
           
   

print a 2d array
    
   using System;   
   class ArrayClass2D
   {      
       static void Main()
       {
           int[,] arr = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
           
           // Pass the array as a parameter:
           PrintArray( arr, 4, 2 );
       }   
   
   
       // pass in 2-d array of ints
       static void PrintArray(int[,] arr, int len0, int len1)
       {
           // Display the array elements: 
           for (int i = 0; i < len0; i++) 
           {
               for (int j = 0; j < len1; j++) 
               {
                   Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
                   OR...
                   Console.WriteLine("Element(" + i + "," + j + ")=" + arr[i, j]);
               }
           }
       }      
   }
   
Output: Element(0,0)=1 Element(0,1)=2 Element(1,0)=3 Element(1,1)=4 Element(2,0)=5 Element(2,1)=6 Element(3,0)=7 Element(3,1)=8

finding dimensions of 2-d array and using to print
 
   // printing 2-d arrays
   // without specifying dimensions
   // get EACH DIMENSION from the array
   class Program
   {
       static void Main() 
       { 
           int[,] arr = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } } );
           
           // Pass the array - method will use bounds           
           PrintArrayBounds ( arr );
           
           // Pass the array - method will use length
           PrintArrayLength( arr );
           
           Console.ReadKey();
       }

       
       // Get upper BOUNDS for each dimension of the array.
       static void PrintArrayBounds(int[,] arr) // pass in the 2-d array
       {
           // Get upper bounds for the array - the max index, NOT the count
           int bound0 = arr.GetUpperBound(0);
           int bound1 = arr.GetUpperBound(1);

           // Display the array elements: 
           // MUST use "<=" as the bound is the the index n-1 in an array of n
           for (int i = 0; i <= bound0; i++) 
           { 
               for (int j = 0; j <= bound1; j++) 
               { 
                   Console.Write(arr[i, j] + " "); // writes out each column of the row 
               }
               Console.WriteLine(); // advances to the next line for next row
           } 
       } 
       
       
       // Get LENGTH of each dimension of the array.
       static void PrintArrayLength(int[,] arr) // pass in the 2-d array
       {
           // Get count of items in the array.
           int length0 = arr.GetLength(0);
           int length1 = arr.GetLength(1);

           // Display the array elements: 
           // MUST use "<" ONLY
           for (int i = 0; i < length0; i++) 
           { 
               for (int j = 0; j < length1; j++) 
               { 
                   Console.Write(arr[i, j] + " "); // writes out each column of the row 
               }
               Console.WriteLine(); // advances to the next line for next row
           } 
       }     
   }

   

jagged arrays
 
        Nums numReader = new Nums();
        int r = numReader.ReadInt("Enter rows");
        int c = numReader.ReadInt("Enter columns");
        
        ///////////////////////////////////////////////////////////////
        // JAGGED ARRAY
        int[][] list = new int[r][]; // jagged but all arrays are same size in this case
        for (int z = 0; z < r; z++)
            list[z] = new int[c];

        //fill
        for (int i = 0; i < list.Length; i++)
           for (int j = 0; j < list[i].Length; j++)
           {
             list[i][j] = i + j;
           }              
              
   

 
    // Print items in JAGGED ARRAY
    static void PrintArray(int[][] arr) // pass in the 2-d array
    {
        // don't print giant-tific lists
        if ((arr.Length*arr[0].Length) > 100) return;

        for (int i = 0; i < arr.Length; i++)
        { 
            for (int j = 0; j < arr[i].Length; j++)
                Console.Write(arr[i][j].ToString("000") + " "); // writes out each column of the row
            Console.WriteLine(); // advances to the next line for next row
        }
        Console.WriteLine("\n"); // advances to the next line for next row
    }