Jagged Arrays
Part of the Logic & Flow section of Coddy's Java journey — lesson 6 of 59.
A jagged array is a special type of 2D array where each row can have a different number of columns. In other words, it's an array of arrays, and each "inner" array can be of a different length. This is different from a regular 2D array, where all rows have the same number of columns, forming a rectangular shape.
Jagged arrays are useful when you need to store data that doesn't fit neatly into a rectangular grid. For example, you might use a jagged array to store the words in each sentence of a paragraph, where each sentence has a different number of words.
Here's how you declare and initialize a jagged array in Java:
data_type[][] array_name = new data_type[number_of_rows][];
// Initialize each row with a different number of columns
array_name[0] = new data_type[number_of_columns_in_row_0];
array_name[1] = new data_type[number_of_columns_in_row_1];
// ... and so onNotice that when you first declare the array, you only specify the number of rows. Then, you initialize each row separately, specifying the number of columns for that row.
Challenge
EasyCreate a method named createJaggedArray that takes an integer n as input returns a jagged array of integers. The jagged array should have the following structure:
- The first row should have 1 element.
- The second row should have 2 elements.
- The third row should have 3 elements.
- And so on, up to the
nrow, which should havenelements.
Initialize each element of the array with the product of its row and column indices (starting from 1). For example, the element at the second row and first column should have the value 2 * 1 = 2.
Cheat sheet
A jagged array is a 2D array where each row can have a different number of columns, unlike regular 2D arrays where all rows have the same length.
To declare and initialize a jagged array:
data_type[][] array_name = new data_type[number_of_rows][];
// Initialize each row with a different number of columns
array_name[0] = new data_type[number_of_columns_in_row_0];
array_name[1] = new data_type[number_of_columns_in_row_1];
// ... and so onWhen declaring a jagged array, you only specify the number of rows initially, then initialize each row separately with its specific number of columns.
Try it yourself
// Write your code only inside the class. Do not write main() or any code outside this class.
class CreateJaggedArray {
public static int[][] createJaggedArray(int n) {
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap