For and While loop in Dart

Loops means a specific thing is going/working on again and again. In programming loops are used to reduce rewritting of code for a constant tidious work, let's say taking an input from user multiple times (say 10 times). This will make our code length too lon just for a small thing. So we use loops in here for this reason.

There are major two loops which you need to be familiar with in Dart. First is For loop, and While loop being the second. You can generate a piece of code for as many times as you want by specifiying some conditions using these loops. Let us see some handy examples:

For Loop:
    Syntactical Use:
    Print 100 numbers
    1.   for(int i=0 ; i < 100 ; i++ ){
    2.        //  a        b      c
    3.         print(i);
    4.   }
In this loop, there are three statements separated by semicolon in line 1 . Those three parts are:
a = Initiation
b = Conditional Expression
c = Increment/Decrement
Line 2, is a comment to show that which, part is signifying what in the first line. Line 3, is a print statement to print the current value of i.

In the above loop, at first the value of i is intiated to zero, which is less than 100, hence the statements inside the loop(enclosed in following curly braces) will be executed i.e. printing i or zero in here. After everything inside the loop is executed once, the value of i is self incremented, due to i++. This means now the value of i is one, which is less than 100 and again entering the loop statements, we will get 1 printed, and this cycle will go on continuing for the values of i till it is less than 100.

A thing to observe is we will get numbers printed in our console from 0 to 99, but not 100. Because, 100 is not less than 100, it is equal to itself. Hence the part b will be false and the loop condition is now unsatisfied, due to which it will terminate the loop and exit.

While Loop
    Syntactical Use: 
    Print 100 numbers
    1.  int i=0;  // a
    2.  while( i < 100 ){
    3.         // b
    4.      print(i);
    5.      i = i+1; // c 
    6.   }
While loop
can be used same as For loop, but the difference is that, in for loop parts: a, b, c were defined in a single parenthesis, whereas in while loop, only the part b of Conditional Expression has to be written in parenthesis. We need to explicitly define and increment the counter variable i. Here also, the numbers will be printed from 0 to 99.

Need more Information?
Click here for YouTube Link
Very Easy! Follow my video lectures on YouTube link and keep reading my blog here for more information. In the video lectures, I have explained all the basic and minor details. The same content will be posted on this website if you like reading more than watching.