Thread: For loops
View Single Post
  #3 (permalink)  
Old 12-02-2008, 4:35 AM
jmcilhinney's Avatar
jmcilhinney jmcilhinney is offline
VB.NET Forum Moderator
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Aug 2004
Location: Sydney, Australia
Age: 40
Posts: 6,118
Reputation: 541
jmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalist
Default

Programming does not exist in a vacuum. Programming concepts are pretty much all analogous to real world concepts. Consider an egg carton full of eggs. Assume that the cups are numbered from 0 to 11. Now, if I said to you, for a number i where i goes from 0 to 11, take egg number i and crack it into a bowl, you could do that, right? Congratulations! You just implemented a For loop.

A For loop has a loop control variable, also called a loop counter, that starts at a specific value and increments each iteration until it reaches a specific end value. Once the next iteration completes the loop ends. Within the loop you can use that loop control variable for whatever purpose is appropriate. The most common use is as an index into an array or collection, a la my egg carton example. That's not the only use though. Lets say that you wanted to sum all the numbers from 1 to 10. You could use a For loop where the loop control variable goes from 1 to 10 and in each iteration add the value of the loop control variable to a running total:
Code:
Dim sum As Integer = 0

For i As Integer = 1 To 10
    sum += i
Next

MessageBox.Show(sum.ToString(), "Sum")
It is common to use i for a loop control variable although, particularly when you're learning, it's a good idea to use a more meaningful name if an appropriate one exists. If it represents an array index then name it index.
Reply With Quote