Loops - For and While

Learning Objectives:

Example For Loop

We have been using a for loop to repeat the body of a loop a known number of times. The body of a loop is all the statements that follow the for statement and are indented to the right of it. Be sure to indent 4 spaces to indicate the statements that are part of the body of the loop.

Before you step through the code in for_counter below, try to predict the last value it will print and then answer the question below.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

If we want to print out a count that starts at 1 and increases by 1 each time, we can do easily do that with a for loop. Use the Forward button to see how counter takes on a new value each time through the loop.

Activity: CodeLens 2 (for_counter2)

Introducing the While Loop

Another way to repeat statements is the while loop. It will repeat the body of loop as long as a logical expression is true. The body of the loop is the statement or statements that are indented 4 or more spaces to the right of the while statement. A logical expression is one that is either true or false like x > 3.

While loops are typically used when you don’t know how many times to execute the loop. For example, when you play a game you will repeat the game while there isn’t a winner. If you ever played musical chairs you walked around the circle of chairs while the music was playing.

The code below will loop as long as the number that you enter isn’t negative. It will add each non negative number to the current sum. It will print out the sum and average of all of the numbers you have entered.

You have attempted 1 of 6 activities on this page