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

      While Loops

      While Loops

      So far your code has run each line once from top to bottom. A loop lets you repeat a block of code many times. The while loop is the simplest kind: it keeps running as long as a condition stays true.

      Basic Structure

      A while loop checks its condition before each pass. While the condition is true, the body runs again:

      Integer count = 1;
      
      while (count <= 3) {
          System.debug('Count is ' + count);
          count++;
      }
      

      This prints the count three times. Each pass through the loop body is called an iteration.

      The Three Parts

      Most while loops have three parts working together:

      1. Setup: create a variable before the loop, like Integer count = 1.
      2. Condition: the test inside the parentheses, like count <= 3.
      3. Update: change the variable inside the body so the condition eventually becomes false, like count++.

      If you forget the update step, the condition never becomes false and the loop runs forever. This is called an infinite loop, and Salesforce will stop it with an error.

      When the Body May Not Run

      Because the condition is checked first, the body might not run at all. If count starts at 5 and the condition is count <= 3, the loop is skipped entirely.

      Why This Matters

      Loops let you process many values without repeating yourself. Whenever you need to count, add up numbers, or keep going until something changes, a while loop is a natural fit.

      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