For Next loops.

 

We use For Next loops to count things.  We can count the items in a list, we can count the number of times we perform a computation, we can ask a password a maximum of 3 times, etc.  A for next loop uses less memory than a do while, so it should be used instead of a do while if possible.

 

A for next loop looks like this:

 

        Dim x As Single

        For x = 1 To 10

            TextBox1.Text = Str(x)

        Next

 

All the above code does is count to 10, and put the answer in the text box so quickly that we only see a 10.

 

We can change the program by adding step .001 after the word Single, and it would take a much longer time to run:

 

        Dim x As Single

        For x = 1 To 10 Step 0.001

            TextBox1.Text = Str(x)

        Next

 

You can also go in reverse:

 

        Dim x As Single

        For x = 10 To 1 step - 1

            TextBox1.Text = Str(x)

        Next

 

If the population of the United States grows at a rate of 1 percent a year, and is 270 million in 2003, what will the population be in 2033?

 

We can solve the above program with a for next loop.

 

        Dim pop As Single

        pop = 270000000

        Dim x As Single

        For x = 2003 To 2033

            pop = pop * 1.01

        Next

        TextBox1.Text = Val(pop)

 

Notice the program adds one percent a year with the formula pop = pop * 1.01.  It can easily be changed to 2 percent by using 1.02.  The program is simple, but this would be difficult to calculate on our own, using our own brains, except maybe for smart kid.

 

Complete the following two programs:

 

1.        Suppose $800 is deposited into a savings account earning 4 percent interest compounded annually, and $100 is added to the account at the end of each year.  Calculate the amount of money in the account at the end of 10 years.  (Determine a formula for computing the balance at the end of 1 year based on the balance at the beginning of the year.  Then write a program that starts with a balance of $800 and makes 10 passes through a loop containing the formula to produce the final answer.)

 

2.        Write a program to estimate how much a young worker will make before retiring at age 65.  Request the worker’s name, age, and starting salary as input.  Assume the worker receives a 5 percent raise each year.  For example, if the user enters Helen, 25, and 20000, then the picture box should display the following:

 

Helen will earn about $2415995