













Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!














Recall this definition: Iteration is when the same procedure is repeated multiple times. Some examples were long division, the Fibonacci numbers, prime numbers, and the calculator game. Some of these used recursion as well, but not all of them.
for loops are used when want to plug in a bunch of successive integers, or repeat a procedure a given number of times. The general structure is: for x in : (do something) end
Let’s say you wanted to print out the values of y = x 2 from x = 5 to x = 12. Here’s the code: for x in 5: println(x^2) end
(Program to add up the values of y = x 2
for can also let you do something a certain number of times; you don’t even need to apply the value of n. Try this: for n in 1: println("Mrs. Crabapple is perfect!") end
It is possible to generate the Fibonacci numbers using a “for” loop, but the replacement is tricky. The first two terms are easy: a = 1 b = 1 And the looped procedure is easy: c = a + b Bu how will you get the next term, and the next, without introducing any new variables?
A while loop is used when you want to iterate until a certain condition is met, or when you know in advance how many loops to run. The format goes: while (condition not met) (do a bunch of stuff) end
Let’s say you wanted to know how many iterations it took for the reproot program to get to within 0.001 of 1. You could modify the program like this: function reproot(x) n = 0 while abs(x – 1) >. x = sqrt(x) n = n + 1 end println(n) end The number n is a counter – it just counts the loops.
Let’s say you wanted to run the reproot program through 20 loops, then print the answer. This can also be done using counters: function reproot(x) n = 0 while n < 20 x = sqrt(x) n = n + 1 end println(x) end
Working in groups or on your own, write a function calcgame(x) that counts the number of iterations in the calculator game. Here are the rules again: if x is odd, multiply by 3 and add 1. if x is even, divide by 2. Stop when x = 1. Count the iterations. Your function must include a “while” loop as well as an “if/else” test.
Use a “for” command to list the iterations of the calgame(x) function from x = 1 to x = 20.