Jagged Array in C# - Easy Guide with Examples and Code
👋 Introduction
Hey there! 😊 Ever tried fitting different-sized books into shelves? Some shelves are wide, some narrow. Similarly, in coding, sometimes you need arrays with rows of different lengths. That’s where a jagged array in C# comes to the rescue!
Unlike regular arrays (which are neat and equal), C# jagged arrays are flexible. Each row can have a different number of elements—just like those bookshelves. 📚 Pretty cool, right?
🎯 What You Are Going to Learn in This Lesson:
✔️ What is a jagged array in C#?
✔️ How to create and use a C# jagged array.
✔️ Real-world scenarios with examples.
✔️ 4 simple programs with code, output, and detailed explanations.
✔️ Why and when to use jagged arrays.
🧪 What is a Jagged Array in C#?
A jagged array in C# is an array of arrays. Think of it like a row of mailboxes, each with different numbers of letters inside. ✉️ Some have 2 letters, some have 5!
👉 Unlike multi-dimensional arrays (which are like perfect tables), C# jagged arrays let each row be as long or short as you need. Flexibility at its best! 🙌
📝 Syntax of Jagged Array in C#:
// Declaring a jagged array
int[][] jaggedArray = new int[3][];
// Initializing each row
jaggedArray[0] = new int[2]; // 2 elements
jaggedArray[1] = new int[3]; // 3 elements
jaggedArray[2] = new int[1]; // 1 element
🧩 Explanation:
int[][]
means an array of integer arrays.new int[3][]
creates a jagged array with 3 rows.- Each row is initialized separately. This gives you the freedom to vary lengths! 🎯
💻 Example 1: Basic Jagged Array Program
Let’s write a simple program to see how it works. 🚀
using System;
class Program
{
static void Main()
{
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write($"Row {i + 1}: ");
foreach (int num in jaggedArray[i])
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
}
💥 Output:
Row 1: 1 2
Row 2: 3 4 5
Row 3: 6
🔍 Code & Output Explained:
- We created a C# jagged array with 3 rows.
- The first row has 2 numbers, the second has 3, and the third has 1.
- The
foreach
loop makes it easy to display the numbers. - Notice how the rows aren’t equal? That’s the beauty of jagged arrays in C#! 😎
Here’s a table that visualizes a jagged array to help you understand it better:
Outer Array Index | Inner Array Elements |
---|---|
0 | 10, 20, 30 |
1 | 40, 50 |
2 | 60, 70, 80, 90 |
How to Read the Table:
- The Outer Array has 3 elements (indices: 0, 1, 2).
- Each element in the outer array points to an inner array with different lengths.
- For example:
array[0]
→{10, 20, 30}
(3 elements)array[1]
→{40, 50}
(2 elements)array[2]
→{60, 70, 80, 90}
(4 elements)
This uneven structure is what makes it a jagged array! 😊
🌍 Example 2: Real-World Scenario – Movie Showtimes 🎥🍿
Imagine you manage movie showtimes at different theaters. Each theater shows a different number of movies. Let’s model that!
using System;
class Program
{
static void Main()
{
int[][] showtimes = new int[3][];
showtimes[0] = new int[] { 10, 13 };
showtimes[1] = new int[] { 11, 14, 17, 20 };
showtimes[2] = new int[] { 9, 12, 15 };
for (int i = 0; i < showtimes.Length; i++)
{
Console.Write($"Theater {i + 1} showtimes: ");
foreach (int time in showtimes[i])
{
Console.Write(time + " ");
}
Console.WriteLine();
}
}
}
💥 Output:
Theater 1 showtimes: 10 13
Theater 2 showtimes: 11 14 17 20
Theater 3 showtimes: 9 12 15
📝 Explanation:
- Each theater (row) has its own set of showtimes.
- Theater 2 has more showtimes than Theater 1 and 3.
- This unevenness is why a jagged array in C# is perfect for this scenario.
🧮 Example 3: Student Test Scores 📊
Different students took different numbers of tests. Let’s track their scores!
using System;
class Program
{
static void Main()
{
int[][] studentScores = new int[2][];
studentScores[0] = new int[] { 85, 90, 78 };
studentScores[1] = new int[] { 92, 88 };
for (int i = 0; i < studentScores.Length; i++)
{
Console.Write($"Student {i + 1} scores: ");
foreach (int score in studentScores[i])
{
Console.Write(score + " ");
}
Console.WriteLine();
}
}
}
💥 Output:
Student 1 scores: 85 90 78
Student 2 scores: 92 88
🧩 Explanation:
- Student 1 took 3 tests; Student 2 took 2.
- Perfect example of when a C# jagged array is a lifesaver! 🎯
🚀 Example 4: Weekly Temperature Records 🌡️
Record varying temperatures over different days.
using System;
class Program
{
static void Main()
{
int[][] weeklyTemps = new int[3][];
weeklyTemps[0] = new int[] { 22, 24, 23 };
weeklyTemps[1] = new int[] { 19, 20 };
weeklyTemps[2] = new int[] { 25, 27, 26, 28 };
for (int i = 0; i < weeklyTemps.Length; i++)
{
Console.Write($"Day {i + 1} temperatures: ");
foreach (int temp in weeklyTemps[i])
{
Console.Write(temp + "°C ");
}
Console.WriteLine();
}
}
}
💥 Output:
Day 1 temperatures: 22°C 24°C 23°C
Day 2 temperatures: 19°C 20°C
Day 3 temperatures: 25°C 27°C 26°C 28°C
📝 Why this example rocks:
- Different days have different readings.
- That’s why C# jagged arrays are so useful in real life! 🌍
🏆 Why Use Jagged Arrays?
✅ Save memory by having varying lengths.
✅ Handle real-world data effortlessly.
✅ Flexible and super easy to use.
🎯 Conclusion
Phew! 🎉 You’ve just mastered jagged arrays in C#! They’re like magic shelves—flexible, easy to manage, and perfect for uneven data. Whether it’s movie times, scores, or temperatures, C# jagged arrays have your back.
👉 Keep practicing! Play around with different sizes and data. You’ll be amazed at how handy they are! 😎
🔜 Next What?
Up next, we’ll explore Iterating Through Arrays in C#! 🎢 Ready to make looping through data a breeze? Stay tuned and keep that coding spirit alive! 💻🔥