Course contentsShow
← Computer Science
Lesson 246 of 2,8726. Arrays and Basic CollectionsFree lesson

Jagged Arrays (Arrays of Arrays)

Understand non-rectangular arrays where each row can have different lengths, their declaration and use cases.

Jagged Arrays (Arrays of Arrays)

You'll learn: How to create arrays where each row can have a different number of elements, unlike the uniform rectangular arrays you've seen before.

What Makes an Array "Jagged"?

Until now, you've worked with 2D arrays that are rectangular—every row has exactly the same number of columns. A jagged array breaks this pattern: it's literally an array of arrays, where each inner array can have its own unique length.

Think of it like a bookshelf where each shelf holds a different number of books. Shelf one might have 3 books, shelf two might have 7, and shelf three might have just 1. The shelves don't need to match.

Why Use Jagged Arrays?

Jagged arrays are perfect when your data naturally has uneven rows:

  • A classroom roster where each class has different enrollment numbers
  • A tournament bracket where each round has fewer matches
  • Monthly expense logs where different months have different numbers of transactions

Declaration and Structure

Instead of declaring a single rectangular block, you declare an array that holds other arrays. Each inner array is created independently with its own length:

// Array of 3 arrays, each with different lengths
row1 has 2 elements
row2 has 4 elements  
row3 has 1 element

The outer array tracks how many rows you have, but each row manages its own size. When you access elements, you still use two indices, but the valid range for the second index depends on which row you're in.

Key Takeaway: Jagged arrays are arrays of arrays where each inner array can have a different length, making them more flexible but requiring careful tracking of individual row sizes.