Loops Grade 10

Loops repeat a block of code multiple times. Delphi has three loop types — choose based on whether you know how many times to repeat.

T3Term 3 · Loops & Repetition Structures

What is a Loop?

A loop is a programming structure that repeats a block of code over and over until a certain point is reached. Instead of writing the same instruction many times, you write it once and tell the computer how often, or until when, to repeat it.

Everyday analogy: Think of doing push-ups. The coach does not shout "do a push-up" fifty separate times. He says "do fifty push-ups." That single instruction, repeated until you reach fifty, is a loop. The action (one push-up) is the loop body, and "fifty" is the condition that tells you when to stop.

Why Do We Use Loops?

Loops save us from repeating ourselves and let programs handle any amount of work with the same short piece of code.

The Three Loop Types in Plain Words

Choosing the right loop comes down to one question: do you know in advance how many times to repeat?

Types of Loops

LoopTypeUse when…
for … doUnconditional (fixed)You know exactly how many times
while … doConditional (pre-test)Repeat WHILE a condition is true — check first
repeat … untilConditional (post-test)Repeat UNTIL a condition is true — always runs at least once

FOR Loop (Fixed / Unconditional)

Runs a set number of times. The counter increments or decrements automatically.

We call it fixed or unconditional because the number of repeats is decided before the loop even starts and cannot change while it runs. You give it a start value and an end value, and Delphi handles the counting for you — you never have to add 1 to the counter yourself.

WHEN TO USE

Reach for a FOR loop whenever you can finish the sentence "do this exactly ___ times" with a number — printing 1 to 10, working through all 30 learners in a class, or drawing 12 rows of a table.

THE FOR LOOP Keyword — starts the loop Keyword — leads into the repeated code for i := 1 to 5 do Counter — created and incremented automatically Start value End value — loop stops once this is reached
Syntax — counting UP
for counter := lowest to highest do
begin
  // code repeated each iteration
end;
Delphi — print 1 to 5
for i := 1 to 5 do
begin
  memOut.Lines.Add(IntToStr(i));
end;

FOR … DOWNTO (counting down)

Delphi — countdown 5 to 1
for i := 5 downto 1 do
begin
  memOut.Lines.Add(IntToStr(i));
end;

FOR Loop — Running Total

Delphi — sum 1 to 10
var
  i, iTotal: Integer;
begin
  iTotal := 0;  // initialise!
  for i := 1 to 10 do
    iTotal := iTotal + i;
  lblTotal.Caption := 'Sum = ' + IntToStr(iTotal);
end;

FOR Loop — the Counter Can Be Any Ordinal Type

A FOR loop's counter does not have to be an Integer — it can be declared as any ordinal type, provided the start value, end value and the counter variable itself all agree on that type. A Char counter, for instance, steps through the alphabet one letter at a time instead of counting through numbers.

Delphi — listing the letters 'B' to 'F'
var
  cLetter: char;
begin
  for cLetter := 'B' to 'F' do
    memOut.Lines.Add(cLetter);
end;
Keep the case consistent

A start value in uppercase paired with an end value in lowercase (or the reverse) will not behave the way you expect — uppercase and lowercase letters occupy separate blocks in the ASCII table, so mixing them changes how far apart the two values actually are, and therefore how many times the loop runs. Pick one case and stick to it for both bounds.

WHILE … DO Loop (Pre-Conditional)

Checks the condition before each iteration. If the condition is false from the start, the loop body never runs.

We call it pre-conditional ("pre" = before) because it tests the condition first, and only then decides whether to run the body. This makes it the safe choice when there is a chance the loop should not run at all.

WHEN TO USE

Use WHILE when you do not know how many repeats you need and it might be zero — for example, "keep reading numbers while the user hasn't typed 0". If they type 0 immediately, you correctly do nothing.

Syntax
while condition do
begin
  // code
end;

The ITC-Principle

A handy checklist for building a correct WHILE loop is the ITC-principle — three things that must all be true of your code, in this order:

StepWhat to check
InitialiseHas every variable used in the WHILE condition already been given a starting value before the loop is reached?
TestIs that condition re-checked at the top of every pass, deciding whether the body runs again?
ChangeDoes something inside the body actually update the variable(s) being tested? Without this step the condition can never turn False.
Avoid Infinite Loops

The counter must be initialised before the loop and incremented inside the loop — otherwise it runs forever and crashes your program. Also never put a ; straight after the do keyword — while condition do; creates an empty loop body, so the statement that was meant to change the condition is skipped, and the loop runs forever.

Delphi — while counter ≤ 5
var
  Counter: Integer;
begin
  Counter := 1;           // initialise BEFORE loop
  while Counter <= 5 do
  begin
    memOut.Lines.Add('Counter: ' + IntToStr(Counter));
    Inc(Counter);          // increment INSIDE loop
  end;
end;

WHILE — Reading user input until sentinel

Delphi — keep adding until user enters 0
var
  iNum, iTotal: Integer;
begin
  iTotal := 0;
  iNum   := StrToInt(InputBox('Input', 'Enter number (0 to stop):', ''));
  while iNum <> 0 do
  begin
    iTotal := iTotal + iNum;
    iNum   := StrToInt(InputBox('Input', 'Enter number (0 to stop):', ''));
  end;
  lblTotal.Caption := 'Total: ' + IntToStr(iTotal);
end;

Letting the User Interrupt a Loop While It Runs

A different situation arises when nobody knows how many times a loop should run until the user physically clicks a [Stop] Button partway through — a reaction game or a live counter are typical examples. This needs a Boolean variable that both the button that starts the loop and the button that stops it can share, so it must be declared in the private section of the form (giving it class scope) rather than inside a single procedure.

Delphi — a running counter the user can interrupt
private
  bRunning : boolean;   // shared by both button handlers below

procedure TForm1.btnGoClick(Sender: TObject);
var
  iTick : byte;
begin
  bRunning := True;
  iTick    := 0;
  while bRunning do
  begin
    Inc(iTick);
    memLog.Lines.Add(IntToStr(iTick));
    Sleep(300);                    // short pause so the numbers are readable
    Application.ProcessMessages;   // give the form a chance to react to the click
  end;
end;

procedure TForm1.btnHaltClick(Sender: TObject);
begin
  bRunning := False;
end;
Why Application.ProcessMessages matters here

A Delphi form normally deals with one event at a time, finishing the current event handler completely before looking at the next. While btnGoClick is stuck inside its loop, a click on [Halt] just waits in a queue rather than running immediately. Application.ProcessMessages is a command that tells the program to pause for a moment and clear that queue — handling any waiting clicks — before the loop carries on. Leave it out, and the [Halt] click is never processed until the loop finishes on its own, which defeats the purpose of having a stop button at all.

REPEAT … UNTIL Loop (Post-Conditional)

Runs the body first, then checks the condition. Guaranteed to run at least once. Loop continues while condition is false; stops when it becomes true.

We call it post-conditional ("post" = after) because it does the work first and asks the question afterwards. That is the opposite of the WHILE loop, and it is exactly what you want when the action must happen at least one time no matter what.

WHEN TO USE

Use REPEAT…UNTIL when the body must run at least once — like showing a menu and asking the user to choose, or asking for a valid mark and re-asking until they get it right. You always ask once, then keep asking until the answer is acceptable.

Syntax
repeat
  // code
until condition;

REPEAT follows the same three checks as the WHILE loop's ITC-principle, only in a swapped order — Initialise, Change, then Test — since the body always fires once before the condition is ever looked at. Lining the two loops up side by side shows how they really are opposites of each other:

While loopRepeat loop
Suited to situations where it is fine for the loop to run zero times.Suited to situations where the body must run at least once.
Keeps looping while the condition stays True.Keeps looping until the condition finally becomes True.
Order of checks: ITC — Initialise, Test, Change.Order of checks: ICT — Initialise, Change, Test.
Prefer >= over = in a termination test

Testing for an exact match can trap you in an infinite loop if the value ever skips straight past the target — for example a running score that jumps from 46 to 52 will never satisfy until iScore = 50. Writing until iScore >= 50 instead guarantees the loop will stop even if the value overshoots.

Delphi — repeat until i = 10
var
  i: Integer;
begin
  i := 1;
  repeat
    memOut.Lines.Add(IntToStr(i));
    i := i + 1;
  until i > 10;
end;

REPEAT — Validate input

Delphi — keep asking until valid mark
var
  iMark: Integer;
begin
  repeat
    iMark := StrToInt(InputBox('Mark', 'Enter mark (0-100):', ''));
    if (iMark < 0) OR (iMark > 100) then
      ShowMessage('Invalid! Enter 0-100');
  until (iMark >= 0) AND (iMark <= 100);
end;

Worked Example — Count, Average & Highest

One loop can gather several answers at once. Here we read marks until the user enters -1, and while looping we keep a counter, a running total and the highest so far — then work out the average at the end.

Delphi — statistics from a loop
var
  iMark, iCount, iTotal, iHighest : Integer;
  rAverage : Real;
begin
  iCount   := 0;      // initialise all three trackers before the loop
  iTotal   := 0;
  iHighest := 0;

  iMark := StrToInt(InputBox('Marks', 'Enter a mark (-1 to stop):', ''));
  while iMark <> -1 do
  begin
    Inc(iCount);                 // how many so far
    iTotal := iTotal + iMark;    // running total
    if iMark > iHighest then    // track the maximum
      iHighest := iMark;
    iMark := StrToInt(InputBox('Marks', 'Enter a mark (-1 to stop):', ''));
  end;

  if iCount > 0 then            // guard against dividing by zero
  begin
    rAverage := iTotal / iCount;
    memOut.Lines.Add('Count:   ' + IntToStr(iCount));
    memOut.Lines.Add('Average: ' + FloatToStrF(rAverage, ffFixed, 4, 1));
    memOut.Lines.Add('Highest: ' + IntToStr(iHighest));
  end
  else
    ShowMessage('No marks were entered.');
end;
The pattern

Initialise your trackers before the loop, update them inside it (add to the total, compare for the highest), and report after it. Always check iCount > 0 before dividing, or an empty run will crash with a divide-by-zero.

Comparison: Which Loop to Use?

SituationBest Loop
Print numbers 1 to 100for
Read until user types "stop"while or repeat
Must run at least once (e.g. menu)repeat
Unknown number of iterationswhile or repeat
Process each element in an arrayfor

Loop Control — How a Loop Is Controlled

Beyond picking FOR, WHILE or REPEAT, it is useful to describe what decides when a loop stops. This splits loops into two broad groups: definite repetition, where the number of passes can be worked out ahead of time, and indefinite repetition, where it cannot.

Counter Controlled Loops (Definite Repetition)

A counter controlled loop relies on a variable that starts at a known value, changes by a predictable amount on every pass, and is compared to a fixed target to decide whether to continue.

Because that change is predictable, you can always calculate in advance exactly how many times a counter controlled loop will run — a FOR loop is the most obvious example, but a WHILE or REPEAT loop built around a simple counter is counter controlled too.

Delphi — counter controlled WHILE loop: 8 times table
iRow := 1;
while iRow <= 10 do
begin
  iResult := iRow * 8;
  memOut.Lines.Add(IntToStr(iRow) + ' x 8 = ' + IntToStr(iResult));
  iRow := iRow + 1;
end; {while}

Sentinel Controlled Loops (Indefinite Repetition)

A sentinel controlled loop watches for a special "stop" value — a sentinel — typed in by the user. That value is only ever compared, never used in a calculation, since its whole job is to signal "no more data."

The "WHILE — Reading user input until sentinel" example further up this page is a sentinel controlled loop: 0 is the signal that tells it to stop. Since nobody can predict how many real numbers the user will enter before typing that sentinel, the number of passes is unknown in advance — which is why sentinel controlled loops fall under indefinite repetition.

Result Controlled Loops (Indefinite Repetition)

A result controlled loop keeps going until a particular outcome has actually happened — it is not driven by a counter reaching a target or a user typing a sentinel, but by whatever condition the program is watching for finally becoming true.

Delphi — spin a wheel of 8 prizes until the jackpot slot comes up
iSpins := 0;
repeat
  iSlot := Random(8) + 1;
  Inc(iSpins);
until iSlot = 8;
ShowMessage('Jackpot landed after ' + IntToStr(iSpins) + ' spins');

Nothing here counts down towards a known number of repeats, and there is no value the user types to signal "stop" — the loop simply keeps spinning until the result it is watching for (slot 8) actually comes up.

Nested Loops

A nested loop is simply a loop placed inside the body of another loop. Each time the outer loop takes one step, the inner loop runs through its entire range from start to finish before the outer loop is allowed to take its next step. The inner and outer loops don't have to be the same kind — a FOR loop can quite happily sit inside a WHILE loop, or inside another FOR loop.

Suppose an exam venue needs a code for every seat: a block letter ('A' to 'C'), a row number (1 to 3) and a seat letter within the row ('a' to 'c'). Three nested FOR loops can generate the complete list in one go.

Delphi — three nested FOR loops listing every seat code
procedure TfrmVenue.btnListSeatsClick(Sender: TObject);
var
  iRow : integer;
  cBlock, cSeat : char;
  iSeatCount : integer;
  sSeatCode : string;
begin
  iSeatCount := 0;
  for cBlock := 'A' to 'C' do       // outer loop
  begin
    for iRow := 1 to 3 do          // middle loop
    begin
      for cSeat := 'a' to 'c' do       // inner loop
      begin
        sSeatCode := cBlock + IntToStr(iRow) + cSeat;
        Inc(iSeatCount);
        memSeats.Lines.Add(sSeatCode);
      end; // for cSeat
    end; // for iRow
  end; // for cBlock
  memSeats.Lines.Add('Total seats = ' + IntToStr(iSeatCount));
end;
Tracing the order the loops fire

Follow the innermost loop first: cSeat runs all the way through 'a', 'b', 'c' before iRow is even allowed to move on to its next value. Only once iRow has itself been through 1, 2 and 3 — meaning the middle loop has fully finished for the current block — does cBlock step forward to its next letter. The resulting list reads A1a, A1b, A1c, A2a, A2b, A2c, A3a, A3b, A3c, B1a, … and finishes at Total seats = 27, since 3 blocks × 3 rows × 3 seats gives 27 combinations in total.

Stopping Early — Break and Exit

Sometimes you need to stop part-way through, without waiting for a loop to finish naturally or a procedure to reach its last line. Delphi has two commands for this. They look similar, but they stop different amounts of the code, so learners often mix them up.

BreakExit
What it stopsStops the rest of the loop from processingStops any further processing in that procedure or function
Where the program carries onWith the first line after the loop — the rest of the procedure still runsIt doesn't — control goes straight back to whoever called the procedure
Where it can be usedOnly inside a loop (FOR, WHILE or REPEAT)Anywhere in a procedure or function, inside a loop or not

Break — leave the loop, keep going with the procedure

In this example the user enters up to five marks, but typing a negative number means "I'm done". Break ends the loop at that point, and the line that displays the total still runs because it comes after the loop.

Delphi — Break stops the loop only
procedure TForm1.btnTotalClick(Sender: TObject);
var
  i, iMark, iTotal : integer;
begin
  iTotal := 0;
  for i := 1 to 5 do
  begin
    iMark := StrToInt(InputBox('Input', 'Mark (negative to stop):', ''));
    if iMark < 0 then
      Break;                 // rest of the loop is skipped...
    iTotal := iTotal + iMark;
  end;
  lblTotal.Caption := 'Total: ' + IntToStr(iTotal);   // ...but this line still runs
end;

Exit — leave the whole procedure

Here a negative mark is treated as an error instead. Exit abandons the procedure on the spot, so the total is never displayed.

Delphi — Exit stops the whole procedure
procedure TForm1.btnTotalClick(Sender: TObject);
var
  i, iMark, iTotal : integer;
begin
  iTotal := 0;
  for i := 1 to 5 do
  begin
    iMark := StrToInt(InputBox('Input', 'Mark:', ''));
    if iMark < 0 then
    begin
      ShowMessage('Marks cannot be negative');
      Exit;                  // nothing else in this procedure runs
    end;
    iTotal := iTotal + iMark;
  end;
  lblTotal.Caption := 'Total: ' + IntToStr(iTotal);   // never reached after Exit
end;
Trap — Break vs Exit

Ask yourself: "Should the code after the loop still run?" If yes, use Break. If no — the whole procedure should stop — use Exit. Also remember that Break in a nested loop only stops the loop it is written in; the outer loop carries on.

Number Algorithms with Loops

Loops really show their strength when you combine them with MOD and DIV to investigate numbers. The algorithms below are the standard ones: each is written first as plain steps, then as Delphi code, then checked with a small trace. Use uses Math for Power in the later examples.

The idea behind most of them

a MOD b = 0 means b divides exactly into a, so b is a factor of a. Test every possible divisor with a loop and you can answer almost any question about factors.

Listing All the Factors of a Number

  1. Start with an empty text variable for the answers.
  2. For every divisor from 1 up to the number itself:
  3. If the number MOD the divisor is 0, add the divisor to the text.
Delphi — all factors of a number
var
  iNumber, iDivisor : Integer;
  sFactors : string;
begin
  iNumber  := StrToInt(edtNumber.Text);      // e.g. 36
  sFactors := '';
  for iDivisor := 1 to iNumber do
    if iNumber mod iDivisor = 0 then
      sFactors := sFactors + IntToStr(iDivisor) + ' ';
  lblOut.Caption := sFactors;                // 1 2 3 4 6 9 12 18 36
end;
iDivisor36 MOD iDivisorFactor?
10Yes — added
20Yes — added
30Yes — added
40Yes — added
51No
60Yes — added
71No
84No
90Yes — added

The table stops at 9 to save space, but the loop carries on all the way to 36. Notice that both 1 and the number itself are always factors.

Prime and Composite Numbers

A prime number is greater than 1 and has exactly two factors: 1 and itself. A composite number is greater than 1 and has more than two factors. The number 1 is neither, because it has only one factor.

So the algorithm is to count the factors with the same loop as above, then judge the count.

  1. Set the factor count to 0.
  2. For every divisor from 1 up to the number: if the number MOD the divisor is 0, add 1 to the count.
  3. If the number is greater than 1 and the count is exactly 2, it is prime.
  4. If the number is greater than 1 and the count is more than 2, it is composite.
Delphi — prime, composite or neither
var
  iNumber, iDivisor, iCount : Integer;
  bPrime, bComposite : Boolean;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 31
  iCount  := 0;                             // initialise BEFORE the loop
  for iDivisor := 1 to iNumber do
    if iNumber mod iDivisor = 0 then
      Inc(iCount);

  bPrime     := (iNumber > 1) and (iCount = 2);
  bComposite := (iNumber > 1) and (iCount > 2);

  if bPrime then
    lblOut.Caption := 'Prime'
  else if bComposite then
    lblOut.Caption := 'Composite'
  else
    lblOut.Caption := 'Neither prime nor composite';
end;
NumberFactors foundiCountResult
311, 312Prime
211, 3, 7, 214Composite
111Neither
Trap — the number 1

Do not shortcut the composite test to bComposite := NOT bPrime. That would call 1 (and 0) composite, when they are neither. Keep the iNumber > 1 check in both tests so the rules match the definitions exactly, and keep the brackets around each comparison.

Stopping early

Once the count reaches 3 the number can no longer be prime, so you could leave the loop with Break (see Stopping Early above) instead of testing every remaining divisor. The simple full loop is still the one to learn first.

Perfect Squares

A perfect square is a whole number multiplied by itself, such as 49 (7 × 7) or 81 (9 × 9). No loop is needed: take the square root, chop off the decimals with Trunc, square the result, and see whether you get the original number back. If the square root had decimals, the square of the chopped value cannot match. (Use a non-negative number, because Sqrt of a negative value is a runtime error.)

Delphi — perfect square check
var
  iNumber, iRoot : Integer;
  bSquare : Boolean;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 81
  iRoot   := Trunc(Sqrt(iNumber));           // Sqrt(81) = 9.0  -> 9
  bSquare := (iRoot * iRoot) = iNumber;      // 9 * 9 = 81 -> True
end;

With 50: Sqrt(50) is 7.07…, Trunc gives 7, and 7 × 7 = 49, which is not 50, so 50 is not a perfect square.

Perfect Numbers

A perfect number equals the sum of its proper factors — all its factors except the number itself. For 28 the proper factors are 1, 2, 4, 7 and 14, and 1 + 2 + 4 + 7 + 14 = 28, so 28 is perfect. For 12 they add up to 1 + 2 + 3 + 4 + 6 = 16, so it is not.

No proper factor can be bigger than half the number, so the loop only needs to run from 1 to iNumber DIV 2. That also keeps the number itself out of the sum.

Delphi — perfect number check
var
  iNumber, iDivisor, iSum : Integer;
  bPerfect : Boolean;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 28
  iSum    := 0;
  for iDivisor := 1 to iNumber div 2 do   // 1 to 14
    if iNumber mod iDivisor = 0 then
      iSum := iSum + iDivisor;
  bPerfect := iSum = iNumber;
end;
Trap — do not add the number itself

If the loop ran up to iNumber, the number would be added as its own factor and every number would fail the test (the sum would always be too big). Stopping at iNumber DIV 2 avoids that.

Factorial

The factorial of n, written n!, is every whole number from 1 up to n multiplied together. So 7! = 1 × 2 × 3 × 4 × 5 × 6 × 7 = 5 040. By definition 0! = 1.

  1. Set a running product to 1.
  2. For every counter value from 1 up to n, multiply the product by the counter.
Delphi — factorial with a FOR loop
var
  i, iNumber : Integer;
  iFactorial : Int64;
begin
  iNumber    := StrToInt(edtNumber.Text);    // e.g. 7
  iFactorial := 1;                          // start at 1, NOT 0
  for i := 1 to iNumber do
    iFactorial := iFactorial * i;
  lblOut.Caption := IntToStr(iFactorial);    // 5040
end;
iiFactorial after the pass
(before loop)1
11
22
36
424
5120
6720
75040
Why Int64?

Factorials grow very quickly: 13! is already 6 227 020 800, which is too big for an Integer. An Int64 variable can hold factorials up to 20!. If iNumber is 0 the loop does not run at all, so the answer stays at 1 — exactly right for 0!. The same calculation can also be written with recursion; see the Grade 12 Recursion page.

The Fibonacci Sequence

In the Fibonacci sequence each term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …. A loop keeps track of the previous and current terms, builds the next one, and then slides both along.

  1. Set previous to 0 and current to 1, and start with an empty text variable.
  2. Repeat for the number of terms wanted:
  3. Add the previous term to the text; then next := previous + current; previous := current; current := next.
Delphi — the first ten Fibonacci terms
var
  i, iTerms, iPrev, iCurr, iNext : Integer;
  sSeries : string;
begin
  iTerms  := 10;
  iPrev   := 0;
  iCurr   := 1;
  sSeries := '';
  for i := 1 to iTerms do
  begin
    sSeries := sSeries + IntToStr(iPrev) + ' ';
    iNext   := iPrev + iCurr;      // build the new term first
    iPrev   := iCurr;              // then slide both values along
    iCurr   := iNext;
  end;
  lblOut.Caption := sSeries;       // 0 1 1 2 3 5 8 13 21 34
end;
PassTerm added (iPrev)iNextiPrev afteriCurr after
10111
21212
31323
42535

Read pass 3 as an example: iPrev is 1 and iCurr is 2, so 1 is added to the text, iNext := 1 + 2 gives 3, and the slide makes iPrev = 2 and iCurr = 3.

Order matters when you slide

If you overwrite iPrev or iCurr before iNext has been worked out, an old value is lost for good. It is the same idea as swapping two variables with a temporary one: always save a value before you replace it.

Greatest Common Divisor (GCD) and Lowest Common Multiple (LCM)

The GCD of two numbers is the largest number that divides exactly into both. Euclid’s method finds it with remainders: divide the first number by the second and keep the remainder, then let the second number become the first and the remainder become the second. Repeat until the remainder is 0. The last non-zero divisor is the GCD. We don’t know in advance how many repeats are needed, so a while loop is the right choice.

Delphi — GCD by Euclid, then LCM
var
  iFirst, iSecond, iA, iB, iRemainder, iGCD, iLCM : Integer;
begin
  iFirst  := StrToInt(edtFirst.Text);        // e.g. 84
  iSecond := StrToInt(edtSecond.Text);       // e.g. 36

  iA := iFirst;                              // work on copies so the originals survive
  iB := iSecond;
  while iB <> 0 do
  begin
    iRemainder := iA mod iB;
    iA := iB;
    iB := iRemainder;
  end;
  iGCD := iA;                                // the last non-zero divisor

  iLCM := (iFirst div iGCD) * iSecond;
end;
PassiAiBiA MOD iB
1843612
236120
stop120— iB is 0, loop ends

So GCD(84, 36) = 12. The LCM is the smallest number that both numbers divide into exactly. It follows from the GCD: LCM = (first DIV GCD) × second, so (84 DIV 12) × 36 = 7 × 36 = 252. Check: 252 ÷ 84 = 3 and 252 ÷ 36 = 7, both exact.

Divide first, then multiply

Doing the DIV before the multiplication keeps the intermediate number small, which helps avoid overflow with large values, and because the GCD divides exactly into the first number the DIV loses nothing.

Converting Decimal to Binary, Octal or Hexadecimal

To write a decimal number in another base, repeatedly divide by that base. Each time, the remainder (MOD) is the next digit — working from the right-hand end of the answer — and the quotient (DIV) is what remains to be converted. Stop when the quotient reaches 0.

Two small tricks make the code short:

A repeat loop is used so that the number 0 still produces one digit ('0').

Delphi — decimal to base 2, 8 or 16
const
  sDigits = '0123456789ABCDEF';
var
  iNumber, iWork, iBase, iRemainder : Integer;
  sResult : string;
begin
  iNumber := StrToInt(edtNumber.Text);       // e.g. 77
  iBase   := 2;                             // change to 8 for octal or 16 for hexadecimal
  iWork   := iNumber;                        // the loop destroys iWork, so keep iNumber
  sResult := '';
  repeat
    iRemainder := iWork mod iBase;
    sResult    := sDigits[iRemainder + 1] + sResult;   // new digit goes in FRONT
    iWork      := iWork div iBase;
  until iWork = 0;
  lblOut.Caption := sResult;
end;

Tracing 77 in base 2:

PassiWork beforeiWork MOD 2sResult afteriWork after (DIV 2)
1771'1'38
2380'01'19
3191'101'9
491'1101'4
540'01101'2
620'001101'1
711'1001101'0 — stop

So 77 is 1001101 in binary. With iBase := 8 the same loop gives 115 (77 = 1 × 64 + 1 × 8 + 5), and with iBase := 16 it gives 4D, because the remainder 13 picks the letter D from the lookup string.

Converting Binary or Octal to Decimal

Going the other way, every digit has a place value of base ^ exponent. Work from the right: the last digit has exponent 0, the next one exponent 1, and so on. Multiply each digit by its place value and add everything up. The Power function (from the Math unit) does the raising to a power.

Delphi — binary or octal text to decimal
var
  sText : string;
  i, iDigit, iExp, iBase : Integer;
  rDecimal : Real;
begin
  sText    := edtValue.Text;                 // e.g. '110101'
  iBase    := 2;                            // use 8 for octal text such as '247'
  rDecimal := 0;
  iExp     := 0;
  for i := Length(sText) downto 1 do      // right to left
  begin
    iDigit   := StrToInt(sText[i]);
    rDecimal := rDecimal + iDigit * Power(iBase, iExp);
    Inc(iExp);
  end;
  lblOut.Caption := FloatToStrF(rDecimal, ffFixed, 8, 0);   // 53
end;

Tracing 110101 in base 2, from the right:

DigitiExpPower(2, iExp)Digit × place valueRunning total
10111
01201
12445
03805
14161621
15323253

So 110101 in binary is 53. Setting iBase := 8 and entering 247 gives 2 × 64 + 4 × 8 + 7 = 167.

An alternative way to get the digit

Instead of StrToInt(sText[i]) you can write Ord(sText[i]) - Ord('0'). The characters '0' to '9' are stored one after the other in the ASCII table, so subtracting the code for '0' leaves the digit’s own value.

Converting Hexadecimal to Decimal

Hexadecimal works exactly the same way, with base 16 — but some of its digits are letters. A to F stand for 10 to 15, and StrToInt cannot read letters, so each character must first be turned into its value. A case statement does this neatly: digits '0' to '9' go through StrToInt, and each letter is listed with its value.

Delphi — hexadecimal to decimal using CASE
var
  sHex : string;
  rDecimal : Real;
  iPos, iValue, iExp : Integer;
  cChar : Char;
begin
  sHex     := InputBox('Hexadecimal', 'Enter a hex value:', '1C5');
  rDecimal := 0;
  iExp     := 0;
  for iPos := Length(sHex) downto 1 do
  begin
    cChar := UpCase(sHex[iPos]);             // accept 'c' as well as 'C'
    case cChar of
      '0'..'9' : iValue := StrToInt(cChar);
      'A' : iValue := 10;
      'B' : iValue := 11;
      'C' : iValue := 12;
      'D' : iValue := 13;
      'E' : iValue := 14;
      'F' : iValue := 15;
    end;
    rDecimal := rDecimal + iValue * Power(16, iExp);
    Inc(iExp);
  end;
  ShowMessage(FloatToStrF(rDecimal, ffFixed, 8, 0));   // 453
end;

For 1C5: the 5 has exponent 0 (5 × 1 = 5), the C is 12 with exponent 1 (12 × 16 = 192), and the 1 has exponent 2 (1 × 256 = 256). Total: 5 + 192 + 256 = 453.

Alternative — letting Ord do the work

Instead of listing six letters, use the fact that 'A' to 'F' are consecutive in the ASCII table. The distance of a letter from 'A' is Ord(c) - Ord('A'), and since A is worth 10 you simply add 10. For 'C' that is 67 − 65 + 10 = 12.

Delphi — the same conversion using Ord with grouped CASE ranges
for iPos := Length(sHex) downto 1 do
begin
  case UpCase(sHex[iPos]) of
    '0'..'9' : iValue := Ord(sHex[iPos]) - Ord('0');
    'A'..'F' : iValue := Ord(UpCase(sHex[iPos])) - Ord('A') + 10;
  end;
  rDecimal := rDecimal + iValue * Power(16, iExp);
  Inc(iExp);
end;
Trap — the right-to-left order

The exponent must start at 0 on the last character. If you loop from the front (for iPos := 1 to Length(sHex)) with the exponent starting at 0, every digit gets the wrong place value. Either loop with downto, as above, or start the exponent at Length(sHex) - 1 and count down.

Which Loop for Which Algorithm?

AlgorithmLoop usedWhy
Factors, prime test, perfect number, factorial, FibonacciforThe number of repeats is known: 1 to n, or a chosen number of terms.
GCD (Euclid)whileNobody knows how many remainders are needed; it might even be zero if the second number is 0.
Decimal to another baserepeatUnknown number of divisions, but at least one digit must be produced, even for 0.
Binary, octal or hexadecimal to decimalfor … downtoOne pass per character, from the last one to the first.

You know exactly how many times to repeat. Which loop is best?

A FOR loop is for a known, fixed number of repeats.

Which loop always runs its body at least once?

REPEAT…UNTIL checks the condition at the end, so the body always runs at least once.

A WHILE loop checks its condition:

WHILE is a pre-conditional loop - it tests first, so it may run zero times.