Programming Iterative Loops: - For - While
Programming Iterative Loops: - For - While
• for
• while
What was an iterative loop, again?
Recall this definition:
Iteration is when the same procedure is
repeated multiple times.
for x in 5:12
println(x^2)
end
Longer Loops with “for”
Now suppose you want to add up the values of
y = x2 – 5x + 11 from x = 0 to x = some number n.
function Sum(n)
f(x) = x^2 – 5x + 11
S = 0
for x in 0:n
S = S + f(x)
end
println(S)
end
A Funny Feature of “for”
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:10
println("Mrs. Crabapple is perfect!")
end
For Loops With Recursion
Recall that the powers of two can be generated
using recursion – each term is double the previous
term. Here’s an example using a for loop to print
out the first ten powers of two:
x = 1
for n in 1:10
println(x)
x = 2x
end
Practice Problems 1 and 2
1. Use a “for” loop to generate a list of values of
y = 4x2 – 12 from x = -6 to x = 6.
function reproot(x)
while abs(x – 1) > 0.001
x = sqrt(x)
println(x)
end
end
While Loops with Counters
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) > .001
x = sqrt(x)
n = n + 1
end
println(n)
end
The number n is a counter – it just counts the loops.
While Loops with Counters, 2
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
While Loops vs. For Loops
For a set number of iterations, you could use
either “while” or “for”.
for loops are short and simple, but only work
when you’re trying to increment by an even
amount. You can make them increment by
numbers other than 1 using for n in
1:0.1:20, for example.
while loops are a little longer, but will work
even if you’re not incrementing evenly.
Practice Problem 4
4. Write a function, compound(P), that will
count how many years it will take for an
investment of P dollars, earning 5% interest, to
grow over $1,000,000.