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

      Do-While Loops

      Do-While Loops

      A while loop checks its condition before the first pass, so its body might never run. Sometimes you want the opposite: run the body once, then decide whether to repeat. That is what a do-while loop is for.

      Basic Structure

      A do-while loop puts the body first and the condition at the end:

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

      The body always runs at least once because the condition is not checked until the end of the first pass.

      The Key Difference

      Compare the two loop types when the condition starts out false:

      Integer count = 5;
      
      // This body never runs
      while (count <= 3) {
          System.debug('while ran');
      }
      
      // This body runs one time
      do {
          System.debug('do-while ran');
      } while (count <= 3);
      

      The while loop skips its body entirely. The do-while loop runs its body one time before the condition stops it.

      Do Not Forget the Semicolon

      A do-while loop ends with a semicolon after the while condition. Forgetting it is a common beginner mistake that leads to a compile error.

      Why This Matters

      Use a do-while loop when the work must happen at least once, such as showing a menu before asking whether to show it again, or processing a value before checking whether more remain.

      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