• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Loops
  4. For Loops

      For Loops

      For Loops

      A while loop works well when you count by hand: you set up a counter, check a condition, and remember to update the counter yourself. A for loop packages all three of those steps into a single line, which makes counting loops shorter and harder to get wrong.

      Basic Structure

      A for loop has three parts inside the parentheses, separated by semicolons:

      for (Integer i = 0; i < 5; i++) {
          System.debug('i is ' + i);
      }
      
      • Initialization (Integer i = 0) runs one time before the loop starts.
      • Condition (i < 5) is checked before every pass. When it is false, the loop stops.
      • Update (i++) runs at the end of every pass.

      This loop prints 0, 1, 2, 3, and 4. The counter starts at 0, the body runs while i is less than 5, and i grows by one each time.

      Counting in Different Ways

      Because all three parts live in one place, a for loop is easy to adjust. You can start somewhere else, stop somewhere else, or step by a different amount:

      // Count 1 through 10
      for (Integer i = 1; i <= 10; i++) {
          System.debug(i);
      }
      
      // Count down from 5 to 1
      for (Integer i = 5; i >= 1; i--) {
          System.debug(i);
      }
      
      // Step by two: 0, 2, 4, 6
      for (Integer i = 0; i <= 6; i += 2) {
          System.debug(i);
      }
      

      Why This Matters

      A for loop keeps the counter, the stopping test, and the update together, so it is easy to read and hard to forget a step. When you know how many times you need to repeat, a for loop is usually the clearest choice.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In