What is Jagged Array in C#: Definition and Example
jagged array in C# is an array of arrays where each inner array can have a different length. It allows you to store data in a structure where rows can vary in size, unlike a rectangular multidimensional array.How It Works
Think of a jagged array like a bookshelf with several shelves, where each shelf can hold a different number of books. Each shelf is an inner array, and the whole bookshelf is the jagged array. This means you can have one shelf with 3 books and another with 5 books, unlike a regular array where every shelf must have the same number of books.
In C#, a jagged array is declared as an array of arrays. Each element of the main array points to another array, and these inner arrays can be created with different lengths. This flexibility helps when you need to store data that naturally varies in size, such as rows of data with different numbers of columns.
Example
This example shows how to create a jagged array with three rows, where each row has a different number of elements. It then prints all the elements to the console.
using System; class Program { static void Main() { // Declare a jagged array with 3 rows int[][] jaggedArray = new int[3][]; // Initialize each row with different lengths jaggedArray[0] = new int[] { 1, 2, 3 }; jaggedArray[1] = new int[] { 4, 5 }; jaggedArray[2] = new int[] { 6, 7, 8, 9 }; // Print all elements for (int i = 0; i < jaggedArray.Length; i++) { Console.Write("Row " + i + ": "); for (int j = 0; j < jaggedArray[i].Length; j++) { Console.Write(jaggedArray[i][j] + " "); } Console.WriteLine(); } } }
When to Use
Use jagged arrays when you need to store collections of data where each group can have a different size. For example, if you are storing test scores for students and each student took a different number of tests, a jagged array lets you keep each student's scores in a separate array of varying length.
Jagged arrays are also useful when working with data that naturally forms uneven rows, such as a calendar where months have different numbers of days or a seating chart where rows have different numbers of seats.
Key Points
- A jagged array is an array of arrays, where inner arrays can have different lengths.
- It provides flexibility for storing uneven or irregular data structures.
- Access elements using two sets of square brackets, like
array[i][j]. - Jagged arrays differ from multidimensional arrays, which have fixed row and column sizes.