Chapter 10
Getting Loopy
IN THIS CHAPTER
Using different kinds of loops
Nesting loops
Coding the Fibonacci Sequence
Loops are a type of control command that are common to every programming language. Computers are really good at repeating the same action over and over again, which is great because as humans, that can get really boring!
Loops can be useful for a variety of purposes. You could animate a cloud in a video game to move from the left of the stage to the right and back to the left and repeat that throughout the entire game. Or you may want to compute how much money you would have after one year if you invest an initial quantity into a bank account that accrues compound interest. Consider placing $100 into that account, with a daily interest rate of 1%! Day 1 you would have $100, day two you would have the balance * 1.01, which would be $101.00, day three you would have the balance * 1.01, which would be $102.01, and so on. If you loop through the process of computing balance = balance * 1.01 for 365 iterations, you would have $3,778.34 at the end of the year! It would be a pretty long program if you had to write balance = balance * 1.01 over and over, 365 times, without ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access