Repetition – For and Do While Yonglei Tao
Future Balance You put $10,000 into a bank account that earns 5% interest per year. How much will your account balance be in five years?
Calculation After Year Calculation Balance 0 $10,000.00 1 balance = balance + balance * 0.05 $10,500.00 2 balance = balance + balance * 0.05 $11,025.00 3 balance = balance + balance * 0.05 $11,576.25 4 balance = balance + balance * 0.05 $12,155.06 5 balance = balance + balance * 0.05 $12,762.82
The For Loop Dim balance, interest As Double balance = 10000.00 For year As Integer = 1 To 5 interest = balance * 0.05 balance = balance + interest Next year lblDisplay.Text = Format (balance, “currency”)
The Do While Loop Dim balance, interest As Double Dim year As Integer ‘ declare control variable balance = 10000.00 year = 1 ‘ initialize control varaible Do While year <= 5 ‘ test control variable interest = balance * 0.05 balance = balance + interest year = year + 1 ‘ update control variable Loop lblDisplay.Text = Format (balance, “currency”)
A Problem You put $10,000 into a bank account that earns 5% interest per year. How many years does it take for the account balance to be double the original?
Calculation ….. After Year Calculation Balance 0 $10,000.00 0 $10,000.00 1 balance = balance + balance * 0.05 $10,500.00 2 balance = balance + balance * 0.05 $11,025.00 3 balance = balance + balance * 0.05 $11,576.25 4 balance = balance + balance * 0.05 $12,155.06 5 balance = balance + balance * 0.05 $12,762.82 …..
The Do While Loop Dim balance, interest As Double Dim year As Integer = 1 balance = 10000.00 Do While year <= 5 interest = balance * 0.05 balance = balance + interest year = year + 1 Loop lblDisplay.Text = Format (balance, “currency”) balance < 20000
Find the Number of Iterations i = 0.5 Do While i <= 1.3 lblDisplay.Text = lblDisplay.Text & i & “ “ i = i + 0.2 Loop Dim sum As Integer = 0 For i As Integer = 2 To 20 Step 5 sum = sum + i Next i