×

Dart Loops

Looping refers to repeating or reusing the same lines of code repeatedly until a particular test condition evaluates to true. It is also known as iterating. 

It is effectively used when the same lines in our code are required to be repeated a finite number of times. In such a case, instead of writing the same lines, again and again, we put them inside the loop. 

Advantages of loops :

  1. It enables the reusability of the code. 
  2. It reduces any duplicity or redundancy of the lines of code. 
  3. It is used to insert elements in an array or traverse them. 

Types of loops in Dart :

There are four types of loops in Dart language, which are as follows : 

  1. for loop
  2. for…. In loop 
  3. while loop
  4. do - while loop

Dart for loop

The for loop is used to know the number of times a block of code is required to be executed. It is quite the same as the C for a loop. The syntax is given below.

Syntax -

for( Initialization ; condition ; increment / decrement statement ) {  
// body of the loop  
}  

An initialization statement is used to initialize the loop pointer with an initial value. The loop iteration begins from this initial value and executes for only one time.

The condition here is a test expression that evaluates to Boolean true or false. It is checked after each iteration. The for loop will execute till the condition evaluates to true. 

The increment/decrement statement is the counter to increasing or decreasing the value of the loop pointer.

Flow of loop

Step 1 : - First, the loop counter is initialized with some value. 

Step 2 : - The test condition present in the for loop overhead is checked. If it evaluates to true, then only further execution takes place.

Step 3 : - The compiler then executes the lines of code in the loop's body. 

Step 4 : - After successful execution of the statements, control passes to the increment/decrement statement. The value of the loop pointer is accordingly incremented/decremented. 

Step 5 : - The compiler then executes from step 2 to step 4. 

Let's understand the following example.

Program

void main( )  
{  
    int num = 5 ;  
    for( num ; num <= 15 ; num++ ) // for loop to print 1-10 numbers  
    {  
        print( num ) ; // to print the number  
    }  
}

Output :

5
6
7
8
9
10
11
12
13
14
15

Dart for… in Loop

Dart provides a loop similar to for loop, the for…in loop. This loop iterates the element only one at a time and takes the dart object or dart expression only as an iterator. The loop will keep on executing the statements until no element is left in the iterator. 

They are the most useful with the iteration statements such as list, sets. 

The syntax of the Dart for.... in loop -

 for ( var in expression ) {  
//statement( s )  
}  

Example :

void main( )  
{  
    print( ' \n The content of List 1 : ' ) ;
    
    // initializing the list 1 with integer values
    var list1 = [ 1, 2, 3, 4, 5 ] ;  
  
    // using the for.... in loop to print the values of the list
    for( var i in list1 )            
    {  
        // printing the values
        print( i ) ;        
    }  
  
    print( ' \n The content of List 2 : ' ) ;
  
    // initializing the list 2 with string values
    var list2 = [ ' A ', ' B ', ' C ', ' D ', ' E ' ] ;
  
    // using the for.... in loop to print the values of the list
    for( var j in list2 )
    {
        // printing the values 
        print( j ) ;
    }
} 

Output :

The content of List 1 : 
1
2
3
4
5
 
 The content of List 2 : 
 A 
 B 
 C 
 D 
 E

It is required to declare the iterable variable to iterate over the elements of the list to print them. 

Dart while loop

The while loop in Dart executes the given block of code until the expression specified in the syntax evaluates to false. Their use case is the time when we are unaware of the number of executions. 

It is also known as the entry - controlled loop as the condition is checked first and the statements contained in its body are evaluated only if the condition evaluates to true. Therefore, the least number of times the body of the while loop can be executed is 0.

Consider the following syntax of Dart while loop :

while( condition ) {  
   // loop body 
}  

Let's understand the following example.

Example -

void main( )  
{  
    var a = 1 ; 
    var max = 10 ;  
    
    print( ' \n First 10 natural numbers are : ' ) ; 
    while( a <= max ) 
    { 
      // this statement makes the block of code to be executed only till the condition evaluates to true.   
      print( a ) ;  
                 
      a = a + 1 ; // increases value 1 after each iteration  
    }  
}

Output :

1
2
3
4
5
6
7
8
9

Dart do…while Loop

The do…while loop is similar to the while loop, differing at just one point that it executes the statements contained in the body of the loop and then checks the given condition. It is an exit-controlled loop because it checks the condition at the end of the loop. Therefore, the least number of times the body of the while loop can be executed is 1.

Syntax -

do {  
    // loop body  
} while( condition ) ;  

Program

void main( )  
{  
 var a = 1 ; 
 var maxnum = 10 ;  
do  
    {                
       print( " The value is: ${ a } " ) ;  
       a = a+1 ;                                    
       }while ( a < maxnum ) ;  
}

Output :

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
The value is: 6
The value is: 7
The value is: 8
The value is: 9

Selection of the loop

The selection of a loop is a little difficult task for the programmer. It is hard to decide which loop will be more suitable to perform a specific task. We can determine the loop based on the following points.

Analyse the problem and observe whether you need a pre-test or a post-test loop.

  • A pre-test loop is that the condition is tested before entering the loop.
  • In the post-test loop, the condition is tested after entering the loop.
  • If we require a pre-test loop, select the while or for a loop.
  • If we require a post-test loop, then select the do-while loop.

Related Topics

Dart Method Overriding

Before understanding method overriding, it is important to clear the concept of polymorphism. Polymorphism is derived from two Greek words 'Poly' which means many and 'morphs' which means many forms....

5 minutes read.

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development...

6 minutes read.

Dart Logical Operators

Logical operators are the operators that combine two or more conditions, and accordingly return a Boolean value : true or false. Assume the value of variable A is 25 and B...

2 minutes read.

Dart - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart If-else-if statement

If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular...

2 minutes read.

Soundness in Dart

What is soundness? Soundness ensures that the program never comes across any invalid state that may lead to abrupt termination of the program. As its name suggests it ensures perfect type...

4 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Dart Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Dart Basic Program

Dart provides various convenient platforms to code and compile the program in Dart language. Some of them are: 1. Using IDE = Visual Studio code is a text editor with IDE....

3 minutes read.

Dart Equality and Relational Operators

Dart provides the functionality of checking the relationship between the values or values within the variables. These operators return the resultant value as Boolean, i.e., either ‘true’ or ‘false’. Some important points...

3 minutes read.

Dart this Keyword

The ' this ' keyword, similar to that in Java and C#, refers to an object of the class using it. It points to the current object of the class,...

5 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart Packages

Every programming language has some in-built functions stored inside the header files that makes the task much easier for the programmer. The Dart Packages refer to the compilation of a...

4 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Interfaces in Dart

An interface in Dart refers to the syntax or blueprint that any class must adhere to. It basically defines the array of methods available on the object. It provides the...

3 minutes read.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

2 minutes read.