While-expression

One important thing about computers is that they don't get bored. Tell them to do a calculation 10 times and they just do it. Tell them to do the same calculation 100 times and you guessed - they just do it. How? With a programming technique called a loop around Blocks of code.

How do we loop in Haxe? There are several ways: one way uses the keyword while. Go to http://haxe.org/ref/syntax under While. Its syntax is:
while( expr-cond ) expr-loop;

Lets be an astronaut. We have to launch our rocket. Here's the program to do it!

class Whileloop
{
  public static function main()
  {
    var i = 5;
    while( i > 0 )
    {
      neko.Lib.println( i );
      i--;
    }
    neko.Lib.println( "Blast - off!" );
 }
 
}

The output of the program is:
5
4
3
2
1
Blast - off!

What Happened?

  1. The variable i is assigned the value 5 in line 3. It is common programming practice to use the letters i, j and k for loop variable names if the variable is not used for any other purpose.
  2. i > 0 evaluates to true because we set i to 5 in the line above, so execution branches to expr-loop. We use the Neko API to print the value of i on screen followed by a newline character.
  3. The value of i is decremented by 1.
  4. We have reached the end of expr-loop. Execution returns to expr-cond and it is evaluated again. While it is true, the expr-loop is repeated.
  5. When i is 0, expr-cond is not true (i.e. false), so execution continues at line 7 and the final message is printed on screen.

More Facts About While-Loops

Notice that expr-cond is evaluated at the beginning of the while-loop. If expr-cond is false on the first evaluation, the loop is never executed.

We know how many times this while-loop will be executed because we have:
  • set an initial value used in expr-cond before we enter the loop, and
  • changed the value inside the loop.
There are times when we need the loop to repeat an unknown or variable number of times, especially when we input data to a program. We can make expr-cond look for a sentinel value, e.g. -1 would not be a data value, but it would tell the program we have no more data to input.

while( user_data != -1 )
{
  // print prompt, get data, store in array
};

There are times when we need a loop to repeat forever by creating an expr-cond which is always true, like while( 1 == 1). We can exit this loop as needed by creating an if-expression inside the loop somewhere and use the break keyword. Be careful not to write an infinite loop from which the program has no way to exit.

Go to http://haxe.org/ref/syntax and look at the explanation under the Break and Continue heading.

Haxe API Documentation

The Haxe API documentation is saved on your local computer as web pages when you install Haxe and Neko. On Windows, it is in C:\Motion-Twin\Haxe\doc so you can see where neko.Lib.println() is described.

Do - While expression

Remember you read before that there are several ways to loop in Haxe. Another way is using the do-while loop.

Go to http://haxe.org/ref/syntax under While. Its syntax is:
do expr-loop while(expr-cond );

Lets get the user to type some lines of text into the program and then print what they typed to the screen.

class Doloop
{
 
  public static function main()
  {
    var i = 1;
    do
    {
      var str = Sys.stdin().readLine();
      Sys.println( "You typed " + str );
      i++;
    } while( i < 5 );
    neko.Lib.println( "Finished." );
 }
 
}

A sample output of the program is:
aaa
You typed aaa
123
You typed 123
the string
You typed the string
6 green apples
You typed 6 green apples
Finished.

What Happened?

  1. The variable i is assigned the value of 1 in line 3.
  2. Execution enters the expr-loop. Some data is typed by the user and assigned to the str variable. Go to http://haxe.org/doc/start/neko to look at Reading User Input.
  3. The contents of str are added after "You typed " and this is printed. Notice the space at the end of the "You typed " string. Note that Sys.println() is equivalent to neko.Lib.println().
  4. The value of the variable i is incremented by 1.
  5. We have reached the end of expr-loop, so expr-cond is evaluated. If it is true, execution loops to the beginning of the loop and the commands in expr-loop are executed again.
  6. When i is 5, expr-cond is not true (false), so execution continues at line 9 and the "Finished" message is printed on screen.

How come the user can only type in 4 strings, and not 5? The value of i is:
1
initialised in line 3
the loop is entered
2
incremented in line 7 on the 1st time through the loop - str is printed
3
incremented in line 7 on the 2nd time through the loop - str is printed
4
incremented in line 7 on the 3rd time through the loop - str is printed
5
incremented in line 7 on the 4th time through the loop - str is printed
the loop ends

Go to the Operators page on this wiki and look under Comparison Operators for a fix. This is known in computing as the "Off-by-one bug" and it is something to watch out for. If you really wanted 5 strings input and printed, change expr-cond to ( i <= 5 ).

Note that a do-while loop is always executed at least once because expr-cond is tested at the end of the loop. There must be a way for expr-cond to become false during the program; otherwise execution will stay in this loop.

Whether you use while or do-while depends on what the loop itself does.

To Do

Now is the time to try writing a little game. You will need your knowledge of the if-expression and loops. You will need to know how to generate random integer numbers, go to Std.random() in the Haxe API documentation.

High - Low Game

In the High-Low game, the computer "thinks" of a number between 1 and 100. The user tries to guess this number. For each guess, the computer provides feedback like Your guess was too high or Your guess was too low. The best feedback the user receives is You have guessed my number. Game over!

Pseudocode

When planning a program, it is useful to work out on paper (or in a text editor) what steps are needed. You can use phrases to describe the order of execution (i.e. pseudocode):
print name_of_program
print instructions_for_user
initialise variable comp_number // computer's random number
while( user_guess != comp_number )
 print prompt "What is your guess? "
 get variable user_guess // user's guess
 if( user_guess > comp_number )
 print "Your guess was too high";
 if( user_guess < comp_number )
 print "Your guess was too low";
print "You guessed my number. Game over!"

Game Extensions

You might like to try to:
  • add a score for the number of guesses,
  • ask the user if they would like to play again after the computer number is guessed,
  • keep a list of player names and high scores on disk,
  • change the target to Flash or another target with a GUI,
  • change the background colour to match how close the guess is, like Blue where the guess is a long way from close, changing to Red and the guess gets closer and Green when the guess is correct.

Where To From Here?

There is yet another way to loop in a program. How to do this is coming up next.