Repetition - Counting and Accumulating Yonglei Tao
Flow Chart – Pretest Loop
Flow Chart – Posttest Loop
Counting and Accumulating Write a program to process input, the number of input values are unknown Sample input 27.50 55.00 38.74 88.26 <empty string> 27.50 63.98 55.00 96.11 38.74 88.26 <empty string> <empty string>
Loop Design Get a value If it is not the empty string Process the value Get next value … If it is the empty string Done Get a value Do While it’s not an empty string Process the value Get next value Loop
Program Version One Private Sub btnCalculate_Click ( … ) Dim sales As String Dim numSales As Integer sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Do While sales <> String.Empty ‘ process the value Loop ‘ display the average End Sub
Program Version Two Private Sub btnCalculate_Click ( … ) Dim sales As String Dim numSales As Integer Dim totalSales, avgSales As Currency sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Do While sales <> String.Empty ‘ process the value numSales = numSales + 1 totalSales = totalSales + Val (sales) Loop ‘ display the average End Sub
Private Sub btnCalculate_Click ( … ) Dim sales As String Dim numSales As Integer Dim totalSales, avgSales As Currency sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Do While sales <> String.Empty numSales = numSales + 1 totalSales = totalSales + Val (sales) Loop If ( numSales > 0 ) Then avgSales = totalSales / numSales lblAerage.Text = Format ( avgSales. “Currency”) else lblAerage.Text = “No Sales” end If End Sub