DMarlon Studio

Lesson 9 · 9 of 20

while and repeat…until · Pascal

Repeat code in Pascal while a condition holds: while checks it before each pass and repeat…until checks it at the end.

Pascal · while and repeat…until in DMarlon Studio: the example's code and its output in the terminal

`while` condition `do` repeats its statement as long as the condition is true, checking it before every pass. The piggy bank adds 15 euros a week while it holds less than 100: after 7 weeks it has 105 and the loop stops.

As with if, when the loop has to do several things they go between begin and end. Something inside must change the condition (here, savings); otherwise the loop would never end.

`repeat ... until` condition checks at the end, so it always runs at least once, and it stops when the condition is true (the opposite of while). The ball bounces back to half its height each time until it drops below 1 metre. Several statements fit between repeat and until without begin or end.

`Inc(bounces)` adds 1 to the variable, just like bounces := bounces + 1; `Dec` subtracts. The last while never runs at all, because savings < 50 is already false at the start.

Code · main.pas

program main;var  savings, weeks, bounces: Integer;  height: Double;begin  // while checks the condition before each turn.  savings := 0;  weeks := 0;  while savings < 100 do  begin    savings := savings + 15;    weeks := weeks + 1;  end;  WriteLn('After ', weeks, ' weeks: ', savings, ' euros saved');  // repeat runs at least once and stops when until is true.  height := 8.0;  bounces := 0;  repeat    height := height / 2;    Inc(bounces);  // the same as bounces := bounces + 1    WriteLn('Bounce ', bounces, ': ', height:0:2, ' m');  until height < 1;  // A while loop whose condition is false never runs.  while savings < 50 do    WriteLn('This line never appears.');  WriteLn('Done.');end.

Output · fpc main.pas && ./main

After 7 weeks: 105 euros saved
Bounce 1: 4.00 m
Bounce 2: 2.00 m
Bounce 3: 1.00 m
Bounce 4: 0.50 m
Done.

Key points

  • while checks the condition before each pass.
  • repeat ... until always runs at least once.
  • until stops when its condition is true.
  • Inc(x) and Dec(x) add and subtract 1.

Exercise

Work out how many years it takes 1000 euros to double in an account paying 5 % a year: with a while, multiply the balance by 1.05 each year until it reaches 2000.