|
CS 140: Introduction
to Computer Programming
Nested For Loops
One is at liberty to write any sort of valid
code within a for loop, including other for
loops. Nested for loops are useful
whenever we need two or more variables to cycle
through a range of values independently of one
another. This will come in handy when
considering all the locations on our screen (a
future topic) or all two digit numbers (below).
A simple example of a nested for loop would be
to write
for j in range(1,6):
for k in range(1,11):
print "*",
The inner for loop prints a row of ten
asterisks, then the outer for loop causes that
to occur five times in a row, yielding a row of
fifty asterisks in total. Of course, we
could have accomplished the same thing with a
single for loop using range(1,51).
However, suppose we add another print statement
after the inner for loop, but within the outer
for loop. (One must choose the level of
indentation carefully.) This gives
for j in range(1,6):
for k in range(1,11):
print "*",
print
Now we get a row of ten asterisks followed by a
carriage return, repeated five times, which
results in five rows of ten asterisks.
Notice that if we had put that print statement
within the inner for loop, like this
for j in range(1,6):
for k in range(1,11):
print "*",
print
then the result would have been fifty asterisks,
one on top of the other. Such is the
effect of indentation!
Just as with regular for loops, we may use the
values of j
and k
while executing the for loop. The
following code will print out the entries of a
five by five multiplication table.
for j in range(1,6):
for k in range(1,6):
print j*k,
print
It's worth understanding why this works.
Work through the program step by step as if you
were the computer. First j=1
and then k=1.
So we print 1. Next k=2,
and we print 2 to the right
of the 1. This
process continues until finally j=5
and k=5,
we print 25 (which is 5*5),
print a carriage return, and the program
ends. The result is a five by five array
of numbers listing all the products.
Here is a novel use of nested for loops to find
two-digit numbers with a certain property.
Let us say that a number is groovy if it
is equal to one more than the sum of the squares
of its digits. Thus 13 is not groovy,
because when we add together 1 squared plus 3
squared we get 1+9, which is 10, and 13 is not 1
more than 10.
To keep track of the units digit and tens digit
separately we need a nested for loop.
Notice that both loops only go up to 9, since
this is the largest digit, but they start at
different places, because we can't use 0 as the
tens digit of a two-digit number.
for tens in range(1,10):
for units in range(0,10):
number = 10*tens + units
value = tens**2 + units**2 + 1
if number == value:
print "Looks like",
number, "is groovy!"
As you can check, 35 is a groovy number.
If you'd like to discover the other one, copy
and paste this code into your editor and run the
program!
|
|
|