"While" loop

Another important power of computer programs is to be able to repeat some dull work multiple times. For example, bank has million clients who deposited money, and by the end of every month we need to increase their deposits by small percent ("interest rate"). That would be very annoying work for human!

For start, let us make a loop which changes value of some variable several times, say, assigning it values from 1 to 10. Here is how it looks like:

x = 1                 -- variable initialization
while x < 11 do       -- "head" and condition of a loop
  print(x)            -- "body" of a loop - doing some useful work here
  x = x + 1           -- increment variable
end                   -- close the "body"
print('done')         -- some code after the loop

Note that we use comments in the program source - everything starting with double dash (--) till the end of line is ignored when executing.

So let's look into details. We decided to call "working" variable x. We need to set it to starting value first, that's happening in the first line (outside of the loop actually).

The loop itself has a form

while {some condition} do
  {some actions}
end

Such syntax makes it easy both for human and for computer to understand:

  1. We need to check "some condition" written between while and do
  2. If it is correct, we do "some actions"
  3. And then go to beginning (see 1 again)

Condition is in form x < 11 - it is a "logical" operation. We'll learn later about other operations usable here. For now it reads simply x is less than 11.

Since the first value of the variable is 1, condition holds, and we enter the "body". It starts with printing the variable (nothing new for us). The next line is curious:

x = x + 1

It may drive mathematician crazy, but it is not the equation! It is assignment, not equality. So we x + 1 is calculated (result is 2 of course) and written again into x variable.

Loop ends with end keyword and we return to checking x < 11 again. Obviously it will be true again and so execution continues for few more "iterations". At last, when it is executed for x = 10, incrementing it in the last line of the body bring value to 11 and condition stops being correct. Loop won't execute anymore and execution passes further, beyond the end (in our case program prints done and ends there).

Hopefully this all is not very confusing. Copy-paste the code into program area, try running it. Feel free to re-read the explanations above.

For exercise please modify the program so that it prints "squares" of all values of x starting from 1 to some N (it will be given to you, set it as a constant in your program). E.g. if asked to print squares of numbers up to 3 Your program should print:

1
4
9

Our general problems also have a couple of good exercises for now: Sums in Loop and Sum in Loop - try them in this order and, hopefully, they'll make you think for a couple of minutes, but won't be very difficult!


Print squares of values up to