What are Loops?
Loops are a handy tool that enables programmers to do repetitive tasks with minimal effort.
Consider the following application.
The task will be completed just fine, the numbers 1 to 10 will be printed in the output, but there are a few problems with this solution:
- Flexibility, what if we wanted to change the start number or end number? We would have to go through and change them, adding extra lines of code where they're needed.
- Scalability, 10 repeats are trivial, but what if we wanted 100 or even 1000 repeats? The number of lines of code needed would be overwhelming for a large number of iterations.
- More error prone, where there is a large amount of code, one is more likely to make a mistake.
Using loops we can solve all these problems. Once you get you head around them they will be invaluable to solving many problems in programming.
Open up your editing program and create a new file. Now type or copy the following code:
This code may look confusing to you if you have never encountered a loop before, don't worry, the exact details of different loops will be explained later in this chapter, this is an aid to illustrate the advantages of loops in programming.
If we run the program, the same result is produced, but looking at the code, we immediately see the advantages of loops. 10 lines of code have been reduced to just 4. Furthermore, we may change the number 10 to any number we like. Try it yourself, replace the 10 with your own number.