Accumulator

Special Variables

Accumulator – a numeric variable used to store a value that gets added to

Flag – a variable that, when set true, signals the end of the loop

Look at the following examples.

Example 1
Dim dblNumber As Double
Dim dblSum As Double
Do
    dblNumber = InputBox("Enter a number (0 to end):")
    If dblNumber > 0 Then
        dblSum = dblSum + dblNumber
    End If
Loop While dblNumber > 0

What does Example 1 do? What is the accumulator? What is the flag?

Class Exercise: Averager

We’re going to create a simple program used to average a set of numbers.

 

  1. Begin by designing the form.
  2. Use the names lblCount, lblAverage, cmdEntry, cmdDone for the controls on the form.
  3. Add code to cmdDone.
  4. Add the code for cmdEntry_Click.

Averager Code
Private Sub cmdDone_Click()
    ' end program
    Unload frmMain
End Sub

Private Sub cmdEntry_Click()
‘ dimension
Dim dblScore As Double
Dim dblSum As Double
Dim intCount As Integer
‘ get entries
Do
‘ ask for score
dblScore = InputBox(“Enter a score (0 to end):”, “Averager”)
If dblScore > 0 Then
‘ add score to average (sum and count)
dblSum = dblSum + dblScore
intCount = intCount + 1
End If
Loop While dblScore > 0
‘ display sum
lblCount.Caption = “You entered ” & Format(intCount, “0”) & ” scores.”
lblAverage.Caption = “The average is ” & Format(dblSum / intCount, “0.0”)
End Sub

Assignment

The Prime Number assignment is due in one week. Start with an algorithm.