8.1. Loops - For and While

Learning Objectives:

8.1.1. 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.

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 8.1.1.2 (for_counter)

8.1.2. 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.

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page