The While Command

while.png

Command Summary

Repeats a block of code as long as a condition is met

Command Syntax

:While condition
(block of code)
:EndWhile

Menu Location

Starting in the program editor:

  • Press F2 to enter the Control menu.
  • Press 5 to paste While..EndWhile.

Calculator Compatibility

This command works on all calculators.

Token Size

2 bytes for While;
4 bytes for EndWhile.

A While..EndWhile block is used to repeat a block of code as long as some true-or-false condition is met. This condition is checked before entering the loop (if it's false to begin with, the loop is skipped), and checked again every time the loop ends. For example:

:1→x
:While x<5
: x+1→x
: Disp x
:EndWhile
           1
           2
           3
           4

The condition is not checked anywhere in the middle of the loop. If the condition becomes temporarily false, but then becomes true again before the end, the loop keeps going.

What kind of conditions are possible? Any command that returns a logical value — true or false — is acceptable. This includes the results of:

  • Relational operators: =, , >, , <, and
  • Logical operators: and, or, xor, not
  • Any advanced test command: pxlTest(), isPrime(), and others.
  • A variable that contains one of the values true or false, or a function that returns them.

Of course, these can also be combined: for example, isPrime(x) and x≠2 is a valid condition.

One common use of a While loop is to wait for a key to be pressed:

:0→key
:While key=0
: getKey()→key
:EndWhile

Optimization

In most programming languages a loop that always keeps repeating would be created using a While loop with a condition that's always true. You can do this in TI-Basic too, but it's simpler to use Loop..EndLoop which does the same thing.

:While true
: © do something
:EndWhile

can be

:Loop
: © do something
:EndLoop

Error Conditions

20 - A test did not resolve to TRUE or FALSE happens when the condition is indeterminate, or the wrong data type.

730 - Missing start or end of block syntax happens when a While is missing an EndWhile, or vice versa.

Related Commands

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Noncommercial 2.5 License.