Learn how to repeat tasks and make decisions in Dart programming.
Loops allow you to repeat a block of code multiple times without writing it again and again. They help automate repetitive tasks.
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."
void main() {
for (int i = 1; i <= 5; i++) {
print('Water plant number $i');
}
}
This will print:
Conditions let your program make decisions. You check if something is true or false, then do different things based on that.
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?"
void main() {
bool isRaining = true;
if (isRaining) {
print('Take an umbrella.');
} else {
print('No umbrella needed.');
}
}
This will print:
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: