The For Loop

Have you ever wanted to make a program that will count to 10!! Probably not, but if you did you could use a for loop. A for loop is used to repeat repetitive task, but one may ask why not use a while loop? The difference is that a for loop can count. By this I mean that if you tell the for loop to stop after 7 times it will. So lets look at a for loop and break it down.

Screen Shot 2013-02-20 at 12.21.18 AM

Now that we undertand the components of a for loop, lets take a look at an example

Screen Shot 2013-02-17 at 3.38.29 PM

This for loop starts off by creating an int that we set equal to one, we set it to one rather than zero because we dont want the program to out put [0,1,2,3,..] we want [1,2,3,…]. Next we set our condition, the condition is checked every time the loop runs and if in this case x is greater than 7 the for loop will quit running. Lastly each time the for loop runs we add 1 to x. With all of this set we output x on each loop. This creates a counting effect and you can see that the output counts from 1 to howMany. howMany is our variable that is checked against, so on the 7th loop  will be equal to 8 therefore the loop quits because howMany> x.

The for loop is very helpful when repetitive task are necessary. While not seen in this example the for loop can be used to complete very complex task, such a alphabetising names and even solving complex equations.

Thanks for reading email me at ccapp.dev@gmail.com if you have any questions

Leave a comment