
For loop are named because they run for a specific range of values. They are the most useful when you have an array of objects you want to iterate over or a specific set of numbers you want to get through.
A for loop has a declaration that contains four main components:
A good analogy for a for loop is you reading a book, so let's talk about these components in that context.
A for loop has a declaration that contains four main components:
for(<variable declaration>; <condition>; <increment>) { <code to run>}
A good analogy for a for loop is you reading a book, so let's talk about these components in that context.
Variable Declaration
This is your chance to create a variable specifically for this loop. Usually this is used as your pointer as your variable runs, kind of like your current page number as you run through a book. It tells you were you are right now.
Condition
The condition of a for loop is how you know where to stop. For our book example, this would be like deciding you are going to stop reading for a while on page 200. Every time you turned a page, you would check, "Is this page 200?" and as long as it isn't you could keep reading. In code, this often has to do with checking if your variable is larger than a certain value.
Increment
This is how much your variable changes by each time the loop runs. It's how many pages you would decide to turn. You could turn one page, or two at a time (if you're crazy).
Code to run
This is the part of the loop that should be used to do something. It's you reading a page and understanding what's on it. For a loop, that means anything you can write in a programming language that you want your loop to do.
No comments:
Post a Comment