Dart Loops & Conditions

Learn how to repeat tasks and make decisions in Dart programming.

1. What are Loops? (Programming Definition)

Loops allow you to repeat a block of code multiple times without writing it again and again. They help automate repetitive tasks.

2. Real-World Example: Loop

Imagine you want to water your 5 plants every day. Instead of saying "water plant 1", "water plant 2", and so on each time, you just say "repeat watering 5 times."

3. Example of a Loop in Dart (for loop)

void main() {
  for (int i = 1; i <= 5; i++) {
    print('Water plant number $i');
  }
}

This will print:

4. What are Conditions? (Programming Definition)

Conditions let your program make decisions. You check if something is true or false, then do different things based on that.

5. Real-World Example: Condition

Imagine if it is raining, you take an umbrella. If not, you don’t. This is a simple decision based on the condition "Is it raining?"

6. Example of a Condition in Dart (if-else)

void main() {
  bool isRaining = true;

  if (isRaining) {
    print('Take an umbrella.');
  } else {
    print('No umbrella needed.');
  }
}

This will print:

7. Combining Loops & Conditions

You can use loops and conditions together to create smart, repeated actions.

void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      print('Water plant number $i carefully.');
    } else {
      print('Water plant number $i');
    }
  }
}

This prints:

8. Summary