What is Jagged Array in C# and how to use Jagged Array

Description

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


class MainClass//from www. ja va  2s . c o 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; //from ww  w  .j  a  va2s .c  om
 
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;// ww  w  . j av a2 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.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var