×

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 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 Booleans

Booleans Dart has a data type named ‘bool’ to represent Boolean values : true and false, which are compile-time constants. ‘True’ or ‘False’ cannot be assigned with values 1 or 0. Example, bool...

1 minute 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 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 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.

Dart Inheritance

Inheritance is a promising concept of any programming language. It is a property by which a class inherits the property of another class. Moreover, the class deriving the properties of...

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 Keywords

Keywords are the reserved words of a programming language, and they have a special meaning that comes defined by the language. These cannot be used as an identifier, and all...

1 minute read.

Dart Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

4 minutes read.

Dart Queues

A queue is a user-defined collection of data. It is based on the FIFO principle ( First In First Out ) which implies that the element to be inserted first,...

3 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 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 Important Concepts

1. Anything placed in a variable is an object, and an object is an instance of a class. Numbers, functions, and null are all objects in Dart, and all these...

3 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.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

1 minute read.

Dart - extends, with and implements Keywords

The application development in Dart programming language using the Flutter framework, regularly experience different usage of the implements, extends and with keywords. Dart has full support for inheritance that is...

5 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

4 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.