Mastering Nested Loops in Dart

Introduction

Our journey today delves into the intricate world of Exploring Nested Loops in Dart. Think of these as interlocking cogs within a mechanism, each managing its distinct movement. By the end of this session, we aim to understand and adeptly navigate these loops in Dart.

Structure of a Nested for Loop in Dart

We begin by revealing the structure of a nested for loop in Dart:

Dart
for (var i = 0; i < 3; i++) {
   for (var j = 0; j < 3; j++) {
       print('i = $i, j = $j'); // e.g., "i = 0, j = 0"
    }
}
/*
Prints:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
*/

With each progression of i from 0 to 2, we traverse through j from 0 to 2, notating the respective values of i and j.

Structure of a Nested while Loop in Dart

In addition to for loops, while loops can also incorporate nested loops:

Dart
var i = 0;
while (i < 3) {
    var j = 0;
    while (j < 3) {
        print('i = $i, j = $j'); // e.g., "i = 0, j = 0"
        j++;
    }
    i++;
}
/*
Prints:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
*/

In this instance as well, the inner loop j completes its cycle for each individual iteration of the outer loop i.

Iterations and Nested Loops: An Example

To illustrate nested loops, let's examine a two-dimensional (2D) list — essentially a list of lists:

Dart
var matrix = [
    [1, 2, 3],
    [4, 5, 6], 
    [7, 8, 9]
];

for (var i = 0; i < matrix.length; i++) {   // Iterating over each row.
    var row = '';
    for (var j = 0; j < matrix[i].length; j++) {  // Iterating over each element in the row.
        row += '${matrix[i][j]} ';
    }
    print(row);
}
/*
Prints:
1 2 3
4 5 6
7 8 9
*/

For every i row in the outer loop, an inner loop runs through every element within that row.

Combining `for` and `while` Loops: Building a Numerical Pyramid

Now let's explore how to combine a for loop with a while loop to construct a numerical pyramid. This example demonstrates the adaptability of nested loops in Dart and how they can be seamlessly integrated.

Dart
for (var i = 1; i <= 5; i++) { // The first loop (for) denotes each level of the pyramid.
    var row = '';
    var j = 1;
    while (j <= i) { // The second loop (while) adds numbers to each level.
        row += '$j ';
        j++;
    }
    print(row); // Prints each level of the pyramid.
}

/*
Prints:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal