## Lesson 11: Repetition & For Loops

Due by the beginning of class on Wednesday, Feb. 17

Repetition is key to the solution of many problems. While it is possible to simulate the rolling of dice 5 times using 5 different function calls, this naive approach breaks down when the number of rolls increases to 10, 100, 1000... Similarly, you could draw multiple figures on the turtle graphics screen by repeatedly executing the code for drawing a single random figure, but this becomes a tedious task when the desired number of figures is large. What is needed in these and many similar problems is the ability to repeat a sequence of statements (rolling dice, drawing a random figure, ...) some specified number of times.

In this lesson, you will consider problems like these that involve unconditional repetition. The term unconditional refers to the fact that the number of repetitions is known ahead of time, as opposed to being dependent on some external condition. In JavaScript, a for loop is a control statement which provides for unconditional repetition.

### For Loops (1st Pass)

Consider a repetitive task such as rolling a pair of dice 10 times and displaying each total. To do this requires 10 copies of the code which simulates the dice rolls and displays their total. Fortunately, you have abstracted the task of rolling two dice into a function called diceRoll (which further makes use of the abstraction randomInt). Unfortunately, this is not all that much help. You still need to call that function 10 times and print the value returned each time.

document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); document.write( diceRoll(6) + "<BR>" ); JavaScript provides a better way for solving such repetitive tasks. A for loop is a control statement which executes some number of statements over and over. For example, the following for loop performs the same dice simulation, calling diceRoll 10 times and displaying each result. for (i = 1; i <= 10; i++) { document.write( diceRoll(6) + "<BR>" ); } This first line of the for loop specifies how many times the code inside the curly-braces is to be executed. In this example, the code will be executed 10 times, since the number 10 appears in the inequality i <= 10. For now, it is not important that you understand all of the details of this line. Just know that by changing the number 10, you can change the number of times the code inside the loop is executed. For example, changing the 10 to a 100 would cause the loop code to be executed 100 times, displaying the result of 100 dice rolls.

Using a for loop, you can repeat any sequence of statements as many times as you wish. Simply enclose the statements in a for loop (i.e., inside the curly-braces) and specify the number of repetitions in the first line. The general form for a simple for loop is the following:

for (LOOP_VARIABLE = 1; LOOP_VARIABLE <= NUMBER_OF_REPS; LOOP_VARIABLE++) { STATEMENTS_TO_BE_REPEATED } Any variable can be used as the loop variable. A common convention is to use the variable names i, j, and k when no more meaningful names are apparent.

When reading and writing loops, presentation style is very important. Indenting the statements that are inside the for loop makes it very clear where the loop begins and ends (since the beginning of the loop and the closing curly-brace line up). This will become even more important when loops become more complex, possibly containing other loops or control statements. So, get in the habit now of properly indenting your loops.

Exercise 1:     Verify that the above for loop does display 10 random dice rolls by cut-and-pasting it into the JavaScript interpreter and executing it. Note that you must include the random.js library file, and also cut-and-paste your diceRoll function into the interpreter window in order to make this function accessible. Once you have this code working, change the 10 in the first line to a 5. What affect does this have?

Exercise 2:     Write a simple for loop which prints out your name 10 times, each on a separate line. Once you have this working, modify the code so that it prints out your name some random number of times. That is, use the randomInt function from random.js to generate a random integer in some range (say 1 to 10), and then use that number to specify the number of repetitions. Report this final version of the code.

Exercise 3:     What happens if you specify 0 or a negative number as the number of repetitions in a for loop? Does this cause an error? Is the code inside the for loop executed at all? Determine the answer to this question and explain how you verified it.

### Repetition and Graphics

One particular application that calls for repetition is graphics. In previous lessons, you simulated repetition by re-executing code. For example, in Lesson 6 you drew multiple random lines by repeatedly executing the code which drew a single line. With the introduction of for loops, it is now possible to specify the repetition in the code itself. In this example, enclosing the line drawing code inside a for loop will enable the code to draw multiple lines in a single execution.

Exercise 4:     Rewrite your random lines code using a for loop. That is, enclose the code for drawing a single random line inside a for loop. Recall that to draw a random line, you first must pick a random pair of coordinates (using randomInt) and then call the moveTo function to move there. Test your code on a small number of repetitions, say 3, so that you can visually check to make sure that it draws exactly 3 lines. Once you have verified this, change the number of repetitions to 100.

Exercise 5:     In Lesson 6, you also wrote code which displayed your name at random coordinates on the screen. Similar to the previous exercise, enclose your name drawing code in a for loop so that multiple names are drawn by a single execution. Again, test your code first on a small number of repetitions, then increase the number to make the output more interesting.

Exercise 6:     A square is a 4-sided regular polygon, with 90 degree angles between each of its sides. As you noted in Lesson 6, a square can be drawn by repeatedly drawing a side and then turning 90 degrees. This sequence of steps can be encapsulated in a function (as you saw in Lab 3): function drawSquare(sideLength) // Given :sideLength > 0 // Results: draws a square with side of length sideLength { turnTo(90); forward(sideLength); left(90); forward(sideLength); left(90); forward(sideLength); left(90); forward(sideLength); left(90); } As you can see, the code for drawing a square is highly repetitive. It contains the same line of function calls, repeated four times. Modify the function definition so that it has only one instance of this line, enclosed in a for loop that executes it four times. Test your modified function to make sure that it behaves the same as the original.

Note: As is the case with all variables in a function (excluding parameters), the loop variable for a for loop should be declared as a local variable.

Exercise 7:     A triangle is a 3-sided regular polygon, while a pentagon is a 5-sided regular pentagon. Similar to the code for drawing a square, you can draw each of these figures by repeatedly drawing a side and then turning the appropriate number of degrees. In the case of a triangle, you must repeat the drawing and turning steps three times, while a pentagon requires five repetitions. Define functions drawTriangle and drawPentagon which use for loops to draw these polygons. As with drawSquare, these functions should have a single parameter, representing the length of the sides.

Note: drawing any regular polygon should result in the turtle making a complete revolution. Thus, the heading of the turtle after drawing the polygon will be the same as it was before drawing. This insight can help you in determining the number of degrees to turn for each polygon, since the sum of the turns must be 360 degrees.

Exercise 8:     Now, consider the task of drawing hexagons (6-sided polygons), octagons (8-sided polygons), or even dodecagons (12-sided polygons). You could certainly define functions for drawing each of these polygons, but these functions would be very similar to each other and the functions you defined above. In fact, all of these function would follow the same pattern: repeatedly draw a side and then turn the turtle. The only differences are (1) the number of repetitions of this drawing and turning, and (2) the number of degrees to turn between sides.

Define a single function called drawPolygon which generalizes all of these polygon functions into a single, all-purpose function. It should have an additional parameter, representing the number of sides in the polygon. For example, the call drawPolygon(4, 20) should result in a square with sides of length 20, while drawPolygon(5, 50) should result in a pentagon with sides of length 50.

Exercise 9:     Cut-and-paste the following code segment into the interpreter, below your definition of drawPolygon, and execute it several times. Describe the result. numPolygons = randomInt(1, 100); for (i = 1; i <= numPolygons; i++) { x = randomInt(-200, 200); y = randomInt(-100, 100); penUp(); moveTo(x, y); penDown(); sides = randomInt(3, 5); size = randomInt(1, 40); drawPolygon(sides, size); }

### Lesson Summary

• A for loop can be used to execute a statement or sequence of statements some specified number of times.
• The general form of a simple for loop is the following: for (LOOP_VARIABLE = 1; LOOP_VARIABLE <= NUMBER_OF_REPS; LOOP_VARIABLE++) { STATEMENTS_TO_BE_REPEATED }
• The loop variable in a for loop can be any legal JavaScript variable. When no meaningful name is obvious, the variable names i, j, and k are commonly used.
• Indenting the statements that are inside the for loop improves readability since it makes it very clear where the loop begins and ends.
• As is the case with all variables in a function (excluding parameters), the loop variable in a for loop should be declared as a local variable.

Solutions to odd numbered exercises (posted late afternoon of due date).