For loops are a coding technique designed to automate a large number of tasks at once. For instance, instead of manually having to type out the numbers 1 - 100, you can get a for loop to do this for you in just a couple of lines of code. This may seem arbitrary now, but as you get into more complex programs that involve more complicated activities your code has to perform, for loops become a lifesaver.
Setting Up For Loops
- Remember to construct a for loop, you have to give it a range of values to loop through. The first number, or the lower bound, is where the loop starts, but remember to be careful because the last number is 1 greater than the end number.
- The variable i is a common variable used to cycle through all the values of a for loop. If your code relies on a variable that changes throughout the for loop, use i.
- Remember your syntax. Indent every line of code after the loop begins and include a : after the first statement of the loop.
Using For Loops
- For loops are useful in many different types of problems in computer science to shorten your code and make it more efficient. Probably the most obvious one is for automation. Simply put, why would you write a hundred lines of code when all you had to do was write one for loop?
- Other uses of for loops include easy ways to look through a set of data and sort the data in particular ways. Don’t worry, we’ll explain what this means more next week. For now, just focus on the setup and logic behind for loops.