% Things not yet covered:
% DoEvents
% Timers??

%{{{ setups

\documentclass{article}

\parindent=0mm
\parskip=5mm

\setlength{\oddsidemargin}{  -5mm}
\setlength{\topmargin}    { -20mm}
\setlength{\textheight}   { 260mm}
\setlength{\textwidth}    { 165mm}

\begin{document}

%}}} 

%{{{ heading and main page

\begin{center}
{\large{\bf An Introduction to VisualBasic}}
\vskip 3mm
\end{center}

This document is designed to give a general introduction to Visual
Basic. It covers the main aspects of the Basic programming language,
and some of the many aspects of the "visual" side of VisualBasic.

There are some checkpoints at various stages in this document where
the reader is invited to write a small VisualBasic project.
These can be used to check that you have understood the section
before moving on.

Please send queries/corrections/criticisms to {\tt c.allton@swan.ac.uk}.

%}}} 

%{{{ 1. An Overview of VisualBasic

\section{1. An Overview of VisualBasic}

VisualBasic has two components: the {\em Visual} and the {\em Basic}.
When you program VisualBasic, you need to setup both these two
halfs. When you create the visual side, you are designing the window,
and the interior of the window (e.g. the buttons and the text and
picture boxes etc) that you will see when you run your VisualBasic
project. These windows are called {\em Forms} in VisualBasic.

The Basic component is the actual code that associated with the
buttons in the windows/forms, and (stating the obvious) uses
the BASIC programming language.

It is important to note that you, the programmer, has to design both
the visual and basic aspect of any VisualBasic project.  These two
components are linked together in a very intuitive way: E.g. Any
"command" button on a window/form has Basic code associated with it,
so the action of clicking on the button means that the Basic code
associated with that button will be run.

{\bf VisualBasic has two components: the "Visual" or Form
(or Window-like) part, and the "Basic" or code part. The two are
linked in a very intuitive fashion.}

%}}}
%{{{ 2. Your first VisualBasic Project (and the {\tt Print} Statement)

\section{2. Your first VisualBasic Project (and the {\tt Print} Statement) }

To begin designing your first VisualBasic Project, you must first
open the VisualBasic environment. If there is no short-cut icon
on your desktop, then you should be able to open the VisualBasic
Programming Environment 
by going to the {\tt Start} button (at the bottom left of your screen)
and then selecting {\tt Programmes} where you should see the
{\tt VisualBasic 6.0} item. 
Once you select this, the VisualBasic Programming window will open.
You will see a window with a {\tt Standard EXE} icon. Double click on this.
(In this course, we will only ever use the {\tt Standard EXE} template.
You'll have to buy a VisualBasic book if you want to know about
the other templates!!)

After you have double clicked on the {\tt Standard EXE} icon, you will see
a blank, grey {\em Form}.

Have a look at the left-hand-side of the VisualBasic Programming window.
You will see a number of icons. Move your mouse over the grey rectangle.
You will see the text {\tt CommandButton} appear. Double click on the icon.
You should see a grey rectangle appear in the middle of the form called
{\tt Command1}.

You have just inserted your first button into your form!

Double click on this button. You will see the following:

\begin{verbatim}
Private Sub Command1_Click()

End Sub
\end{verbatim}

You have now left the {\em Visual} (or Form) component of the VisualBasic
Programming environment and are now in the {\em Basic} (or code) component.
The code which you are about to enter is associated with the button
called {\tt Command1} on your form. Type the following line:

{\tt Print "Hello Swansea"}

Your screen should now be like this:

\begin{verbatim}
Private Sub Command1_Click()
Print "Hello Swansea"
End Sub
\end{verbatim}

(Note that if you type {\tt print "Hello Swansea"} with a lower case "p",
then once you move the cursor away from that line, the "p" becomes
upper case. This is VisualBasic showing off and making everything look tidy.)

We are now ready to {\em run} this VisualBasic project.
To do this, just click on the icon near the top of the screen which is
like a play button on a video player (i.e. like a triangle pointing to the right).

As if by magic, a copy of your form appears on the screen. Click on the
button called {\tt Command1}. You will see the words {\tt "Hello Swansea"}
appear at the top of your form! To exit this "run mode", click on the icon
in the shape of a square near the play button and you will return to play mode.

To stop the programme from running, you can click on the X on the top
right of the window (as usual) OR you can click on the square button
which looks like a stop button on a video player. (It's next to the
``play'' button!)

If you are stuck doing this, then you can download a working version
very similar to this 
<a href=''../VB_Form_Files/Hello_World.frm'' > here</a>.

You can print more than one thing on the same line using either a
comma (which plays the role of a TAB character) or semi-colon
(which leaves no space at all).

Edit the programm above so that it now looks like:

\begin{verbatim}
Private Sub Command1_Click()
Print "Hello Swansea",''and the rest of Wales''
Print "Hello Swansea";''and the rest of Wales''
End Sub
\end{verbatim}

When you run this programme you will see the difference between the
comma and semi-colon.  Note that you can put comma's and semi-colon's
at the end of the line in a {\tt Print} statement too. The following
code would do the same as the code above.

\begin{verbatim}
Private Sub Command1_Click()
Print "Hello Swansea",
Print "and the rest of Wales"
Print "Hello Swansea";
Print "and the rest of Wales"
End Sub
\end{verbatim}


{\bf CHECKPOINT:} Take the example programme 
<a href='''../VB_Form_Files/Hello_World.frm''>from here</a> and modify it
so that it prints out the messages all on one line. Change it to print
out messages of your choice!


{\bf VisualBasic operates in two {\em modes}. The first is the
{editting/designing} mode (which is what you are doing when you are
creating and modifying your form and the associated code),
and the second is the {\em running} mode (which is what happens
once you click on the play button). You can get back to the edit
mode by clicking on the stop button.

You can add a {\tt CommandButton} to a form by double clicking on the
corresponding icon in the Toolbox.

The {\tt Print} statement is used to output to the screen.
}

%}}}
%{{{ 3. Some mathematics (and Comment lines)

\section{3. Some mathematics (and Comment lines)}
\label{sec:maths}

We are now ready to get our VisualBasic project to do something useful.

Make sure you are in edit mode with the form highlighted (or "in focus").
(If you are having trouble with this, make sure that you are not in run
mode by clicking on the stop button. Then click on the bar which is called
{\tt Form1(Form)}.)

Double click on the {\tt Command1} button. This should now display the
three lines of code:

\begin{verbatim}
Private Sub Command1_Click()
Print "Hello Swansea"
End Sub
\end{verbatim}

Edit these lines of code so that it now says:

\begin{verbatim}
Private Sub Command1_Click()
' This programme is going to add two numbers
a = 2
b = 4
c = a + b
Print "a+b = "; c
End Sub
\end{verbatim}

{\bf Make sure that there is NO }{\tt Option Explicit}{\bf line
appearing at the start of the programme.} (i.e. remove this line
if it appears.)

Note that there is a ``comment'' line in this programme:

{\tt ' This programme is going to add two numbers}

Comment lines are included in programmes to give some guidance to
you (and anyone else who reads your programme) about
what the programme is doing.  It is totally ignored by the computer
when it comes to run the programme.

Run this project (i.e. click on the play button), and click on the
{\tt Command1} button. You should see

{\tt a+b = 6}

appear at the top of the form.

Lets explore the Basic component a little.
Each line in any computer program represents an instruction to the
computer. The computer reads one line at a time and performs whatever task
is stated on that line.
It is analogous to the set of instruction to bake a cake. You start by
breaking eggs, then you add flour, then ... etc.

What we have done in the above Basic program is to tell the computer
to perform four tasks, one after the other. The first is to assign
the number "2" to the variable called {\tt a}. The second is
to assign the number "4" to the variable called {\tt b}.
The third is to calculate what {\tt a} plus {\tt b} is, and to assign
the answer to the variable called {\tt c}. The final task is to
print the value of {\tt c} to the screen.

This sounds incredibly straightforward doesn't it?

Computer programs are often used to calculate the values of mathematical
expressions. These expressions involve the familiar operations such as
addition, multiplication etc. The above example was simply to calculate
{\tt c=a+b}.

Other mathematical operations are listed below:

\begin{tabular}{ll}
{\tt a - b}    & subtraction \\
{\tt a * b} & multiplication \\
{\tt a / b}    & division \\
{\tt a\^n}      & raising a to the power n i.e. $a^n$\\
{\tt a Mod b}  & gives the remainder e.g. {\tt 5 MOD 2} is {\tt 1} \\
\end{tabular}

You can also use many mathematical functions in the usual way:

{\tt Cos(a), Sin(a), Tan(a), Exp(a), Log(a)}

Note that the angle {\tt a} has to be in RADIANS!

Other useful commands are:

\begin{tabular}{ll}
{\tt Abs(a)} & takes the absolute value, {\tt |a|} \\
{\tt Atn(a)} & returns the arctangent of {\tt a}, i.e. $tan^{-1}(a)$ in RADIANS!\\
{\tt Sqr(a)} & takes the square root, $\sqrt{a}$ \\
{\tt Sgn(a)} & returns either {\tt +1}, {\tt -1} or {\tt 0} \\
             & depending on whether {\tt a} is positive, negative, or zero\\
{\tt Int(a)} & returns the integer part of {\tt a}, i.e. {\tt Int(4.8) = 4} \\
             & Note though that  {\tt Int(-4.8) = 5} \\
{\tt Rnd}    & returns a "random" number between 0 and 1 \\
\end{tabular}

{\bf CHECKPOINT:} Write a program which calculates {\tt x} in the following
expression, and prints its value to the screen. (Note that if it crashes,
try increasing the value of $b$.)

\[
x = \frac{ -b + \sqrt{b^2 - 4 a c} } {2a}
\]

{\bf A program is just a list of instructions for the computer
to perform. Often these instructions involve numerical manipulation
of variables!

You can include {\em comment lines} (i.e. information for others to read
which explain what the programme is trying to do) by using the single
quotation character ' }

%}}} 
%{{{ 4. Saving your VisualBasic Programme

\section{4. Saving your VisualBasic Programme}

We have now done a fair bit of typing and would like to save our work
somehow so that we can come back to it later on. This section
describes how this is done.

Open up a VisualBasic programme, for instance the one which calculated
the quadratic solution from the previous section. If you don't have
one to hand, try this 
<a href=''../VB_Form_Files/Hello_World.frm'' > old one</a>.

Now go to the {\tt File Menu} (top left of screen) and select
{\tt Save XXXX.FRM As ...} (where {\tt XXXX} is the name of your form file - probably
{\tt Form1}). Click on this option, and choose some directory to save your
file, e.g. the C: drive. Once this form file is saved, you can load
this form file by simply double-clicking on its icon.

You can set up your VisualBasic so that these saves are automatically performed
every time you run your programme. Simply
go to the {\tt Tool} menu item, then choose {\tt Options}, and then in the
{\tt Environment} tab, check the box labelled {\tt Prompt to Save Changes}.

{\em Note that unfortunately, even if you are on an Open Access PC,
VisualBasic may not be able to see your {\tt P:}
drive. However, you can still save your form file to {\tt C:} and then
use ``My Computer'' (or Windows Explorer) to copy it to your {\tt P:}
drive which is in the {\tt Network Drives} section of ``My Computer''.
}

%{\em
%Note that there is a way ???????????????
%}

{\bf
Obviously it is crucial to make a backup copy of your programme as
well.% (See the Course Information section for details about how to do
%this.)
}

You may be wondering about the {\tt Save Project} options under the
{\tt File} menu. This is something you'll never need to do unless you start
writing very complicated VisualBasic programmes. When you come to
submitting your solutions for your continuous assessment, you need
only ever submit your Form file.

{\bf
You can save your VisualBasic Programme by saving the FORM file. You
do this using the {\tt File} menu item and selecting the {\tt Save XXXX.FRM}
option.
}

%}}}
%{{{ 5. {\tt IF/THEN/ELSE} (and {\tt End}) Statements

\section{5. {\tt IF/THEN/ELSE} (and {\tt End}) Statements}
\label{sec:ifthen}

Now edit the quadratic solution programme so that you are using the following values:
{\tt a=1, b=2, c=8}. Run this project. Note that you will get an error
message. Click on the {\tt Debug} button, and you will see the line in
your code which is taking the square root highlighted in yellow. This
is the actual line in the code which caused the error.  Why do you
think this happened in this case? (Note, you'll have to click on the
stop button to leave the run mode, and to get back to the edit mode.)

This error message is very embarrassing, so we'll investigate a method
of getting around it. What you want is for the computer to {\em test} whether
$b^2 - 4ac$ is negative or not, before proceeding to calculate {\tt x}.

This "test" can be done with an {\tt If ... Then} statement.
Edit your code so that it looks like:

\begin{verbatim}
Private Sub Command1_Click()

a = 1 ' Setting the values of the coefficients of the quadratic
b = 2
c = 8

If b^2 - 4 * a * c < 0 Then
   Print "Imaginary Solution!"
Else
   x = ( -b + Sqr( b^2 - 4 * a * c ) ) / ( 2 * a )
   Print "x = "; x
End If

End Sub
\end{verbatim}

(Note that the indentation in this code is for legibility only.)

In the above the line
%
\begin{verbatim}
a = 1 ' Setting the values of the coefficients of the quadratic
\end{verbatim}
%
contains a {\em comment} which is simply everything after the
quotation mark. Remember, comments are totally ignored by VisualBasic;
they are designed so that the programmer (i.e. you!) can put
in information to remind yourself (and others who will read your
program) of what the program is designed to do at that point.
It is good programming practice to put lots of comments into your programme!

You can no doubt guess what the above code is doing.
If {\tt b^2 - 4ac<0}, then it prints out the warning message
{\tt Imaginary Solution} and stops at the {\tt End} statement.
If not, then it calculates the root.
Note that the warning message may flash up on the screen too quickly
for you to see...

Note that the {\tt ELSE} branch of the {\tt IF} statement is optional,
so the following would also work (make sure you understand why!):

\begin{verbatim}
Private Sub Command1_Click()
a = 2
b = 4
c = 1

If b^2 - 4 * a * c < 0 Then
   Print "Imaginary solution!"
   End
End If

x = ( -b + Sqr( b^2 - 4 * a * c ) ) / ( 2 * a )
Print "x = "; x

End Sub
\end{verbatim}

Note that the message {\tt Imaginary solution} may flash up on the screen
too quickly for you to see...
(i.e. the {\tt End} statement stops the programme instantly.)


{\em It is important to remember that, in general, each of these} {\tt
If ... Then} {\em statement comes with a matching} {\tt End If}.

You can also do more complicated tests like:

\begin{verbatim}
If x > 0 and y < 2 Then ...
\end{verbatim}
\vspace{-10mm}
\begin{verbatim}
If a = 1 or b = 2 Then ...
\end{verbatim}
\vspace{-10mm}
\begin{verbatim}
If Var1 >= 1 and xyz <> 2 Then ...
\end{verbatim}

In the above, the {\tt Var1 >= 1} means "{\tt Var1} greater than or equal to 1",
and the {\tt xyz <> 2} means "{\tt xyz} not equal to 2".

Furthermore you can use ``Not'' as well in these {\tt If/Then} statements. i.e.

\begin{verbatim}
If Not a + b = c Then
Print ``a + b is not equal to c''
End If
\end{verbatim}

is identical to:

\begin{verbatim}
If a + b <> c Then
Print ``a + b is not equal to c''
End If
\end{verbatim}

You can also use an {\tt ElseIf} statement and even nest {\tt If ... Then}
as follows:

\begin{verbatim}
If a <= 9 Then
   If b = c And ( d < e Or f >= g) Then
      Print "Hello"
   ElseIf b > c Then
      Print "Goodbye"
   End If
Else
   If h <> j Then
      a = 3*c
   End If
End If
\end{verbatim}

Finally, you can have a brief version of {\tt If ... Then}
without the {\tt End If} line, {\em so long as everything is
on the one line}. To illustrate this consider the following code:

\begin{verbatim}
a = 2
b = 4

If a < b Then Print "a is less than b"

If b < a Then Print "b is less than a"

Print "Hi there"
\end{verbatim}

The output from the case above would be:

\begin{verbatim}
a is less than b
Hi there
\end{verbatim}

{\bf CHECKPOINT:} Write a program which reads in two numbers {\tt A}
and {\tt B} and prints out the greater.


{\bf Sometimes the computer will give an error when you
ask it to do something it can't - e.g. take the square root of
a negative number. You can get the program to branch to different
parts of the code using the {\tt If ... Then} statements.}

{\bf You can get a program to stop instantly by the {\tt End} statement.}

%}}} 
%{{{ 6. Message Boxes

\section{6. Message Boxes}
\label{sec:msgbox}

In the example in the previous section where the solution of a
quadratic equation was calculated, we had to take care when we took
the square root of a negative number. In cases like this, it may be
convenient, or just more pretty, if the warning message appeared in a
separate box, rather than in the main form itself.

In VisualBasic, the way of doing this is with the Message Box.

The Syntax for this is very simple:

{\tt MsgBox "Error - Imaginary Solution"}

So the whole of the quadratic formula code would now look like:

\begin{verbatim}
Private Sub Command1_Click()
a = 1 ' Setting the values of the coefficients of the quadratic
b = 2
c = 8
If b^2 - 4 * a * c < 0 Then
   MsgBox "Error - Imaginary solution!"
Else
   x = ( -b + Sqr( b^2 - 4 * a * c ) ) / ( 2 * a )
   Print ``x = ''; x
End If
End Sub
\end{verbatim}

Try the above code out to see how the Message Box works. You may find
Message Boxes useful in the future when you code some more complex
programmes.

You can make the output of Message Boxes more complex. Try replacing the
{\tt MsgBox} line in the programme above with:

\begin{verbatim}
   MsgBox "Error - Imaginary solution!" & vbNewLine & "b = " & Str(b) & " is too small"
\end{verbatim}

You'll see that using the ampersand character {\tt &} is a way of joining
text together in the output of the Message Box. Note also that to output
a number to a Message Box, you have to convert it to a string (or text)
using the {\tt Str} function. We'll talk more about this function very
soon...

{\bf Message Boxes allow the programme to interact very usefully with the
user. In particular they are useful to give warning messages, or to
display the results of a calculation.}

%}}}
%{{{ 7. TextBoxes (and Labels)

\section{7. TextBoxes and Labels}
\label{sec:textbox}

Earlier you wrote a simple program which calculated (one
of) the solutions of the quadratic equation. However, it is not in a
very convenient format because in order to change the coefficients,
{\tt a,b} and {\tt c}, you have to leave the {\em run} mode, and {\em edit} the actual
basic code itself.

We are now going to learn a far more convenient way to change the values
of {\tt a,b} and {\tt c} in the above VisualBasic project.

Make sure you are in edit mode, (still with the above project from
the previous section) and click on the window containing
{\tt Form1}. Have a look at the left hand side of the VisualBasic Programming
Environment window. You will see a number of icons in the {\em Toolbox} (including the
{\tt Command Button} icon which we have already used).
Move the mouse over the button which looks like a white rectangle
with {\tt ab|} in it ({\em don't click yet!}).
You should see the text {\tt "TextBox"} appear as you move your mouse over it.
Double click on this white rectangle icon now.
You will now see this text box appear on your form.
It is probably positioned in an inconvenient place on your form,
so just drag it near to the top-left of your form.

Make sure that the text box you have just inserted on your form is
highlighted. Now have a look near the bottom-right of the VisualBasic
Programming window. You will see a table with two
columns. This is the {\tt Properties} table. In the {\tt (Name)}
row, you will see {\tt Text1}. Change this to {\tt a}.
Further down in the Properties table, you will see the {\tt Text}
row. Delete the {\tt "Text1"} which appears in this row (i.e. it
is now empty).

What we have done is to set up an "input" box in your form into
which you can put any value of {\tt a} you like.
Repeat the above procedure so that we have text boxes
for both {\tt b} and {\tt c} as well as for {\tt a}.
(i.e. (i) double click on the {\tt text box} icon, and (ii)
in the Properties window, change the {\tt Name}
of the text box to {\tt b} (or {\tt c}), and make sure that the
{\tt Text} property is empty.)

Now double click on the {\tt Command1} button. This should take you
to the code associated with this button which should be something like:

\begin{verbatim}
Private Sub Command1_Click()
a = 1
b = 2
c = 8
x = ( -b + Sqr( b^2 - 4 * a * c ) ) / ( 2 * a )
Print "x = "; x
End Sub
\end{verbatim}

Now delete the three lines

\begin{verbatim}
a = 1
b = 2
c = 8
\end{verbatim}

You don't need these lines to define the value of {\tt a,b} and {\tt c} because
these will be defined while in run mode. (Honest!)
Now run this project. You will see a form (window) with three empty
white boxes in it. Ummm... It is a little confusing because it is
not clear which box is {\tt a}, and which is {\tt b} and {\tt c}.
VisualBasic has a way of labelling forms (windows).

Go back to edit mode (i.e. hit the stop button). Now have a look at
the {\em ToolBox} which is the array of icons on the left-hand of the
VisualBasic Programming window. You'll see one which is simply the
letter {\tt A} called a {\tt Label}.  Double click on
this to add it to your form. Now move it next to the text box which
contains {\tt a}. Have a look at the Properties window of this {\tt Label}.
Change the {\tt Caption} property from {\tt Label1} to {\tt a}.  You will see the
character {\tt a} appear on the form!

Repeat this procedure for both {\tt b} and {\tt c} so that their text boxes
are now labelled appropriately.

Now run this project one more time. It still doesn't quite look up to
scratch because there is an ugly grey button called simply {\tt
Command1} on it. It would be better to have this called {\tt
Calculate} or whatever. Can you guess how to change this?  (Go back to
edit mode, highlight the {\tt Command1 button} and change its {\tt
Caption} property from {\tt Command1} to, e.g. {\tt Calculate}. You may
want to change the text font (by altering the {\tt Font} property)
of the background colour (by altering the {\tt BackColor} property,
and then changing the {\tt Style} property from {\tt Standard} to
{\tt Graphical}) as well while you are there!

OK. Now run this project once more. Enter in your choice of {\tt a,b} and
{\tt c} into the text boxes. Then click on the (brightly coloured?) {\tt
Calculate} button. You should see the quadratic solution appear on the
screen!

This is almost good enough to submit for Continuous Assessment,
but it could be just a little bit better. What we'd like to
do is to output the result to a nice text box, rather than
to the background part of the form.

Any ideas how to do this?

{\bf CHECKPOINT:} Modify the above project so that you now have
a fourth text box on your form (correctly labelled) which will
display the value of {\tt x}.

{\bf 
{\tt text boxes} can be used to input information from the user/keyboard
directly into our program.
}

{\bf {\tt Labels} are a way of writing useful words directly onto the form.}

%}}} 
%{{{ 8. Problems with TextBoxes

\section{8. Problems with {\tt TextBoxes}}
\label{sec:probtext}

The above program seems very straightforward. Once you have set up the
{\em Visual} (i.e. form) component of the project, the code was
amazingly simple. It just consisted of the lines:

\begin{verbatim}
Private Sub Command1_Click()
x = ( -b + Sqr( b^2 - 4 * a * c ) ) / ( 2 * a )
End Sub
\end{verbatim}

Now we are going to modify this project to make it even simpler.
Edit the form, and highlight the {\tt x} text box. Delete this
by hitting the delete key on your keyboard. (Delete also the {\tt Label}
box next to it.)

Now double click on the {\tt Calculate} button. Edit the code so that
you have simply:

\begin{verbatim}
Private Sub Command1_Click()
c = a + b
End Sub
\end{verbatim}

This seems like a backward step! However, trust me! Run this project
and enter in your choice of {\tt a} and {\tt b}.

What is going wrong??!!

If you try with a few different values of {\tt a} and {\tt b} you'll
soon see the pattern. It is just treating {\tt a} and {\tt b} as {\em
character strings} and not as numbers. The line in your code {\tt c =
a + b} is simply concatenating {\tt a} and {\tt b} (i.e. appending
{\tt b} onto the end of {\tt a}).

{\bf {\em The basic problem is that VisualBasic treats the entries in
the TextBoxes as strings rather than as numbers. Since you cannot do
algebra (i.e. multiply, divide, add etc.) with strings, we must
convert these string variables into numbers first, and then do our
algebra on these numbers!}}

Go back to edit mode and highlight the {\tt a} text box on the form.
Now change the {\tt Name} property from {\tt a} to {\tt str\_a}.
Similarly change the name of the {\tt b}'s text box to {\tt str\_b},
and the {\tt c}'s text box to {\tt str\_c}.
The {\tt str\_} just underlines the fact that what you enter into
the text box associated with {\tt a} is treated as a character {\em
string} and not a number.

We now have to modify the code slightly. Double click on the
{\tt Calculate} button to bring up the code. Alter the code to the
following:

\begin{verbatim}
Private Sub Command1_Click()
a = Val(str_a)
b = Val(str_b)
c = a + b
str_c = Str(c)
End Sub
\end{verbatim}

Note that as you type in the {\tt Val(} or the {\tt Str(}, VisualBasic
gives you a little caption which helps you complete the line.

What are we doing in the above? Well, we've introduced two new functions,
{\tt Val} and {\tt Str}. These just convert between the {\em string}
and {\em numerical} values. So

{\tt a = Val(str\_a)}

takes the character string {\tt str\_a} (which is what you will be
entering into the {\tt a} text box when you run this project) and converts
it to a numerical value, and stores this in the (numerical) variable,
{\tt a}.

Similarly

{\tt str\_c = Str(c)}

converts the numerical value stored in {\tt c} into the string {\tt str\_c}
(which is the actual text box which you so carefully called {\tt str\_c}
above).

To you and I, both the TextBox {\tt str_a} and the numerical variable
{\tt a} contain the same thing. However, to VisualBasic they are quite
different. The {\tt str_a} is a {\em string} variable (and you can't
do algebra on string variables) and {\tt a} is a {\em number} which
can be used in an algebraic expression.

This seems a little messy, but it is the way you have to proceed!!!

{\bf Text boxes always contain {\em text} or string variables, and therefore the functions
{\tt Val} and {\tt Str} must be used to convert to and from numerical
values.}

%}}} 
%{{{ 9. Declaring your Variable Types: {\tt Long, Double} and {\tt String}, and {\tt Option Explicit}

\section{9. Declaring your Variable Types: {\tt Long, Double} and {\tt String}, and {\tt Option Explicit}}
\label{sec:declare}

In the previous section (see \ref{sec:probtext}), we introduced the
concept of different {\em data types}. There are many different types
that VisualBasic understands, but we will only deal with three:

{\tt Long, Double} and {\tt String}

{\tt Long} is for integer numbers.

{\tt Double} is for real numbers (i.e. numbers which have decimal
points in them!). (They can have up to around 12 significant figures.)

The {\tt String} type is for character strings (like names etc).
{\tt TextBoxes} are defined as {\tt String} types.
Note though that this is done automatically for you - i.e. you {\bf don't}
have to declare your {\tt TextBoxes} as string variables in your code with
the {\tt Dim} statement (see below).

It is best to get into the habit of always declaring which type each
variable used belongs to. The way to do this is with the declaration
or {\tt Dim} statement. In the following, we are defining different
variables:

\begin{verbatim}
Option Explicit

Private Sub Command1_Click()

Dim A, BB, I As Long
Dim x, y, speed As Double
Dim name1, place, city As String

End Sub
\end{verbatim}

In the above,
{\tt A, BB} and {\tt I} are declared to be integers
(using {\tt Long});
{\tt x}, {\tt y} and {\tt speed} are declared as
real numbers (using {\tt Double});
and 
{\tt name1, place} and {\tt city} are declared to be
string variables.

You will also notice in the above the line {\tt Option Explicit}
which is very useful. This line means that VisualBasic will demand
that you declare {\em every} variable that you use. i.e. if you use
a variable that you haven't declared with a {\tt Dim} statement,
it will give you an error.

You can automatically get {\tt Option Explicit} to appear at the
start of all of you VisualBasic Programs by going to the {\tt Tools}
menu item (at the top of the VisualBasic Window) and then selecting
{\tt Options...}. You should then tick the box labelled
{\tt Require Variable Declaration}. From now on, VisualBasic will
insert the line {\tt Option Explicit} into the top of your program.

Why do you need to declare each variable's type?  The reason is that
all of these variables are stored in the computer's memory in binary
format - as a series {\em bits} i.e. zeros and ones.  When integers
are stored, they are simply converted to base two, and stored
directly. i.e. $5 = 1 \times 2^2 + 0 \times 2^1 + 1 \times 2^0$.  So
the number 5 would be stored as ``101'' in the computers memory.

However, things are not this simple for real numbers. Any general real
number, $R$, can be written in scientific notation as

\[
R = a \times 10^b
\]

where $-1 \le a \le +1$ and $b$ is an integer. So when the computer
stores the real number $R$, some of the bits the computer's memory
are reserved for storing the $a$, and some for $b$.
(In practice $a$ is only ever stored to a certain precision - typically
12 significant figures for the {\tt Double} variable type.)

When the computer does algebra on variables, it obviously needs to know
whether each of these numbers is stored as integers or reals
because, as explained above, integers and reals are stored entirely
differently. This is the reason that each variable needs to be
declared!

{\bf There are three very useful data types: {\tt Long, Double} and
{\tt String} which refer to {\em integer, real} and {\em character
string} variables. You can declare your variables with a {\tt Dim
... As ...}  statement. Each of these variable types is stored in the
computer's memory in a different format. A useful habit is to declare
all your variables. You can force yourself to do this using the {\tt
Option Explicit} command.}

%}}} 
%{{{ 10. OptionButtons

\section{10. OptionButtons}

In the {\tt ToolBox} (on the left of the VisualBasic Window), you will
see an icon in the shape of a small, white circle with a black dot
called {\tt OptionButton}.

Beginning with a blank form, insert two of these {\tt OptionButton} boxes
onto your form. You should move them around the form so that you
can see them both. Now insert a {\tt CommandButton} on to this form.
Double click on the {\tt CommandButton} to access the program.

Enter the following code:

\begin{verbatim}
Private Sub Command1_Click()

If Option1 Then
   Print "Option1 chosen!"
End If

If Option2 Then
   Print "Option2 chosen!"
End If

End Sub
\end{verbatim}

When you run this program, you should first select one of the two options,
and then click on the {\tt CommandButton}. You will see a message appear
on the screen telling you which {\tt Option} you selected.

There are a few things to note about {\tt OptionButtons}:

\begin{itemize}

\item
You can change the {\tt text} property of each of the option boxes so
that they are called something more useful than {\tt Option1, 
Option2} etc.

\item
Only one option box can be selected at a time (in run mode)

\item
You can label each option button by entering the label into the {\tt
Caption} property

%\item
%In the program, the variables {\tt Option1, Option2} etc take the
%values {\em true} or {\em false}

\end{itemize}

<a href=''../VB_Form_Files/Option_Buttons.frm'' >Here</a>
is an example programme using {\tt OptionButtons}.

{\bf {\tt OptionButtons} are a way of selecting one (and only one) of
a number of choices. They naturally are useful with the {\tt If ... Then ...}
statements. (See \ref{sec:ifthen}.)}

%}}} 
%{{{ 11. CheckBoxes

\section{11.CheckBoxes}

{\tt CheckBoxes} are very similar to {\tt OptionButtons}.
They appear in the {\tt ToolBox} (on the left of the VisualBasic Window),
as an icon in the shape of a small white square with a cross through it.

Beginning with a blank form, insert two of these {\tt CheckBoxes} boxes
onto your form. You should move them around the form so that you
can see them both. Now insert a {\tt CommandButton} on to this form.
Double click on the {\tt CommandButton} to access the program.

Enter the following code:

\begin{verbatim}
Private Sub Command1_Click()

If Check1 Then
   Print "Check1 chosen!"
End If

If Check2 Then
   Print "Check2 chosen!"
End If

End Sub
\end{verbatim}

When you run this program, you should note that you can select
no {\tt CheckBoxes}, or one, or both!
When you click on the {\tt CommandButton} you will see a message
on the screen telling you which (if any) of the {\tt CheckButton} you selected.

As with the {\tt OptionButtons}, you can change the {\tt text}
property of each of the {\tt CheckBoxes} so that they are called
something more useful than {\tt Check1, Check2} etc. You can also
label each CheckBox button by entering the label into the {\tt Caption}
property

<a href=''../VB_Form_Files/Check_Boxes.frm'' >Here</a>
is an example programme using {\tt CheckBoxes}.

{\bf {\tt CheckBoxes} allow the user to select from a number of choices.
The user can select from any of the {\tt CheckBoxes} - so, e.g. no
{\tt CheckBoxes} selected, or even all selected are both valid!
As with {\tt OptionButtons} they are naturally useful with the
{\tt If ... Then ...}
statements. (See \ref{sec:ifthen}.)}

%}}} 
%{{{ 12. {\tt FOR/NEXT} Loops

\section{12. {\tt FOR/NEXT} Loops}
\label{sec:for}

Often the main benefit of computers is that they perform the same (often
tedious task) repeatedly - without even complaining. Rather than writing
out the same list of instructions many times, you can get
the program to repeatedly {\em loop} through the {\em one} set of
instructions many times.

As an example, consider the procedure you need to go through to check
the pressure in your car's tyres (written in an imaginary computer language):

\vspace {-5mm}
\begin{verbatim}
MOVE TO TYRE 1
MEASURE PRESSURE IN TYRE 1
MOVE TO TYRE 2
MEASURE PRESSURE IN TYRE 2
MOVE TO TYRE 3
MEASURE PRESSURE IN TYRE 3
MOVE TO TYRE 4
MEASURE PRESSURE IN TYRE 4
\end{verbatim}

Instead of writing out what to do for each of the four tyres, you can
simply write:

\begin{verbatim}
LOOP OVER THE VALUES n = 1,2,3,4
MOVE TO TYRE n
MEASURE PRESSURE IN TYRE n
GO TO START OF LOOP
\end{verbatim}

In Basic, the commands to start the above loop is {\tt For n = 1 To
4} and the command at the end is {\tt Next n}. As an example, the
following program writes out all the numbers from 1 to 10:
(Note that you can click
<a href="../VB_Form_Files/Prints_numbers_to_10.frm" > here </a>
to download a copy of this program.)


\begin{verbatim}
For i = 1 TO 10
Print i
Next i
\end{verbatim}

The variable {\tt i} is called the {\em loop} variable.
Note that the loop variable {\tt i} is incremented by one
each time through the loop. You can increment the loop variable by any
amount you choose. For example, the following program prints all odd
numbers between 1 and 10. This is done using the {\tt Step} parameter
in the {\tt For} line:
(Note that you can click
<a href="../VB_Form_Files/Prints_odd_numbers_to_10.frm" > here </a>
to download a copy of this program.)

\begin{verbatim}
For i = 1 TO 10 Step 2
Print i
Next i
\end{verbatim}

The above examples print out numbers down a column. i.e. each number
is on a separate line. To print out numbers across a line (i.e. along
a row) you need to modify the Print command to

\begin{verbatim}
Print i,
\end{verbatim}

i.e. the comma is telling the programme to expect more output on that
line. The comma inserts a TAB character (which gives a fairly big
space). If you don't want such a big space between the numbers, you
could use

\begin{verbatim}
Print i;"  ";
\end{verbatim}

The semi-colon adds no extra space at all, so the {\tt ;"  ";} will
add just a few spaces between the numbers. Click
<a href="../VB_Form_Files/Prints_Numbers_on_one_line.frm" > here </a>
to get a programme which illustrates these Print commands.

{\bf You can get a program to repeat a similar task many times using the
{\tt For} loop.}

{\bf CHECKPOINT:} Write a program which prints out the numbers 10,9,8,
\ldots 1.

%}}} 
%{{{ 13. {\tt WHILE/WEND} Loops

\section{13. {\tt WHILE/WEND} Loops}
\label{sec:while}

Imagine that you want to check the tyre pressure for lorries and motor
bikes, as well as for four-wheeled cars. (See Sec.\ref{sec:for}.) The
algorithm to do this is something like:

\begin{verbatim}
CHECK IF THERE ARE MORE TYRES LEFT
MOVE TO NEW TYRE
MEASURE PRESSURE IN TYRE
GO BACK TO START
\end{verbatim}

As can be seen, the above program/algorithm keeps going around in a
loop so long as a certain condition is satisfied (i.e. so long as
there are more tyres to be checked). Basic has a loop in exactly this
style.

Consider the following program (note that {\tt str_My_Number} should
be the name of a text box):

\begin{verbatim}
My_Number = Val(str_My_Number)

i = 0

While i <> My_Number
i = i + 1
Wend

Print ``I think that your number is ``; i
\end{verbatim}

In this example, the loop begins with {\tt While} and ends with {\tt
Wend}. Inside this {\tt While} loop the variable {\tt i} is increased
by one each time through the loop. The {\tt While} loop stops when
{\tt i} is equal to {\tt My_Number}. Note that the symbol <> means
``not equal to'' (see \ref{sec:ifthen}). A working version of this
programme appears <a href=''../VB_Form_Files/While_Example.frm'' > here</a>.

You can see that in this case the {\tt For/Next} loop is of no use since
you {\em don't know in advance} how many times you want to go around the
loop.

{\bf {\tt While} loops are similar to {\tt For/Next} loops in that they are used
when the same lines of code need to be repeated more than
once. However {\tt While} loops are typically more flexible - the loop stops
when some condition is no longer satisfied.}

%}}} 
%{{{ 14. Outputting to a Data File

\section{14. Outputting to a Data File}
\label{sec:output}

If you have a lot of output from a program it is often useful to get
the programme to write this output to a file for later use, rather
than the screen. There are four steps to do this:

\begin{enumerate}

\item Firstly, the programme selects where the output file will be
written. This is optional, but if you don't specify the directory, it
defaults to the directory which the Visual Basic programming suite
sits in. When you start Visual Basic from the ``Programming
Languages'' directory, this default directory is hidden away in a
``systems'' directory deep down many sub-directories. However, when
you load a programme (i.e. form file) from blackboard) the default
directory is your desktop.
<a href=''../VB_Form_Files/Example_Output.frm'' >Here</a>
is an example form file which will output a number to a file on
your Desktop.

\item Secondly, it needs to ``open'' the file; i.e. tell the computer
that there is going to be a file used by the program;

\item Thirdly, it simply writes the variables to this file;

\item Finally, it closes the file (Visual Basic may get upset if you
don't do this...)

\end{enumerate}

These four commands are listed below:

\begin{verbatim}
ChDrive "P:"
ChDir "\My_Directory"

Open "EXAMPLE.DAT" For Output As #1
Print #1, X
Close #1
\end{verbatim}

Here the first two instructions {\em select the drive and the
directory} where the output file is to be written.  i.e. the {\tt
ChDrive "P:"} sets the drive to be the {\tt P:}  drive,
and the {\tt ChDir "My\_Directory"} sets the directory within that
drive to be {\tt My_Directory}.  Note that you must put the drive and
directory name inside quotation marks (i.e. the {\tt ChDrive} and {\tt
ChDir} must have a {\em string} following it).
Note also that these {\tt ChDrive} and {\tt ChDir} lines are both
optional. If you don't have them, then the {\em default} directory is
used (see above).

Then the computer is told to {\em open} the file {\tt EXAMPLE.DAT} and to
give this file a number {\tt \#1}.

The third command simply tells the computer to {\em write} out the value of
the variable {\tt X} to this file, i.e. to the file {\tt \#1}.

Finally the file is {\em closed}.

Note that in the example above, the file number was 1, but you could have
assigned almost any number to it. If you have more than one file open at
the same time, you will obviously have to refer to them by different numbers.

You can easily generalise the above example so that it outputs more data than
simply one number. The following example outputs 35 rows of data, each row
consisting of two columns.

\begin{verbatim}
Open "EXAMPLE.DAT" For Output As #5

For I = 1 To 35
Print #5, I, I^2
Next I

Close #5
\end{verbatim}


{\bf There are three steps to outputting to a data file: (i) Open the file;
(ii) Print to the file; (iii) Close the file. Optionally, you may wish to
specify which directory the file will be in before any of these steps.}

%}}} 
%{{{ 15. Inputting from a Data File

\section{15. Inputting from a Data File}
\label{sec:input}

Data can easily be read from a data file using analogous statements as
outputting to a file. i.e. there are four steps to do this:

\begin{enumerate}
\item Firstly, the programme defines where the input file is
(i.e. by specifying the drive and directory). This is optional, but if you
don't specify the directory, it defaults to the directory which the
Visual Basic programming suite sits in. When you start Visual Basic
from the ``Programming Languages'' directory, this default directory
is hidden away in a ``systems'' directory deep down many
sub-directories. However, when you load a programme (i.e. form file)
from blackboard) the default directory is your desktop.
<a href=''../VB_Form_Files/Example_Input.frm'' >Here</a>
is an example form file which will input a number from a file on
your Desktop.

\item Secondly you need to "open" the file;
i.e. tell the computer that there is going to be a file used by the
program;

\item Then you simply input the variable(s) to this file;

\item Finally you close the file (VisualBasic may get upset if you
don't do this...)

\end{enumerate}

These four commands are listed below:

\begin{verbatim}
ChDrive "P:"
ChDir "\My_Directory"

Open "EXAMPLE.DAT" For Input As #1
Input #1, X
Close #1
\end{verbatim}

Here the first two lines {\em set the drive and the directory} where
the input file is sitting.  i.e. the {\tt ChDrive "P:"} sets
the drive to be the {\tt P:} drive, and the {\tt ChDir
"My\_Directory"} sets the directory within that drive to be {\tt
My_Directory}. Note that you must put the drive and directory name
inside quotation marks (i.e. the {\tt ChDrive} and {\tt ChDir} must
have a {\em string} following it).
Note also that these {\tt ChDrive} and {\tt ChDir} lines are both
optional. If you don't have them, then the {\em default} directory is
used (see above).

The file is {\em opened} (or prepared to be input from) with the
{\tt Open} command.

Then the {\tt INPUT} command is used to {\em input} the variable
{\tt X} from the file.

Finally the file is {\em closed}.

You will note that the lines of code are exactly analogous to the
code which was used to do the outputting (see Sec.\ref{sec:output}).

A very common problem is to read in an numbers from a data file of unknown
length. The best method of doing this is illustrated below:

\begin{verbatim}
ChDrive "P:"
ChDir "\Test_dir"

Open "EXAMPLE.DAT" For Input As #7

While Not EOF(7)
Input #7, A,B
Wend

Close #7
\end{verbatim}

In the above {\tt EOF(7)} stands for "end-of-file 7". So the above
{\tt While} loop will continue to loop so long as the program has {\em
not} reached the end of the file. Note also, that in the case above,
{\tt EXAMPLE.DAT} must contain two columns of data.

{\bf CHECKPOINT:} Write a program which reads in two numbers {\tt A}
and {\tt B} from the data file {\tt SAMPLE.DAT} and then outputs their
average value to the file {\tt AVERAGE.DAT}.

<a href="../VB_Form_Files/Average.frm"> Here it is for you! </a>
(Note, you'll have to have a file called {\tt SAMPLE.DAT} with two numbers
in it on the same line for this programme to work.)


{\bf There are three steps to inputting to a data file: (i) Open the file;
(ii) Input from the file; (iii) Close the file.
Optionally, you may wish to
specify which directory the file will be in before any of these steps.

The {\tt While} loop (as shown above) is very useful to read in data from
a file of unknown length.}

%}}} 
%{{{ 16. Calculating the Sum of some numbers

\section{16. Calculating the Sum of some numbers}
\label{sec:sum}

Often we will want to calculate the following sum:
%
\[
Sum = \sum_{i=1}^{N} X_i \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;
                         \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\; (1)
\]
%
for example to calculate the average of some numbers.

Lets assume that the X's are stored in a data file.
The following code calculates the above sum:

\begin{verbatim}
Dim Sum, X As Double

Open "EXAMPLE2.DAT" For Input As #4

Sum = 0  ' This just makes sure that Sum is initialised to zero

While Not EOF(4)
Input #4, X
Sum = Sum + X
Wend

Print "The Sum of all the X = ", Sum

Close #4
\end{verbatim}

In the above, we firstly {\em declare} the variables {\tt Sum} and
{\tt X} as real numbers (specifically {\tt Double}) - see
Sec. \ref{sec:declare}. We then {\em open} the data file {\tt
EXAMPLE2.DAT} which has been prepared before to contain the numbers X
which we want to sum. ({\tt EXAMPLE2.DAT} should have all these X
values one per line.) The line {\tt Sum = 0} just initialises {\tt Sum}
just in case it has been used previously!

The {\tt While} loop (see Sec. \ref{sec:while}) is designed to read
in all the number in the file {\tt EXAMPLE2.DAT} until the end-of-file
is reached. Then comes the important line:

\begin{verbatim}
Sum = Sum + X
\end{verbatim}

If this is viewed mathematically, it looks a bit odd (it would imply
that {\tt X=0} !!). But what this really means is to calculate the
R.H.S.  (i.e. add {\tt Sum} to {\tt X}), and assign it to the variable
on the L.H.S., (i.e. {\tt Sum}). In the above case, the old value of
{\tt Sum} will be overwritten.

Each time through the {\tt While} loop, the variable {\tt Sum} will
accumulate another term, and, at the end of the loop, the Sum in
Eq.(1) will be calculated.

The above example can be generalised to calculating the following sum:
%
\[
Sum = \sum_{i=1}^{N} X_i^2
\]
%
by simply replacing the {\tt Sum = Sum + X} with {\tt Sum = Sum + X^2}.

{\bf If you need to calculate the sum of some numbers, then the code
above, or some generalisation of it, is the way to go.
}

%}}}
%{{{ 17. Picture Boxes

\section{17. PictureBoxes}
\label{sec:picture}

Start an entirely new project by going to the {\tt File} menu item,
and selecting the item {\tt New Project}. Now insert a {\tt CommandButton}
(from the {\em Tool Box} onto the blank form, and then insert a
{\tt PictureBox} as well. This is the icon on the {\em Tool Box} which looks
like a cactus plant!

You should adjust the size of your {\tt PictureBox} to make it quite big
(by dragging the corners). You may want to increase the whole form size itself
as well. Note that the name of this {\tt PictureBox} is {\tt Picture1}
by default, although, you can obviously change it to anything you want!
Also, you can set the background colour of the {\tt PictureBox} via
the {\tt BackColor} property in the {\tt PropertyBox}.

A {\tt PictureBox} is quite a powerful object. You can plot points, or draw
lines or other objects on it.

Now place a {\tt CommandButton} on the form. Double click on this
{\tt CommandButton} and insert the following code:

\begin{verbatim}
Private Sub Command1_Click()

Picture1.Scale (-100, 100) - (100,-100)
Picture1.FillStyle = 0
Picture1.FillColor = RGB(255,0,0)
Picture1.Circle (10, 20), 30, RGB(255,0,0)

End Sub
\end{verbatim}

In the above, the {\tt Picture1.Scale} line defines the size of the
{\tt PictureBox}. Specifically, it defines the top-left and bottom-right
of the {\tt PictureBox}. In the case above, we have defined a
{\tt PictureBox} whose x and y coordinates both run from -100 to +100.

The {\tt Picture1.FillStyle} line just ensures that any object (such
as a circle, etc.) are "filled-in" rather than just an outline.
To draw the outline only, use {\tt Picture1.FillStyle = 1}

The {\tt Picture1.FillColor} defines the colour of the object (note the
American spelling!!). In the case above, we have defined it via the
{\tt RGB} function - which stands for Red, Green, Blue. The argument
of the {\tt RGB} function run from 0 to 255. So, in the case above,
the colour chosen is going to be Red. (Note {\tt RGB(0,255,255)}
would be yellow, i.e. green + blue.)

Finally, the {\tt Picture1.Circle} line plots a circle (which is filled
in due to the two {\tt Picture1.Fill} lines) at coordinate position 
(10,20), with a radius of 30, and a colour of red.

There are many, many more {\tt PictureBox} commands (you would have seen them
listed when you typed in the {\tt Picture1.} commands in the above
example.

I'll list just some more which might be useful:

\begin{itemize}
\item {\tt Picture1.Cls} which clears the {\tt PictureBox} totally
\item {\tt Picture1.Pset (x, y)} which plots a single pixel
(i.e. a very small dot!) at the position (x,y)
\item {\tt Picture1.Line (x1, y1) - (x2, y2)} which plots a line
between the coordinates (x1,y1) and (x2,y2)
\end{itemize}

You can also print out text etc. to a {\tt PictureBox}:

\begin{verbatim}
Private Sub Command1_Click()

Dim b As Long
b=4

Picture1.Scale (-100, 100) - (100,-100)

Picture1.CurrentX = -30
Picture1.CurrentY = 50
Picture1.Print "I am writing this to a PictureBox, b = " & Str(b)

End Sub
\end{verbatim}

The above code places the text {\tt "I am writing this to a PictureBox, b = 4"}
on the {\tt PictureBox} starting at coordinates (-30,50). 
Note the use of the ampersand character & in the above to join two
strings together. This is exactly as in the Message Box case (see \ref{sec:msgbox}).

{\bf The {\tt PictureBox} is a very powerful way of producing graphics,
and plotting objects such as circles, lines etc etc.}

%}}}
%{{{ 18. Functions

\section{18. Functions}
\label{sec:functions}

Sometimes a particular piece of code may be needed in several parts of a
program. Rather than write it out every time it is needed, it is
convenient to write it in a special part of the program and refer to it
when needed. Consider the case above (see Sec.\ref{sec:maths})
where the solution of the
quadratic equation (i.e. $x=(-b\pm\sqrt{b^2-4ac})/2a$) is required at
several points in the program. It is convenient to place this in a
"function" as in the following:

\begin{verbatim}
' Calculates the solution of the quadratic equation

x = QuadSoln(a,b,c)
.
.
.
y = QuadSoln(d,e,f)
.
.
.
z = QuadSoln(g,h,i)
.
.
.


Function QuadSoln (a, b, c) As Double

QuadSoln = ( -b + Sqr(b^2 - 4*a*c) ) / (2*a)

End Function
\end{verbatim}

As you can see the program calculates the solution of three quadratic
equations. Each solution is handled by the same piece of code: {\tt
QuadSoln}. This is called a {\em Function}. Note that the {\tt Function}
must be defined as a particular variable type (in this case it is
a {\tt Double} or real number). Note also that the {\tt Function}
actually takes a value - so in this case it can be used inside a
mathematical equation. We say that a {\tt Function} returns a value
to the calling programme.

<a href=''../VB_Form_Files/Function_Example.frm'' >Here</a>
is an example programme using a {\tt Function} to find the minimum of
two numbers.

{\bf A {\tt Function} is a separate, self-contained piece of code
which can be called, or refered to by another part of the program, and
which returns a value to the calling part of the program.
They are very useful when the same piece of code is used many
times.}

%}}} 
%{{{ 19. Subroutines

\section{19. Subroutines}
\label{sec:sub}

{\tt Subroutines} are similar to {\tt Functions} (see \ref{sec:functions})
in that they are a separate piece of code that can be refered to from
elsewhere in the program. However, unlike {\tt Functions}, they do
{\em not} return a value to the calling part of the code.

There are some cases where the same piece of code is performed on
numerous occasions, but where a value is {\em not} passed back to the
main program. Consider the following example.

\begin{verbatim}
Input "Enter two numbers",a,b
Call Equal(a,b)
.
.
.

Sub Equal(a,b)

If a = b Then
   Print "a and b ARE EQUAL !!!!"
End If

End Sub
\end{verbatim}

In this program a {\em Subroutine} called {\tt Equal} is called which
then performs some instructions. When the computer reaches the {\tt
End Sub} command it returns to the main program just after the {\tt
Call Equal(a,b)} line. As you can see, {\em no value} has been passed
between the subroutine and the main program, unlike the case of
Functions (see \ref{sec:functions}).

<a href=''../VB_Form_Files/Subroutine_Example.frm'' >Here</a>
is an example programme using a {\tt Subroutine} to swap two numbers
around.

{\bf A {\tt Subroutine} is a separate, self-contained piece of code
which can be called, or refered to by another part of the program, and
which does {\em not} return a value to the calling part of the program.
They are very useful when the same piece of code is used many
times. They are also useful to structure your programme (i.e. make it
easier for someone else to understand).
}

%}}}
%{{{ 20. Arrays

\section{20. Arrays}

Often we may want to store and manipulate a large set of numbers (for
example the marks for a number of students in an exam). It is clearly
not convenient to give a new variable name to each student's mark, so
{\tt arrays} are introduced for this purpose. An array is just like a
vector; i.e. it has many {\em components}. Below is an example of a
program which uses arrays.

\begin{verbatim}
Dim Marks(100) As Double
Dim I, N As Long

' First the Marks are read in from a file

Open "Exam.dat" For Input As #2

N = 0

While Not EOF(2)
N = N + 1
Input #2, Marks(N)
Wend

' Then the sum of the Marks is calculated and the average found

Sum = 0

For I = 1 To N
Sum = Sum + Marks(I)
Next I

Print "The average mark is ", Sum / N
\end{verbatim}

The very first instruction {\tt Dim Marks(100) As Double} tells the
computer to set aside memory for an array called {\tt Marks} which
will have (a maximum of) 100 real-valued elements. Then the marks are
read from the file {\tt Exam.dat}. (See \ref{sec:input} for an
explanation of reading in data from a file using the {\tt While Not
EOF} statement.)  The next step in the code is to calculate the sum of
all the {\tt N} students marks using a {\tt For/Next} loop. (See
\ref{sec:sum} for an explanation of using the {\tt For/Next} loop to
sum up some numbers). Finally the average mark {\tt Sum / N} is
outputted to the screen.

{\bf CHECKPOINT:} Using the above examples, write a program which finds
the largest mark from data in the file {\tt Exam.dat}.

Note that it is possible to have more than one dimension in the array.
Consider the following:

\begin{verbatim}
Dim A(20,100,5) As Long

For I = 1 To 10
    For J = 1 To 100
        For K = 1 To 5
        A(I,J,K) = ...
        Next K
    Next J
Next I
\end{verbatim}

In this case, the array {\tt A} is a 3-dimensional array, and the elements
of A are accessed within the three nested {\tt For/Next} loops.
Note that the {\tt I} loop only goes up to 10, whereas the corresponding
dimension of {\tt A} (i.e. the first dimension) has a maximum value of 20,
i.e. you don't have to access all the elements of the array.

You can pass arrays to subroutines using the following. (Note, for
information on subroutines, see sec.\ref{sec:sub}.)

\begin{verbatim}
.
.
.
call add( x(), n, total )
.
.
.

sub add( x(), n, sum )

Dim i as Long

sum = 0.

For i = 1 To n
sum = sum + x(i)
Next i

end sub
\end{verbatim}

Note that in the above example that
\begin{itemize}

\item
the arguments of the subroutine {\tt add} include the array {\tt x}
and it appears with {\em empty parentheses}.

\item
the last argument of the subroutine is called {\tt total} in the
calling programme, but {\tt sum} in the subroutine itself. i.e. you
are allowed to call the arguments by a new name within the subroutine.

\end{itemize}

I've included a small programme which uses a subroutine call with
an array as an argument to find the minimum of that array. Click
<a href="../VB_Form_Files/Find_minimum.frm" > here </a> to download it.

{\bf {\tt Arrays} can be used as a convenient way of storing more than
one piece of data within a single variable name. They are the
computing equivalent of vectors or matrices. You can have arrays of
any data type: e.g. {\tt Double, Long, String} see \ref{sec:declare}.}

%}}} 
%{{{ 21. Horizontal and Vertical Scroll Bars

\section{21. Horizontal and Vertical Scroll Bars}

There are two more useful icons in the Toolbox that we haven't yet
investigated. These are the Horizontal and Vertical Scroll Bars
{\tt HScrollBar} and {\tt VScrollBar}. Move your cursor over the icons which
look like a rectangle with arrows at each end. (There is one
which is vertical and one which is horizontal.)

Now start a new project (which can be done by going to the {\tt File}
menu item in the VisualBasic environment, and selecting the
{\tt New Project} option!).

Place a command button and a {\tt VScrollBar} on the form.
Edit the {\tt Properties} of the {\tt VScrollBar} so that
its {\tt Max} is 100 and its {\tt Min} is 0.

Now enter the following code:

\begin{verbatim}
Private Sub Command1_Click()

Print Val(VScroll1)

End Sub
\end{verbatim}

When you run this program, before you click on the {\tt Command1}
button, move the position of the indicator in the {\tt VScrollBar}
to a new position. You will see the numerical value that the
{\tt VScrollBar} indicator is set at appear on the screen.

Note that instead of using {\tt Val(VScroll1)} you could equally
use {\tt VScroll1.Value}

<a
href=''../VB_Form_Files/Scroll_example.frm''>Here</a>
is another, slightly more sophisticated programme which prints out the
value of the scroll bar for you to play with!

{\bf {\tt HScrollBar} and {\tt VScrollBar} can be used
to input values into a program just like {\tt TextBoxes} (see
\ref{sec:textbox}). The obvious difference is that they provide a more
graphical/mouse based method compared with {\tt TextBoxes}.}

%}}}

\end{document}

