Lesson goal: The while-loop: introduction

Previous: Patterns in Pi ($\pi$) (more) | Home | Next: Type some words

By this time, you hopefully understand a few things. The first is the for-loop and the second is the ability to ask the computer true/false questions. Lastly, with the if-statement you were able to make the computer react to the result of a true/false question.

Like the for-loop, the while-loop can cause the computer to execute a chunk of code over and over again. But unlike the for-loop, which is primarily used for counting, the while-loop can loop over and over again without doing any counting at all! In fact, a while-loop will run a chunk of code over and over again, until a true/false condition you give it becomes false. It is a very useful looping structure.

Let's start with a simple example that mimics the for-loop, and does a bit of counting.

while condition do
BODY

end
Move the mouse over a dotted box for more information.

Now you try. Put a condition in the while ... do line to have the computer count from 1 to 10.

Type your code here:


See your results here:

This code will not run! What condition will you put in the while loop to cause it to count in the variable a from $1$ to $10$? In other words, you want to keep the while loop going as long as a is less than or equal to 10. Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.