C# Jagged Array

In this chapter you will learn:

  1. Initializing a Jagged Array
  2. Length with jagged arrays
  3. Use foreach statement to loop through jagged array

Description

A jagged array is an array of arrays in which the length of each array can differ.


class MainClass//from  ww  w .j a v a 2 s .co m
{
  static void Main()
  {

    int[][] cells = {
        new int[]{1, 0, 2, 0},
        new int[]{1, 2, 0},
        new int[]{1, 2},
        new int[]{1}
    };
  }
}

The code above generates the following result.

Length of Jagged Arrays

The following code creates a jagged array by creating the first dimension first and assigns each dimension with different length arrays.


using System; /* w ww. j ava2  s  .c o  m*/
 
class MainClass {  
  public static void Main() {  
    int[][] jaggedArray = new int[4][];  
    jaggedArray[0] = new int[3];  
    jaggedArray[1] = new int[7];  
    jaggedArray[2] = new int[2];  
    jaggedArray[3] = new int[5];  
 
    int i, j; 
 
    for(i=0; i < jaggedArray.Length; i++){
      for(j=0; j < jaggedArray[i].Length; j++){
        jaggedArray[i][j] = i * j + 70;  
      }
    }
 
    Console.WriteLine("Total number of network nodes: " + 
                      jaggedArray.Length + "\n"); 
 
    for(i=0; i < jaggedArray.Length; i++) {  
      for(j=0; j < jaggedArray[i].Length; j++) { 
        Console.Write(i + " " + j + ": "); 
        Console.Write(jaggedArray[i][j]);  
        Console.WriteLine();  
      } 
      Console.WriteLine();  
    } 
  }  
}

The code above generates the following result.

Jagged array with foreach loop


using System;//www . j  a v  a 2  s.c  o m

class MainClass
{
   static void Main()
   {
      int[][] arr1 = new int[2][];
      arr1[0] = new int[] { 1, 3 };
      arr1[1] = new int[] { 1, 1, 4 };

      foreach (int[] array in arr1)      
      {
         Console.WriteLine("Starting new array");
         foreach (int item in array)     
         {
            Console.WriteLine(" Item: {0}", item);
         }
      }
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Use for each loop to output elements in an array
  2. Use Foreach statement to loop through Rectangular Array
  3. for vs foreach for multi-dimensional array
Home »
  C# Tutorial »
    C# Language »
      C# Array
C# Arrays
C# Array Length
C# Array Rank
C# Array Index
C# Multidimensional Arrays
C# Array Initialization
C# Jagged Array
C# Array foreach loop
C# Array ForEach Action