(ToC) |
...like this:
Then when it runs, the computer unrolls it, and does those steps over and over as if it were the sequence you started out with.Notice that inside the iteration, you still have a sequence. But what happens if not all the copies of that short sequence are the same? That happened when we ate the cereal, I left out the last two steps, where we look to See if the bowl is empty, and -- this is a conditional -- if it is empty, we finished (eXit) the iteration, otherwise we go back and do it Again:
Dip spoon into bowlDrawn out as a long sequence it might look like this: but you see, the iterations are not all identical, the last step in the last iteration eXits, where the corresponding step in the previous iterations did it Again. No problem, that's what conditionals are for: and it is this new subsequence -- four steps done every time, then a conditional also done every time, but inside that conditional, we either do it Again or else eXit, never both -- with a resulting diagram for the iteration like this: When this program runs, (you, when you eat breakfast, or the computer, whoever) you do the colored steps one at a time, and when you come to an arrow, you follow it like a train track, or like the arrows they paint on the floor of a big hospital so you won't get lost. And it comes out at run-time exactly like the linear sequence: The point is that iteration and conditionals are both ways of changing what step (what colored letter) comes next in the written program. When you think about it at the beginning, it might look like a flat line, then you roll it up to get rid of the duplications, and insert conditionals for where there are differences, one or the other (not both). Does that make sense? If not, ask somebody, your neighbor, the instructor, somebody, that's what we are here for. You need it to make sense to you, because that's a large part of what programming is all about, knowing where to put iterations and conditionals in what otherwise might be a straight-line sequence.
Lift spoon to mouth
Eat
See if bowl is empty
If not, do it again.
How about you write a program -- anything you want, since writing programs
you want to write is what this is all about -- that uses iteration. If
you want to throw in a conditional that would be cool too. Then turn
the page.
<<Previous | ToC | Next >>
[2021 June 28]