ApexSensei

Drills › Write Apex

For loop: number invoices

Write Apex · Beginner · 10 min · Runs in your Salesforce Developer org · Free

Scenario. An export needs simple display numbers for each invoice in a known batch.

Number three invoices with a for loop, count the passes, and run the loop again with zero invoices.

What you will learn

A for loop has three parts: a start, a test, and a step. Use it when you know how many times to repeat.

for (Integer i = 1; i <= invoiceCount; i++) {
    System.debug('Invoice ' + i);
}

Starting at 0 with i < invoiceCount also runs invoiceCount times.

Gotcha. If the test is false before the first pass, the body runs zero times.

The task

Use a for loop to number three invoices, then run it again with zero invoices.

Examples:

  • passes 1 to 3 → Invoice: INV-1, Invoice: INV-2, Invoice: INV-3
  • after the loop → Numbered count: 3
  • zero invoices → Zero count: 0

Requirements:

  1. Loop once per invoice, up to invoiceCount. Start at 1 with <=, or start at 0 with <.
  2. On each pass, print Invoice: INV- plus the invoice number, and add 1 to numbered.
  3. After the loop, print Numbered count: with the value of numbered.
  4. For case B, reset numbered to 0 before the second loop, run the loop again, and print Zero count: with the result.

Starter code

Integer invoiceCount = 3;
Integer numbered = 0;

// Case A: number three invoices

// Case B: no invoices this time
invoiceCount = 0;
numbered = 0;

When it passes

INV-1, INV-2 and INV-3 print in order, the count is 3, and the zero-invoice run counts 0 passes.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Switch on Case status · For-each over Accounts ›