Finding the smallest in e.g. 20 numbers is easy for humans - we just scan them. But what
about finding the smallest value from 50,000 numbers, presented to you on a stack of paper?
How might you solve this problem? Think!
One way is to use another piece of paper. Look through the numbers in turn, and write the smallest
so far on the paper.
We keep on looking - if we find a smaller one than the one we previously noted, we cross the old
value out, and write down the new one.
The piece of paper acts like a variable. It only holds one value at once, and this value changes
as we work through the list. Let us now look at coding the plan in VB.
Problem
A bank has a list of student overdraft amounts, printed on paper. We have to key in the numbers, and
the program is to display the smallest overdraft. The overdrafts are all positive (>=0) and are ended by
-999.
Some points about the problem:
-
we need a loop, which keeps running as long as -999 is not entered.
-
we need a variable to keep track of the current smallest as we work through the numbers.
A meaningful name helps - e.g. smallestSoFar
-
we need an IF to compare the smallest so far with the number we have just input. Sometimes, we need to
alter the smallest so far.
-
When a human does the job with a piece of paper, what is initially written on the paper? 0? - but
what if an overdraft has a value of 0?
A solution
Remember the while/ inputbox pattern we did with the password problem? Here it is:
n=inputBox... ' get first number
while...
...
n=inputBox... ' get next number
end while
We will approach the solution by writing some simpler programs. First, a program to display
every number we input into a text box. (This lets us check the we are getting
the first and the last number properly)
dim number as double
number=CDbl(inputBox("Enter balance"))
while number <> -999
TextBox1.appendText( CStr( number))
number=CDbl(inputBox("Enter balance"))
end while
To progress: instead of displaying the number, we need to check if it is smaller than the smallest so far.
-
if it is smaller, then we set the smallest so far to the number
-
if it is NOT smaller, then we leave the smallest so far unaltered - i.e. we do nothing.
We Have:
dim number as double
dim smallestSoFar as double
smallestSoFar = 100000 ' has to be bigger than any of the input numbers
number=CDbl(inputBox("Enter balance"))
while number <> -999
if number < smallestSoFar then
smallestSoFar = number
end if
number=CDbl(inputBox("Enter balance"))
End While
MessageBox.Show("Smallest is: " & smallestSoFar)
Note:
Alternatively...
The point of this example was to get you to think about control structures (loops-while, and decisions-if), which
you can then use in other programs. If all you wanted to do was to find the smallest in a list, you would use a spreadsheet.
Later, you will see how to use the VB listbox control, which can automatically sort numbers into ascending order.
| |