5.2 Using for loop

The concept

One of the most powerful part of computer is it can perform repetitive tasks very efficiently. In order for computers to do that, we need to introduce loop.


List<String> seasons = new List<String>{'Winter', 'Spring', 'Summer', 'Fall'};
for(String season: seasons) 
{
    System.debug(season);
}

List numberList = new List();
for(Integer i = 0; i < 10; i++) 
{
    numberList.add(i + 1);
}

Integer sum = 0;
for(Integer num: numberList)
{
    sum += num;
}
System.debug('Sum is: ' + sum);

The result should be similar to the following:
forloop

A bit explanation

for loop has two formats. The first one is more traditional:

for(initialisation; escape condition; afterthought)

Initialisation is the initialise of the looping variable. This is done for 1 time only which is before the loop begins.

Escape condition is when this statement becomes true, the loop ends.

Afterthought is executed every time one single loop run ends. So the loop works in the way described in the following picture:

loop_pic

Another format is usually called the foreach or for … in format. The grammar is:

for(T var: [list or set])

Here T is the type. var is the variable name. It basically means this will iterate through all the elements in the list or set. We will explain what is set in the container chapter.

For loop is a very powerful tool. It is used almost everywhere in programming world. We will talk more about using loop and condition statements with examples in next chapter.

Exercise

Try to write a program to calculate 3 + 6 + 9 + … + 99 .

Next post

5.3 Using while loop

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Comments

  1. Paolo - May 30, 2017 @ 1:39 pm

    List seasons = new List {‘Winter’, ‘Spring’, ‘Summer’, ‘Fall’};// you forgot to define the list type ()
    for(String season: seasons)
    {
    System.debug(season);
    }

    • LanceShi - May 30, 2017 @ 1:42 pm

      You are right. Thank you for that. I will update the post.

  2. Paolo - May 30, 2017 @ 1:40 pm

    List seasons = new List {‘Winter’, ‘Spring’, ‘Summer’, ‘Fall’};
    for(String season: seasons)
    {
    System.debug(season);
    }

Leave a Reply

Your email address will not be published / Required fields are marked *