JMA201-01 |
||||
|
Computers are good at doing things repeatedly. Often, we will want to loop - run a series of statements either a set number of times, or until some condition is met.
The for loop is the first type. It is good when you want to run some statements a known number of times (either when you write the program, or based on user input). Take the following example: you want to calculate compounding interest over a number of years. Although there is a formula for this, it serves as a good example of a loop, so we will take the "brute force" approach to solving it.
Our algorithm for this process might look like this:
So we plan to run this cycle of startbalance=(startbalance*.05)+startbalance 10 times.
Here is the code I wrote for this:
Private Sub cmdCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCalc.Click Dim interestRate As Decimal Dim balance As Decimal Dim numberOfYears As Integer interestRate = CDec(txtInterestRate.Text) / 100 balance = CInt(txtStartingBalance.Text) numberOfYears = CInt(txtNumberOfYears.Text) Dim i As Integer For i = 1 To numberOfYears balance = balance * interestRate + balance Next balance = (Math.Floor(balance * 100)) / 100 lblAnswer.Text = CStr(balance) End Sub
In this logic, we use the for...next loop. Quite simply - we declare a variable (i is frequently used). We choose a starting point (1 in my case) and an ending point (number of years). The i variable acts as a counter - for each lap (iteration) we use the current value of i. At the end of each lap, we add 1 to the value of i... the loop will end when the counter variable is no longer equal to or less than numberOfYears.
It is possible to use a step variable, to change how our loop functions - like so:
for i=1 to 10 step 2
'statements
'next
In this case, for each lap, we would have values of 1,3,5,7,9. The loop would add 2 to i at the last lap, and get 11 for i. During the next check of the counter, it would realize i was outside the boundaries of the starting value and the ending value, and exit the loop (resume statements found below the loop).