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.
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.
- Less code – printing the numbers 1 to 100 takes three lines with a loop instead of one hundred lines without one.
- Fewer mistakes – you write the instruction once, so there is only one place where a typo could hide.
- Flexibility – the same loop can run 5 times or 5 000 times just by changing one number, so your program copes with any size of data.
- Processing collections – loops let you visit every item in a list, every learner in a class, or every character in a string, one at a time.
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?
- FOR – use it when you know the exact number of repeats. Analogy: climbing a staircase with a known number of steps — you count "step 1, step 2…" up to the top.
- WHILE – use it when you do not know how many times, and you must check first before doing anything. Analogy: filling a glass of water — you keep checking "is it full yet?" before each pour, and if the glass was already full you never pour at all.
- REPEAT…UNTIL – use it when you do not know how many times, but you must do the action at least once and check afterwards. Analogy: asking someone for their PIN — you always ask once, then check if it was right, and ask again only if it was wrong.
Types of Loops
| Loop | Type | Use when… |
|---|---|---|
for … do | Unconditional (fixed) | You know exactly how many times |
while … do | Conditional (pre-test) | Repeat WHILE a condition is true — check first |
repeat … until | Conditional (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.
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.
for counter := lowest to highest do
begin
// code repeated each iteration
end;for i := 1 to 5 do
begin
memOut.Lines.Add(IntToStr(i));
end;FOR … DOWNTO (counting down)
for i := 5 downto 1 do
begin
memOut.Lines.Add(IntToStr(i));
end;FOR Loop — Running Total
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.
var
cLetter: char;
begin
for cLetter := 'B' to 'F' do
memOut.Lines.Add(cLetter);
end;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.
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.
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:
| Step | What to check |
|---|---|
| Initialise | Has every variable used in the WHILE condition already been given a starting value before the loop is reached? |
| Test | Is that condition re-checked at the top of every pass, deciding whether the body runs again? |
| Change | Does something inside the body actually update the variable(s) being tested? Without this step the condition can never turn False. |
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.
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
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.
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;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.
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.
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 loop | Repeat 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. |
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.
var
i: Integer;
begin
i := 1;
repeat
memOut.Lines.Add(IntToStr(i));
i := i + 1;
until i > 10;
end;REPEAT — Validate input
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.
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;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?
| Situation | Best Loop |
|---|---|
| Print numbers 1 to 100 | for |
| Read until user types "stop" | while or repeat |
| Must run at least once (e.g. menu) | repeat |
| Unknown number of iterations | while or repeat |
| Process each element in an array | for |
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.
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.
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.
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;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.
Break | Exit | |
|---|---|---|
| What it stops | Stops the rest of the loop from processing | Stops any further processing in that procedure or function |
| Where the program carries on | With the first line after the loop — the rest of the procedure still runs | It doesn't — control goes straight back to whoever called the procedure |
| Where it can be used | Only 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.
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.
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;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.
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
- Start with an empty text variable for the answers.
- For every divisor from 1 up to the number itself:
- If the number MOD the divisor is 0, add the divisor to the text.
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;| iDivisor | 36 MOD iDivisor | Factor? |
|---|---|---|
| 1 | 0 | Yes — added |
| 2 | 0 | Yes — added |
| 3 | 0 | Yes — added |
| 4 | 0 | Yes — added |
| 5 | 1 | No |
| 6 | 0 | Yes — added |
| 7 | 1 | No |
| 8 | 4 | No |
| 9 | 0 | Yes — 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.
- Set the factor count to 0.
- For every divisor from 1 up to the number: if the number MOD the divisor is 0, add 1 to the count.
- If the number is greater than 1 and the count is exactly 2, it is prime.
- If the number is greater than 1 and the count is more than 2, it is composite.
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;| Number | Factors found | iCount | Result |
|---|---|---|---|
| 31 | 1, 31 | 2 | Prime |
| 21 | 1, 3, 7, 21 | 4 | Composite |
| 1 | 1 | 1 | Neither |
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.
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.)
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.
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;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.
- Set a running product to 1.
- For every counter value from 1 up to n, multiply the product by the counter.
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;| i | iFactorial after the pass |
|---|---|
| (before loop) | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
| 6 | 720 |
| 7 | 5040 |
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.
- Set previous to 0 and current to 1, and start with an empty text variable.
- Repeat for the number of terms wanted:
- Add the previous term to the text; then next := previous + current; previous := current; current := next.
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;| Pass | Term added (iPrev) | iNext | iPrev after | iCurr after |
|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 1 |
| 2 | 1 | 2 | 1 | 2 |
| 3 | 1 | 3 | 2 | 3 |
| 4 | 2 | 5 | 3 | 5 |
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.
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.
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;| Pass | iA | iB | iA MOD iB |
|---|---|---|---|
| 1 | 84 | 36 | 12 |
| 2 | 36 | 12 | 0 |
| stop | 12 | 0 | — 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.
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 constant string
'0123456789ABCDEF'acts as a digit lookup. A remainder of 0 to 15 picks the matching character. Because strings start at position 1, the digit for remainderrissDigits[r + 1], which also turns 10 to 15 into A to F automatically. - Each new digit is the next one to the left, so it is added to the front of the result (
digit + sResult), not to the back.
A repeat loop is used so that the number 0 still produces one digit ('0').
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:
| Pass | iWork before | iWork MOD 2 | sResult after | iWork after (DIV 2) |
|---|---|---|---|---|
| 1 | 77 | 1 | '1' | 38 |
| 2 | 38 | 0 | '01' | 19 |
| 3 | 19 | 1 | '101' | 9 |
| 4 | 9 | 1 | '1101' | 4 |
| 5 | 4 | 0 | '01101' | 2 |
| 6 | 2 | 0 | '001101' | 1 |
| 7 | 1 | 1 | '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.
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:
| Digit | iExp | Power(2, iExp) | Digit × place value | Running total |
|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 1 |
| 0 | 1 | 2 | 0 | 1 |
| 1 | 2 | 4 | 4 | 5 |
| 0 | 3 | 8 | 0 | 5 |
| 1 | 4 | 16 | 16 | 21 |
| 1 | 5 | 32 | 32 | 53 |
So 110101 in binary is 53. Setting iBase := 8 and entering 247 gives 2 × 64 + 4 × 8 + 7 = 167.
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.
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.
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;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?
| Algorithm | Loop used | Why |
|---|---|---|
| Factors, prime test, perfect number, factorial, Fibonacci | for | The number of repeats is known: 1 to n, or a chosen number of terms. |
| GCD (Euclid) | while | Nobody knows how many remainders are needed; it might even be zero if the second number is 0. |
| Decimal to another base | repeat | Unknown number of divisions, but at least one digit must be produced, even for 0. |
| Binary, octal or hexadecimal to decimal | for … downto | One 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.