C# .NET - What is Jagged Array

Asked By kunal mehta
20-Aug-08 11:03 AM

Interview Question

What is jagged array in C#

Code snippet for it

What is Jagged Array  What is Jagged Array

20-Aug-08 11:06 AM

A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.

Example: A Jagged Array can be used is to create a table in which the lengths of the rows are not same. This Array is declared using square brackets ( [ ] ) to indicate each dimension.

The following code demonstrates the creation of a two-dimensional jagged array.

Class Jagged
{
public static void Main()
{
int [][] jagged=new int [3][];
jagged[0]=mew int[4]
jagged[1]=mew int[3]
jagged[2]=mew int[5]
int I;
‘Storing values in first array
for (I=0;I<4;I++)
jagged[0][I]=I;
‘Storing values in second array

 

for( I=0;I<3;I++)

jagged[1][I]=I;

‘Storing values in third array

 

for(I=0;I<5;I++)

jagged[2][I]=I;

‘Displaying values from first array

 

for (I=0;I<4;I++)

Console.WriteLine(jagged[0][I])

‘Displaying values from second array

 

for (I=0;I<3;I++)

Console.WriteLine(jagged[1][I])

 

‘Displaying values from third array

for(I=0;I<5;I++)

Console.WriteLine(jagged[2][I])

 

}

}

reply  reply

20-Aug-08 12:39 PM
Jagged Arrays

Jagged arrrays are nothing but arrays of arrays. This is very clear from the 'Declaration' sysnatx. See the [] appears more than once in the following declaration.

Declaring Jagged Arrays

// "jagged" array: array of (array of int)
int[][] j2;
// array of (array of (array of int))
int[][][] j3;
Rectangualr Arrays ~ Jagged Arrays
//single-dimensional rectangukar arrays
int[] r1 = new int[] {1, 2, 3};
//two-dimensional rectangualar arrays
int[,] r2 = new int[,] {{1, 2, 3}, {4, 5, 6}};
//three-dimesional rectangular arrays
int[,,] r3 = new int[10, 20, 30];
//"jagged" array: araay of(array of int)
int[][] j2 = new int[3][];
j2[0] = new int[] {1, 2, 3};			
j2[1] = new int[] {1, 2, 3, 4, 5, 6};
j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};

reply  reply

20-Aug-08 12:42 PM

Jagged array represents array of arrays where each array can have arbitrary number of elements. It’s the similar concept of double pointers in C.

Jagged array provides flexible services for manipulating and controlling data. In the case of C pointers will have to do the manual book keeping for better control over the bounds of data. We can have the same implementation by using dequeue/vector container classes in C++. But still we can’t say they’re representing array. Rather than they’re containers and provides common “container” interfaces.


You can check the number of facilities available for jagged arrays and arrays from MSDN. Also you will get some other good examples

How to use Jagged Arrays – Listing 1

// constructing jagged array

int[][] myJaggedArray = new int[5][];


for (int i = 0; i < myJaggedArray.Length; i++)

{

myJaggedArray[i] = new int[i + 1];

}


// iterating each arrays

for (int i = 0; i < myJaggedArray.Length; i++)

{

// iterating each elements in an array

for (int j = 0; j < myJaggedArray[i].Length; j++)

{

Console.Write( “{0} “, myJaggedArray[i][j]);

}

Console.WriteLine(” - {0} elements”, myJaggedArray[i].Length);

}

How to use Jagged Arrays – Listing 1

int[][,] jaggedArray4 = new int[3][,]

{

new int[,] { {1,3}, {5,7} },

new int[,] { {0,2}, {4,6}, {8,10} },

new int[,] { {11,22}, {99,88}, {0,9} }};

check here...  check here...
20-Aug-08 01:13 PM
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array-of-arrays." This topic contains examples of declaring, initializing, and accessing jagged arrays.


// cs_array_of_arrays.cs
using System;
public class ArrayTest
{
public static void Main()
{
// Declare the array of two elements:
int[][] myArray = new int[2][];

// Initialize the elements:
myArray[0] = new int[5] {1,3,5,7,9};
myArray[1] = new int[4] {2,4,6,8};

// Display the array elements:
for (int i=0; i < myArray.Length; i++)
{
Console.Write("Element({0}): ", i);

for (int j = 0 ; j < myArray[i].Length ; j++)
Console.Write("{0}{1}", myArray[i][j],
j == (myArray[i].Length-1) ? "" : " ");

Console.WriteLine();
}
}
}
Jagged Array  Jagged Array
20-Aug-08 11:40 PM

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.

It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray2 = new int[][]
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:

int[][] jaggedArray3 =
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

You can access individual array elements like these examples:

// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:

int[][,] jaggedArray4 = new int[3][,]
{
    new int[,] { {1,3}, {5,7} },
    new int[,] { {0,2}, {4,6}, {8,10} },
    new int[,] { {11,22}, {99,88}, {0,9} }
};

You can access individual elements as shown in this example, which displays the value of the element [1,0] of the first array (value 5):

System.Console.Write("{0}", jaggedArray4[0][1, 0]);

The method Length returns the number of arrays contained in the jagged array. For example, assuming you have declared the previous array, this line:

System.Console.WriteLine(jaggedArray4.Length);

will return a value of 3.

This example builds an array whose elements are themselves arrays. Each one of the array elements has a different size.

class ArrayTest
{
    static void Main()
    {
        // Declare the array of two elements:
        int[][] arr = new int[2][];

        // Initialize the elements:
        arr[0] = new int[5] { 1, 3, 5, 7, 9 };
        arr[1] = new int[4] { 2, 4, 6, 8 };

        // Display the array elements:
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write("Element({0}): ", i);

            for (int j = 0; j < arr[i].Length; j++)
            {
                System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
            }
            System.Console.WriteLine();
        }
    }
}
Best Luck!!!!!!!!!!!!!!!!!
Sujit.
A jagged array is an array whose elements are arrays.  A jagged array is an array whose elements are arrays.
20-Aug-08 11:41 PM

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
Jagged Array Overview  Jagged Array Overview
21-Aug-08 01:23 AM

Overview:

Problem

Efficiently manage a variable number of values in a jagged array. We have several rows of data, such as ints, and want to store them together in a single data structure. Jagged arrays are ideal for this. We must learn the syntax and then investigate the reasons why their performance is good. Our solution must be effective and efficient.

C# Solution

How can we use jagged arrays? First I show some syntax of how you can add elements ('rows') to a jagged array after declaring it. What the first example does is create three rows in a jagged array in different ways. Then it loops through the jagged array and prints out each int value.

/// <summary>
/// Example class.
/// </summary>
class JaggedArray
{
    /// <summary>
    /// Example method.
    /// </summary>
    public JaggedArray()
    {
        // Declare local jagged array with 3 rows.
        int[][] jagged = new int[3][];

        // Create a new array in the jagged array, and assign it.
        jagged[0] = new int[2];
        jagged[0][0] = 1;
        jagged[0][1] = 2;

        // Set second row, initialized to zero.
        jagged[1] = new int[1];
        
        // Set third row, using array initializer.
        jagged[2] = new int[3] { 3, 4, 5 };

        // Print out all elements in the jagged array.
        for (int i = 0; i < jagged.Length; i++)
        {
            int[] innerArray = jagged[i];
            for (int a = 0; a < innerArray.Length; a++)
            {
                Console.Write(innerArray[a] + " ");
            }
            Console.WriteLine();
        }
    }
}
  • Jagged arrays shown
    The word 'jagged' doesn't even exist in C#, meaning that you don't need to use this word in your code. Jagged is just a descriptive variable name I use.
  • Lots of square brackets
    Look at the int[][] line at the start, and some of the other parts with new int[]. There's lots of square brackets. This is very different from a 2D array, which uses commas instead of pure brackets. (If that isn't confusing, I don't know what is.)
  • New arrays assigned to jagged array
    Above you should see that indexes in the array are assigned to new int[] arrays. This is because the jagged array only allocates the list of empty references to arrays at first. You have to make your own arrays to put in it.
  • Use Length to loop
    You will want to examine each item in the jagged array. We must call Length first on the array of references, and then again on each inner array. The Console calls above are just for the example.

Jagged array vs. 2D array

What's the difference? Jagged arrays are faster and have different syntax. They are faster because they use the "newarr" (vector) IL calls internally. I don't know all the details, but the boost is because they are optimized for starting at 0 indexes. The next example shows some code I compared in IL DASM.

/// <summary>
/// Shows jagged array vs. 2D array.
/// </summary>
private static void CompareIL()
{
    int[,] twoD = new int[1, 1]; // 1 x 1 array

    twoD[0, 0] = 1;

    int[][] jag = new int[1][];

    jag[0] = new int[1];
    jag[0][0] = 1; // 1 x 1 jagged array
}

IL of jagged and 2D arrays.

How much faster are jagged arrays?

Quite a lot faster. This is apparently because the .NET runtime has many optimizations for this specific case, and for some reason the 2D array cannot take advantage of them. My opinion is that you should always use jagged arrays when possible. I don't know the difference in memory usage. This data is based on 10 million repetitions.

Perf of jagged arrays.

Version Time in ms
10 million tests
Details
2D array 422 I tested the fastest method for using 2D arrays (using Length).
Jagged array 109 -

Discussion

Jagged arrays are fast and easy to use once you master the slightly different syntax. Prefer them to http://dotnetperls.com/Content/2D-Array-Use.aspx when performance is a consideration, and they are not more complex more to use. Investigating IL can be useful for understanding .NET internals. Finally, put bright rainbow colors on your bar charts.

Link: http://dotnetperls.com/Content/Jagged-Array.aspx

jagged array in C#  jagged array in C#
21-Aug-08 01:45 AM

Using jagged arrays, one can create multidimensional arrays with irregular dimensions. This flexibility derives from the fact that multidimensional arrays are implemented as arrays of arrays. The following piece of code demonstrates how one might declare an array made up of a group of 4 and a group of 6 elements:

int[][] jag = new int[2][];
jag[0] = new int [4];
jag[1] = new int [6];

The code reveals that each of jag[0] and jag[1] holds a reference to a single-dimensional int array. To illustrate how one accesses the integer elements: the term jag[0][1] provides access to the second element of the first group.

To initialise a jagged array whilst assigning values to its elements, one can use code like the following:

int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}};

Be careful using methods like GetLowerBound, GetUpperBound, GetLength, etc. with jagged arrays. Since jagged arrays are constructed out of single-dimensional arrays, they shouldn't be treated as having multiple dimensions in the same way that rectangular arrays do.

To loop through all the elements of a jagged array one can use code like the following:

for (int i = 0; i < jag.GetLength(0); i++)

for (int j = 0; j < jag[i].GetLength(0); j++)

Console.WriteLine(jag[i][j]);

Jagged Array  Jagged Array
21-Aug-08 03:32 AM
Overview

I thank the editor for publishing my first article ie 'Why C#' in csharphelp.com and also thankful to its reader for their constructive suggestions and comments.

This article discusses about the most talked datatype in the programming world - ARRAYS. C# offers two type of Arrays.

1. Rectangular Arrays
2. Jagged Arrays .

For those thaousand of programmers from the conventional progarmming (non-OO) world of 'Visual Basic' or like, the conecpt of 'Jagged Array' may be grey area. So I thought to pen down my understaning on this topic.

Rectangular Arrays

This is the arrays datatype, most of us are familiar with. Rectangular arrays may be may be single-dimensional or multi-dimensional.

Declaring single dimenisonal arrays.
    
    short[] shtEmpNo;
    int[] intSalary;

Declaring multi-dimenisonal arrays.
    // two-dimensional arrays of short
    short[,] shtEmpNo;
    // three-dimensional arrays of int
    int[,,] intSalary;        

Rule: Element-type (int, short, long) Rank-specifiers ([], [,,]) Name (Arrays Name)

Array types are reference types, and so the declaration of an array variable merely sets aside space for the reference to the array. Array instances are actually created via array initializers and array creation expressions

Intialising Arrays

    // 5 member single-dimensional arrays intialised
    short[] shtEmpNo = new short[5];
    // 3 member single-dimensional arrays    
    int[] intSlNo = new int[] {1, 2, 3};
    // 3*2 member two-dimensional arrays
    int[,] intCount = new int[,] {{1, 2, 3}, {4, 5, 6}};
    // 1*3 member three-dimesional arrays.
    int[,,] intDec = new int[10, 20, 30];

In C# supports 0-based arrays only. Infact now in all languanges for .Net Framework arrays are 0-based arrays.(In Visual Basic 6.0 Arrays could be Non-Zero based). So

shtEmpNo[0] = 0 ..... shtEmpNo[4] = 0
intSlNo[0] = 1 , intSlNo[1] = 2 and intSlNo[2] = 3
intCount[0,0] = 1, intCount[1,0] = 2,  intCount[0,1] = 4 and  intCount[2,2] = 6
intDec[0,0,0] = 10 and intDec[0,0,2] = 30

Here is a simple example

using System;
class MyClass
{
    static void Main() {
        int[] intDec = new int[5];
        for (int i = 0; i < intDec.Length; i++)
            intDec[i] = i * 10;
        for (int i = 0; i < intDec.Length; i++)
            Console.WriteLine("intDec[{0}] = {1}", i, intDec[i]);
    }
}
The program output is:
intDec[0] = 0
intDec[1] = 10
intDec[2] = 20
intDec[3] = 30
intDec[4] = 40

Jagged Arrays

Jagged arrrays are nothing but arrays of arrays. This is very clear from the 'Declaration' sysnatx. See the [] appears more than once in the following declaration.

Declaring Jagged Arrays

// "jagged" array: array of (array of int)
int[][] j2;
// array of (array of (array of int))
int[][][] j3;

Rectangualr Arrays ~ Jagged Arrays

//single-dimensional rectangukar arrays
int[] r1 = new int[] {1, 2, 3};
//two-dimensional rectangualar arrays
int[,] r2 = new int[,] {{1, 2, 3}, {4, 5, 6}};
//three-dimesional rectangular arrays
int[,,] r3 = new int[10, 20, 30];
//"jagged" array: araay of(array of int)
int[][] j2 = new int[3][];
j2[0] = new int[] {1, 2, 3};            
j2[1] = new int[] {1, 2, 3, 4, 5, 6};
j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};

The above illustartions shows variety of array creation expressions (both recatngular and jagged). The variables r1, r2 and r3 are rectangular arrays and the variable j2 is a jagged array.

Rectangular arrays always have a rectangular shape. For example, the length of r3's three dimensions are 10, 20, and 30 respectively, and it is easy to see that this array contains 10*20*30 elements.

The variable j2 is a "jagged" array. Specifically, j2 denotes an array of an array of int, or a single-dimensional array of type int[]. Each of these int[] variables can be initialized individually, and this allows the array to take on a jagged shape. The example gives each of the int[] arrays a different length. Specifically, the length of j2[0] is 3, the length of j2[1] is 6, and the length of j2[2] is 9.

See also this msdn article ::

http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Hope it helps.
  ansar replied to Shailendrasinh Parmar
21-Jul-10 01:19 PM
static void Main()
      {
        int[][] arr = new int[3][];
        int a=5;
        arr[0] = new int[4];
        arr[1] = new int[5];
        arr[2] = new int[6];
        

        for (int i = 0; i < arr.GetLength(0); i++)
        {
          for (int j = 0; j < arr[i].Length; j++)
          {
            arr[i][j] = a;
            a = a + 5;

          }
        }
        for (int i = 0; i < arr.GetLength(0); i++)
        {
          for (int j = 0; j < arr[i].GetLength(0); j++)
          {
            Console.WriteLine(arr[i][j]);
          }

        }

}

 

 this will work

  dummy ahuja replied to kunal mehta
01-Feb-11 05:32 AM
check this useful link related to jagged array
http://www.mindstick.com/Articles/ef6f3693-1eff-47b7-8236-840665fa20a6/?Jagged%20Array%20In%20C#.NET
Create New Account
help
Visual Basic 6.0 in Vista 64 Bits Windows 7 Hi, is posible install Visual Basic 6.0 Vista 64 Bits? Thanks, Alvaro Scorzo Windows 64 bit Discussions Visual Basic 6.0 (1
Visual Basic 6.0 Support Windows 7 Want to know till when Microsoft would provide support for Visual Basic 6.0? MSDN Discussions Visual Basic 6.0 (1) April (1) Vbrun (1) Fee based support until
Run 424 Error ON Visual Basic 6.0 DataBase i get a Run 424 Error ON Visual Basic 6.0 when i am creating a program what does this mean? Access Modules DAO Discussions Visual
Difference between MDI Form and Normal Form in visual basic 6.0 can any body explain me the difference between MDI form and Normal Form in Visual Basic 6.0 hello check out these links http: / / msdn2.microsoft.com / en-us / library / we128ese.aspx http
VB 6.0 + Visual Studio 2005 .NET Framework Hola. Tengo instalado el Visual Studio 6.0, con Visual Basic 6.0, y por curiosidad, para empezar a tocar algo, me he instalado el Visual