Loops in Dart

See how loops iterate and variables change in each iteration

Loops in Dart


Definition

A loop is a control structure that repeats a block of code until a condition is no longer true. Loops help you avoid writing the same code multiple times and process collections of data efficiently.


Three Types of Loops


**for Loop**

Repeats code a specific number of times using a counter variable.

`

for (int i = 0; i < 5; i++) {

// Code runs 5 times (i = 0, 1, 2, 3, 4)

}

`

**while Loop**

Repeats code as long as a condition is true.

`

while (condition) {

// Code runs while condition is true

}

`

**for-in Loop**

Iterates through each item in a collection.

`

for (var item in collection) {

// Code runs for each item

}

`

Key Concepts


Loop Counter

  • The variable that controls how many times a loop runs
  • Often named 'i', 'j', or 'index'
  • Incremented or decremented each iteration

  • Iteration

  • One complete execution of the loop body
  • Each iteration processes one step

  • Exit Condition

  • The condition that must become false to stop the loop
  • Prevents infinite loops
  • Cell2Dart
    // For loop example int sum = 0; for (int i = 0; i < 5; i++) { sum = sum + i; print('i = $i, sum = $sum'); } print('Final sum: $sum');

    How Loops Work


    1. **Initialization**: Set up the counter variable (i = 0)

    2. **Check Condition**: Is the condition true? (i < 5?)

    3. **Execute Body**: Run the code inside the loop

    4. **Update**: Change the counter (i++)

    5. **Repeat**: Go back to step 2


    Watch the Memory visualization on the right to see how variables change with each iteration!

    Cell4Dart
    // While loop example int count = 0; while (count < 3) { print('Count: $count'); count = count + 1; } print('Done!');

    Real-World Uses


  • **Processing Lists**: Go through each item in a list
  • **Summing Values**: Add up multiple numbers
  • **Counting**: Count occurrences of something
  • **Searching**: Find an item in a collection
  • **Validation**: Repeat until user input is valid
  • Cell6Dart
    // For-in loop over a list List<String> fruits = ['Apple', 'Banana', 'Orange']; for (String fruit in fruits) { print('Fruit: $fruit'); }

    Practice

    CellcustomDart
    // Try a while loop int count = 0; while (count < 3) { print('Count: $count'); count = count + 1; }
    Run code to see variables update