Loops in Dart
Looping
In Programming, looping is used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. For E.g, For printing name 10 times, you can use loop.
Types of Loop
- For Loop
- For each Loop
- While Loop
- Do While Loop
For Loop
This is the most common type of loop. You can use for loop to run a block of code multiple times according to condition.
Syntax
for(initialization; condition; increment/decrement){
statements;
}
- Initialization is executed (one time) before the execution of the code block.
- Condition defines the condition for executing the code block.
- Increment/Decrement is executed (every time) after the code block has been executed.
Example To Print 1 To 10 Using For Loop Increment
void main() {
for (int i = 1; i <= 10; i++) {
print(i);
}
}
Example To Print 10 To 1 Using For Loop Decrement
void main() {
for (int i = 10; i >= 1; i--) {
print(i);
}
}
For each Loop
The for each
loop iterates over all elements of list or variable. It is a higher order function.
Example For List
void main(){
List<String> footballplayer=['Ronaldo','Messi','Neymar','Hazard'];
footballplayer.forEach( (names)=>print(names));
}
Example For Variable
void main(){
var name=['ram','hari','aastha','kiran'];
name.forEach((var names)=>print(names));
}
While Loop
The body of the loop will run until and unless the condition is true. You must write condition first before statements.
Syntax
while(condition){
//statement(s);
// Increment (++) or Decrement (--) Operation;
}
Example To Print 1 To 10 Using While Loop Increment
void main() {
int i = 1;
while (i <= 10) {
print(i);
i++;
}
}
Example To Print 10 To 1 Using While Loop Decrement
void main() {
int i = 10;
while (i >= 1) {
print(i);
i--;
}
}
Do While Loop
Do while loop is used to run a block of code multiple times. Simply you can say, the body of the loop will be executed first and then the condition is tested.
Syntax
do{
statement1;
statement2;
.
.
.
statementN;
}while(condition);
Example To Print 1 To 10 Using Do While Loop Increment
void main() {
int i = 1;
do {
print(i);
i++;
} while (i <= 10);
}
Example To Print 10 To 1 Using Do While Loop Decrement
void main() {
int i = 10;
do {
print(i);
i--;
} while (i >= 1);
}