C# Jagged Arrays
Introduction
In C#, a jagged array is an array of arrays, where each sub-array can have a different length. Unlike rectangular multidimensional arrays where all rows have the same number of columns, jagged arrays give you the flexibility to have varying lengths for each dimension. This makes them perfect for scenarios where you need to store data with irregular shapes.
Think of a jagged array as an array whose elements are also arrays. These inner arrays can be of different sizes, creating an irregular or "jagged" structure, hence the name.
Creating Jagged Arrays
Syntax
// Declare a jagged array
type[][] arrayName = new type[outerSize][];
// Initialize each inner array separately
arrayName[0] = new type[size1];
arrayName[1] = new type[size2];
// and so on...
Simple Example
Here's how to create a basic jagged array:
// Declare a jagged array of integers with 3 rows
int[][] jaggedArray = new int[3][];
// Initialize each row with different sizes
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[2]; // Second row has 2 columns
jaggedArray[2] = new int[5]; // Third row has 5 columns
// Now we can access elements
jaggedArray[0][0] = 10;
jaggedArray[1][1] = 20;
jaggedArray[2][4] = 30;
Initializing Jagged Arrays
You can initialize jagged arrays in several ways:
Method 1: Initialize at Declaration
// Initialize a jagged array at declaration
int[][] jaggedArray = new int[][]
{
new int[] { 1, 2, 3, 4 },
new int[] { 5, 6 },
new int[] { 7, 8, 9, 10, 11 }
};
Method 2: Initialize Each Row Separately
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3, 4 };
jaggedArray[1] = new int[] { 5, 6 };
jaggedArray[2] = new int[] { 7, 8, 9, 10, 11 };
Accessing Jagged Array Elements
To access elements of a jagged array, you need to use two square bracket operators [][]
:
int[][] jaggedArray = new int[][]
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
// Access single elements
int element = jaggedArray[0][1]; // Gets the value 2
Console.WriteLine($"Element at position [0][1]: {element}");
// Change a value
jaggedArray[2][3] = 99;
Console.WriteLine($"Modified element at position [2][3]: {jaggedArray[2][3]}");
Output:
Element at position [0][1]: 2
Modified element at position [2][3]: 99
Iterating Through Jagged Arrays
To iterate through a jagged array, you need nested loops:
int[][] jaggedArray = new int[][]
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
// Print all elements of the jagged array
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(); // New line after each row
}
Output:
Row 0: 1 2 3
Row 1: 4 5
Row 2: 6 7 8 9
You can also use foreach loops for more elegant iteration:
int[][] jaggedArray = new int[][]
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
// Using foreach loops
int rowIndex = 0;
foreach (int[] row in jaggedArray)
{
Console.Write($"Row {rowIndex++}: ");
foreach (int element in row)
{
Console.Write($"{element} ");
}
Console.WriteLine();
}
Jagged Arrays vs Multidimensional Arrays
Let's compare jagged arrays with regular multidimensional arrays:
Feature | Jagged Arrays | Multidimensional Arrays |
---|---|---|
Memory layout | Non-contiguous | Contiguous |
Row lengths | Can be different | Must be the same |
Declaration | int[][] | int[,] |
Access syntax | array[i][j] | array[i, j] |
Performance | Potentially better for sparse data | Better for consistent dimensions |
Flexibility | More flexible structure | More rigid structure |
Practical Example: Student Scores
Let's implement a practical example where we store test scores for different classes, where each class may have a different number of students:
using System;
class Program
{
static void Main()
{
// Create a jagged array to store scores for different classes
int[][] classScores = new int[3][];
// Class 1 has 4 students
classScores[0] = new int[] { 85, 92, 78, 95 };
// Class 2 has 3 students
classScores[1] = new int[] { 88, 76, 90 };
// Class 3 has 5 students
classScores[2] = new int[] { 91, 82, 70, 88, 95 };
// Calculate and display average score for each class
for (int i = 0; i < classScores.Length; i++)
{
int sum = 0;
foreach (int score in classScores[i])
{
sum += score;
}
double average = (double)sum / classScores[i].Length;
Console.WriteLine($"Class {i + 1} Average Score: {average:F2}");
}
// Find the class with the highest average
double[] averages = new double[classScores.Length];
for (int i = 0; i < classScores.Length; i++)
{
int sum = 0;
foreach (int score in classScores[i])
{
sum += score;
}
averages[i] = (double)sum / classScores[i].Length;
}
double maxAverage = averages[0];
int maxIndex = 0;
for (int i = 1; i < averages.Length; i++)
{
if (averages[i] > maxAverage)
{
maxAverage = averages[i];
maxIndex = i;
}
}
Console.WriteLine($"\nClass {maxIndex + 1} has the highest average score: {maxAverage:F2}");
}
}
Output:
Class 1 Average Score: 87.50
Class 2 Average Score: 84.67
Class 3 Average Score: 85.20
Class 1 has the highest average score: 87.50
Real-World Application: Storing Survey Responses
Jagged arrays are perfect for scenarios where data has varying dimensions. Here's an example that simulates storing survey responses where each respondent answers a different number of questions:
using System;
class Program
{
static void Main()
{
// Create a jagged array to store survey responses
string[][] surveyResponses = new string[4][];
// Respondent 1 answered 3 questions
surveyResponses[0] = new string[]
{
"Strongly Agree",
"Neutral",
"Disagree"
};
// Respondent 2 answered all 5 questions
surveyResponses[1] = new string[]
{
"Agree",
"Strongly Agree",
"Neutral",
"Strongly Disagree",
"Agree"
};
// Respondent 3 answered only 2 questions
surveyResponses[2] = new string[]
{
"Disagree",
"Agree"
};
// Respondent 4 answered 4 questions
surveyResponses[3] = new string[]
{
"Neutral",
"Neutral",
"Strongly Agree",
"Disagree"
};
// Display all responses
Console.WriteLine("Survey Responses:\n");
for (int i = 0; i < surveyResponses.Length; i++)
{
Console.WriteLine($"Respondent {i + 1} (answered {surveyResponses[i].Length} questions):");
for (int j = 0; j < surveyResponses[i].Length; j++)
{
Console.WriteLine($" Question {j + 1}: {surveyResponses[i][j]}");
}
Console.WriteLine();
}
// Find the most common response
Dictionary<string, int> responseCounts = new Dictionary<string, int>();
foreach (string[] responses in surveyResponses)
{
foreach (string response in responses)
{
if (responseCounts.ContainsKey(response))
{
responseCounts[response]++;
}
else
{
responseCounts[response] = 1;
}
}
}
string mostCommonResponse = "";
int maxCount = 0;
foreach (var pair in responseCounts)
{
if (pair.Value > maxCount)
{
maxCount = pair.Value;
mostCommonResponse = pair.Key;
}
}
Console.WriteLine($"The most common response was: {mostCommonResponse} (appeared {maxCount} times)");
}
}
Advanced: Jagged Array of Objects
You can also create jagged arrays of custom objects:
using System;
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"{Name} (Age: {Age})";
}
}
class Program
{
static void Main()
{
// Create a jagged array of Student objects
Student[][] schoolClasses = new Student[2][];
// Initialize the first class with 3 students
schoolClasses[0] = new Student[3];
schoolClasses[0][0] = new Student { Name = "Alice", Age = 15 };
schoolClasses[0][1] = new Student { Name = "Bob", Age = 16 };
schoolClasses[0][2] = new Student { Name = "Charlie", Age = 15 };
// Initialize the second class with 2 students
schoolClasses[1] = new Student[2];
schoolClasses[1][0] = new Student { Name = "Diana", Age = 16 };
schoolClasses[1][1] = new Student { Name = "Edward", Age = 17 };
// Display all students by class
for (int i = 0; i < schoolClasses.Length; i++)
{
Console.WriteLine($"Class {i + 1} Students:");
foreach (Student student in schoolClasses[i])
{
Console.WriteLine($" {student}");
}
Console.WriteLine();
}
}
}
Output:
Class 1 Students:
Alice (Age: 15)
Bob (Age: 16)
Charlie (Age: 15)
Class 2 Students:
Diana (Age: 16)
Edward (Age: 17)
Summary
Jagged arrays in C# are powerful data structures that allow you to create arrays of arrays with different lengths. They offer flexibility when dealing with irregular data that can't be neatly organized into rectangular multi-dimensional arrays.
Key points to remember:
- Jagged arrays are arrays of arrays
- Each inner array can have a different length
- Use double square brackets for access:
array[i][j]
- They're useful for representing irregular data structures
- You can nest jagged arrays to create more complex structures
- Jagged arrays can sometimes be more memory-efficient than multidimensional arrays
Exercises
-
Create a jagged array to represent a triangle pattern with the numbers 1 through 10, where each row has one more element than the previous row.
-
Write a program that uses a jagged array to represent a weekly schedule, where each day might have a different number of activities.
-
Create a jagged array to store temperatures for a month where each row represents a week and each element represents a day's temperature.
-
Implement a program that uses a jagged array to represent a small library where each row is a book category, and the elements are book titles.
-
Challenge: Create a method that converts a regular 2D rectangular array to a jagged array where empty or default values are removed from the end of each row.
Additional Resources
Happy coding with jagged arrays!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)