90 likes | 225 Views
Repetition Structures. Yonglei Tao. 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
E N D
Repetition Structures Yonglei Tao
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 a value • If it is not the empty string • Process the value • Get a value • If it is not the empty string • Process the value • Get a value • … • If it is the empty string • Done Get a value Do While it’s not an empty string Process the value Get a 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 sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) 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) sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) 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) sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Loop If ( numSales > 0 ) Then avgSales = totalSales / numSales lblAerage.Text = Format ( avgSales. “Currency”) else lblAerage.Text = “No Sales” end If End Sub