Understanding the types of loops in Dart and how to use them.
Prerequisites
To test this code, you should be able to access Dartpad.dev or have a Dart SDK platform where you can run this code.
What are loops?
The loop is a function of code that allows you to run a desired request repeatedly until an outcome is achieved.
Loops work by checking the given condition and repeating the process until that condition is met.
Types of loops in dart.
- For loop.
- While loop.
- Do-while loop (A type of while-loop).
- For-in loop (A type of for-loop).
- For-each loop (A type of for-loop).
● For loop.
In the main function, we created the for loop by using the for keyword.
We then proceeded by creating an integer variable named I and assigned 0 to it.
The condition here states that i < 5; i++ for i is less than 5 adding 1. This means as long as I is less than 5 add 1.
Here is the output.
● While loop.
In this type of loop, it is written with the keyword while before the condition.
On every iteration, the loop checks the condition.
While(condition){}
Here is the output.
Note: Avoid writing a condition that is always true to avoid falling into an infinite loop.
● Do-while loop.
Just as the name indicates, it's simply do-while. It carries the function first before checking the condition.
The condition is placed last in this type of loop. It is executed at least once.
Here is the result
● For-in loop.
For-in loop is used to loop through the properties of an object.
This loops through the properties in order.
For everything in this variable
Here is the output.
● For each loop.
In this type of loop, you can simplify the for-in loop.
The for-each loop applies to collections.
For Example.
Here is the output.
Top comments (2)
Good one. It also resemble Javascripts. Nice one
It does. Thank you 😊