7.2. Repeating with Numbers

We are going to use a for loop. A for loop is one type of loop or way to repeat a statement or set of statements in a program. A for loop will use a variable and make the variable take on each of the values in a list of numbers one at a time. A list holds values in an order.

Notice that line 3 in the program below ends with a : and that line 4 is indented four spaces so that it starts under the n in number. Indented means that text on the line has spaces at the beginning of the line so that the text doesn’t start right at the left boundary. Both the : and the indention are required in a loop. Line 3 is the start of the for loop and line 4 is the body of the loop. The body of the loop is repeated for each value in the list thingsToAdd.

What is the sum of all the numbers between 1 and 10? Run the program below to calculate the answer.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted 1 of 4 activities on this page