Skip to main content
Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.

Use Loops

Learning Objectives

After completing this unit, you’ll be able to:

  • Differentiate between while and do-while loops.
  • Use incrementing and decrementing operators to control code execution.

In our Teatime example, we made a pot of tea to share with our closest friends. But what happens if we need to serve tea to a group of 100 people? We need to do the same steps over and over again until everyone has been served. Sounds like that’s going to be a lot of redundant code, doesn’t it? That’s where loops come in handy.

A loop is a block of code that is repeated until a certain condition is met. In the case of the Teatime code, let’s review the steps to be repeated:

Add Tea and Sugar to Teacup
Pour Tea in Teacup
Put 1 teaspoon of Sugar in Teacup
Stir Tea in Teacup
Serve Tea to a Friend

Repeated steps can be added to a loop. Apex has three ways to loop code: while, do-while, and for loops. For now, we’ll focus on while and do-while loops. Like their names, while and do-while loops are very similar. Both verify that a particular condition is met. The differentiator is when they verify that the condition is met. While loops check the condition before the loop starts, and do-while loops check it after the loop is finished. 

Seems like such a small detail, right? Actually, the impact is pretty big. 

Think of it this way: the do-while loop always runs at least once. The while loop might never run, depending on the condition. 

While Loops

The while loop starts with verifying if a condition has been met. If the condition is true, it does something. If it’s false, the loop stops.

A graphical process flow for a while loop consisting of a condition being verified to see if it is true or false. If the condition is true the loop continues. If the condition is false the loop stops.

Note

Note

For a refresher on flowchart symbols and notation click here.

Here’s the syntax:

While(condition) {
    //run this block of code
}

Let’s apply while loops to our Teatime code. 

  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. Copy this code and paste it into the Enter Apex Code window.
    //Declare an Integer variable called totalGuests and set it to 100
    Integer totalGuests = 100;
      
    //Declare an Integer variable called totalAmountSugar and set it to 159 (number of teaspoons in a bag of sugar).
    Integer totalAmountSugar = 159;
      
    //Declare an Integer variable called totalAmountTea and set it to 35 (number of teabags).
    Integer totalAmountTea = 35;
      
    //Loop: Add a teaspoon of sugar and one tea bag to a tea cup. Serve until there is no sugar or tea left.
      
    While(totalGuests > 0) {
        System.debug(totalGuests + ' Guests Remaining');
        //check ingredients
        if(totalAmountSugar == 0 || totalAmountTea == 0) {
            System.debug('Out of ingredients! Sugar: ' + totalAmountSugar + ' Tea: ' + totalAmountTea);
            break; //ends the While loop
        }
      
        //add sugar
        totalAmountSugar--;
      
        //add tea
        totalAmountTea--;
      
        //guest served
        totalGuests--;
    }
  3. Select the Open log checkbox and then click Execute. The Execution Log opens, displaying the result of running your code.
  4. Select the Debug Only checkbox at the bottom of the window.

No, that -- sign is not a typo. It’s called a post-decrement operator. It's a shorthand way of saying, “Subtract one number from this value.” If totalAmountSugar is equal to 159, decrement it so that now the value of totalAmountSugar is equal to 158. The Post Increment Operator, ++, does the opposite, adding one number to the value.

What exactly is going on here? Remember, we have one main goal: serve tea to 100 guests. Each time we serve a guest, a serving of each ingredient (totalAmountSugar and totalAmountTea) and a guest (totalGuests) are deducted. When the totalAmountSugar or the totalAmountTea gets to 0 (line 15) OR the totalGuests gets to 0 (line 12) the loop stops and no one else is served. 

Let’s look at how the do-while loop works.

Do While Loops

A do-while loop allows the code to do something once before the condition is tested.

The do-while loop starts with doing a task once. Next, a condition is verified. If the condition is true, it runs the task again. If it’s false, the loop stops.

A graphical process flow for a do-while loop consisting a block of code being run and then a condition being verified to see if it is true or false. If the condition is true the loop continues. If the condition is false the loop stops.

Take a look at the syntax:

Do {
    //run this block of code
} while(condition);
  1. In the Developer Console, click Debug | Open Execute Anonymous Window.
  2. Copy this code and paste it into the Enter Apex Code window.
    //Declare an Integer variable called totalGuests and set it to 100
    Integer totalGuests = 100;
      
    //Declare an Integer variable called totalAmountSugar and set it to 159 (number of teaspoons in a bag of sugar).
    Integer totalAmountSugar = 159;
      
    //Declare an Integer variable called totalAmountTea and set it to 35 (number of teabags).
    Integer totalAmountTea = 35;
      
    do {
        //deduct sugar serving
        totalAmountSugar--;
      
        //deduct tea serving
        totalAmountTea--;
      
        //deduct guest
        totalGuests--;
      
        System.debug(totalGuests + ' Guests Remaining!');
      
        //check ingredients
        if(totalAmountSugar == 0 || totalAmountTea == 0) {
            System.debug('Out of ingredients!');
            break; //ends the While loop
        }
      
    } while(totalGuests > 0);
  3. Select the Open log checkbox and then click Execute. The Execution Log opens, displaying the result of running your code.
  4. Select the Debug Only checkbox at the bottom of the window.

You’ve declared variables, instantiated values, created lists, and looped data multiple ways. Congratulations! You’ve completed an introduction to Apex and are well on your way to understanding more about code.

Resources

Share your Trailhead feedback over on Salesforce Help.

We'd love to hear about your experience with Trailhead - you can now access the new feedback form anytime from the Salesforce Help site.

Learn More Continue to Share Feedback