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.
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.
Most while loops have three parts working together:
Integer count = 1.count <= 3.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.
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.
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.