Jagged arrays & Passing arrays to function
Part- 20 Jagged arrays & Passing arrays to function
Jagged array is known as "array of arrays". Jagged array can be different dimensions and sizes. The Jagged array element size can be different. A jagged array is initialized with two square brackets [][].
- The first bracket rows specifies has to provide size of an array, and
- The second bracket columns specifies the dimensions of the array which is going to be stored.
int[][] jagged_array = new int[4][]
Example :
arr [0] = new int [ ] { 1, 2, 3, 4 };// Initialize the array
arr [1] = new int [ ] { 1, 2, 3, 4, 5, 6, 7 };
// Jagged Array with Single Dimensional Array.
int[][] jagged_array = new int[3][];
jagged_array [0] = new int[5] { 1, 2, 3, 4, 5 };
jagged_array [1] = new int[3] { 10, 20, 30 };
jagged_array [2] = new int[] { 12, 50, 60, 70, 32 };
// Jagged Array with Two Dimensional Array.
int[][,] jagged_array = new int[3][,];
jagged_array [0] = new int[2, 2] { { 1, 24 }, { 2, 54 } };
jagged_array [1] = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
jagged_array [2] = new int[4, 3];
// Initialize the jagged array while declaration.
int[][] jagged_array = new int[2][]{
new int[3]{1, 2, 3},
new int[4]{1, 2, 3, 4}
};
Example :
class JaggaryArray
{
static void Main(string[] args)
{
//jagged array of 5 array of integers
int[ ][ ] a = new int[ ][ ]
{
new int[ ] {0, 0},
new int[ ] {1, 2},
new int[ ] {2, 4, 2},
new int[ ] {3, 6},
new int[ ] {4, 8}
};
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
Output
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
Passing arrays to function:
If you observe above result, methods are able accept array as a parameter to perform
required operations based on our requirements.
class ArrayExample
{
static void printArray(int[] arr)
{
Console.WriteLine("Printing array elements:");
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
public static void Main(string[] args)
{
int[] arr1 = { 5, 10, 20, 25, 30, 35 };
printArray(arr1);//passing array to function
}
}