Programming for Computing 07 - 08

Chapter: Variables and assignment, strings, message box, text box

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

 


Section 3.0

Introduction

Conceptually, a variable is like a box with a unique name, into which we can place a value. Lower down in the program, we may then refer to the box by its name. So, a variable gives the program a 'memory' like the memory in a calculator. In a program, we can create as many variables as we need. Here, we will look at the rules for introducing variables into a program, but the hard part is deciding which variables are required - it depends on practice, experience, and a knowledge of similar examples.

Why do we do this...

The use of variables and assignment is probably the most common task that a programmer does. You must know about data types (e.g. strings, whole numbers, decimal numbers etc) and you must know how to write programs that are easier for other programmers to modify. The use of meaningful names can assist here.  


Section 3.1

Declaring Variables

Here is an example of declaring a variable, and placing a value in it. Run it by creating a new project, and placing a button on the form.

Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    Dim mark As Integer         (integer means 'whole number' see below)
    mark = 50
End Sub
(Recall that VB creates the Private Sub... and the End Sub - do not type them in.)

Explanation:

  • Dim (short for dimension, but it really means 'declare') introduces your chosen variable name (we chose mark). Integer means 'whole number' (our value will not need a decimal point) Integer is the TYPE of the mark variable here.
  • Next we used = to store a value in the variable (the storage box) named mark.

Here is another example, involving a person's weight in kg. This would need a decimal point type, known as double in VB, as in


Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    Dim weight As Double
    weight = 56.1
End Sub
Now try this:

Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    salary = 23000
End Sub
what is wrong? Try this:

Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    Dim pay As Double
    pey = 24000
End Sub
what is wrong? Does VB spot the typo?

Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    Dim n As Double
    Dim n As Double
End Sub
error? why?  


Section 3.2

VB and errors

The vb system spots many errors at 'compilation-time' - i.e. the checking phase, before it runs your code. It underlines them in a blue wavy line. Hover the mouse to see more info.

In general, run-time errors are harder to spot. For example, setting pay to 14000 instead of 24000.  


Section 3.3

Numeric Variables - Integer, Double

There are two main classes of numeric variable:
- integer
- double (known as float, 'real' or 'floating-point' in other languages.)

Normally, choose integer for exact, whole-number quantities, e.g:
- the number of students in a class.
- the number of locations in a computer's RAM memory.
- the number of lines on a VDU screen.

Choose double for 'decimal-point' quantities, e.g:

- your height in metres.
- average of several integer numbers.
- mass of an atom.

The capacity of these types is large:

  • an integer can hold values up to 2000 million
  • a double can hold values to around 15 decimal places, and up to 10308. But note that double values are not exact. For example the answer to 20/3 is 6.666666 recurring. When we chop this off after 15 digits, we make it inaccurate. Integers are totally accurate, though. Choose the type based on your knowledge of the problem.
 


Section 3.4

String variables and joining them with &

Briefly, a string can hold a sequence of characters, and its size is practically unlimited. We use double quotes to contain string values, and can use & to join them together end-to-end (jargon: concatenate). For example:

Dim first as String = "Mike "
Dim last as String
Dim myName as string

last = "Parr"
myName = first & last                  ( myName  set to  "Mike Parr")
 
Sometimes, students get confused between variable names and values. For example: 'A program is used by a person named John...' They try to put:
John = ...            or
name = John
In fact, it is probably:
name = "John"
("John" is a value, just like 2.345 is a value).  


Section 3.5

Meaningful Names

As in all programming languages, there are certain rules about how we are allowed to express variable names. In VB, the rules are:
- they can contain only letters or digits, or the _ underscore
- they must start with a letter.
- they can be as long as we like. Here are some illegal names:

3times,  payin£,  tax-rate,   exam mark
Rather than put exammark, we put examMark We shall use this style to make names more readable: i.e. capitalise the start of words within a name, but not the first letter.

gotTheIdea      -    ?
Use meaningful names! Your program may be read by other programmers, who need to understand its logic as quickly as possible. Meaningful names will help - e.g:

examMark
rather than
	em,  m,  emk.
Case-sensitivity: in Java, you can decare 2 variables named examMark and exammark. They are different variables. Java is sensitive to the capitalisation.

In VB, you cannot do this. However, if you put:


Dim examMark As Integer
exammark=50
Then vb will reformat the second line to:

examMark = 50
i.e it re-capitalises the name, and also puts spaces round =. This means that once you have declared an item correctly, you can type it in without having to use the shift key. VB does it for you. neat!

 


Section 3.6

Several declarations in one Dim

If you wish, you can put:

Dim length, width As Integer
This declares 2 integers. You might also put

Dim length As Integer
Dim width As Integer
Most people adopt the second approach, declaring each variable in a separate Dim.

 


Section 3.7

Declaring AND initialising at the same time

Rather than put:

Dim count As Integer
count = 0
It is neater to put

Dim count As Integer = 0
You cannot always do this - often, we don't know the initial value of a variable (for example, the user might enter the value as the program runs.)

 


Section 3.8

Variables and storage boxes

We can imagine a variable as a storage box, which has a name, and has a value. The value can change as the program runs. A simple calculator has 2 'variables' - a display, and a memory. Their values can change during a session of calculations.
[varassig1.jpg]
Assigning a value to a variable

 


Section 3.9

Who is 'The User' ? - not you!

In the questions, I say things like 'write a program that asks the user to enter...'
In general, you write programs for other people (users) to use. Your choice of meaningful variable names is nothing to do with users. The names make it easier for yourself and other programmers to understand your code.

The user will never see the code.

What the user will see though, are messages which explain answers, or ask them to do things. Consider how we might ask the user for their weight. Here are 4 ways:


Weight?                              (what about it?)
Enter data:                          (what data - age? height?)
Type weight:                         (units?)
Type weight in Kg:
The final one is clearest.

Similarly, the user must be able to understand the results. We should ensure that some text is alongside any output, as in this 'bonus' result:


550                                  (what is it?  What units)
£550                                 (better)
Bonus:  £550                         (best)
When we do textboxes in more detail, you will see how this can be done.  


Section 3.10

Using ' for comments

You know how some people scribble annotations in the margin of a book, to clarify understanding? We can do the same in all languages. In VB, use ' - the single quote - as in:

' some example declarations
Dim x As Double   ' one example
Dim y As Double    ' and another one
Anything to the right of ' is to clarify the meaning - it is up to you what to put. We can also use blank lines to separate sections of code. Normally, we do not comment every line - we just comment sections of code (explaining what the whole section does ) and we comment intricate bits. (In notes however, lecturers sometimes put extra comments, to explain things to beginners. You would not see this in industry.)  


Section 3.11

MessageBox, and Joining Strings with &

Here, we look at making messages clear to the user.

We will make extensive use of strings when inputting and displaying data. Here is how we can make the messageBox clearer to the user:


Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
Dim salary As Integer
salary = 23000
MessageBox.Show("I get £" & salary & "  per year")
End Sub
Run it. The result is:

I get £23000 per year
Note the spaces inside the quotes, to space out the text. The messageBox can only deal with one item. We have built up this string by joining three smaller ones:

"I get £"
the value of  salary
" per year"
Remember that in real life, the user is not you or another programmer. The user does not want to see messages which mention variable names, or messages which contain unexplained numbers.

To display a numeric variable without any accompanying text, we have to convert it to a string, using CStr(), as in:

MessageBox.Show( CStr(salary))
 


Section 3.12

Problems - variables and message boxes

1. In your Button1_click section, declare some meaningfully-named variables to hold:
- your salary
- your house number
- your shoe size
- your IQ

Place typical values in them with = , and use messageBox to display them, with meaningful messages.

 


Section 3.13

Using Text boxes for output

What if we want to display some result in a form, rather like:

    Area of room is  xxx  Sq Metres
where xx is the value of a variable. We can think of the message as 3 items, and can use 3 text boxes, as in:
[threetextboxes.jpg]
Output with several text boxes

VB gives names for the text boxes, but the naming depends on the order in which you place them on the form.

The Text property of 1 and 3 can be set on the design form, using the Property List at the right of the screen. We can set them here, because they never change. However, we need to set the Text property of TextBox2 at run-time, as in:


Private Sum Button1_Click(etc...)
Dim area as Double

...calculate area - to do

TextBox2.Text = CStr(area)
Incidentally, TextBox2 is a rather meaningless name for something that will display an area. We might rename the control to e.g. areaTextBox. We don't need to rename the other textboxes, because we never refer to them in the program code.

An alternative to using 3 boxes it to use one box, and join the 3 items with &. This is not as neat. (You can see this with message boxes, above.)  


Section 3.14

Problems - TextBoxes

Declare variables for age and height. Give them suitable numeric values, and display them using several boxes in this way:

You are xxx years old, and are yyy  metres high
 


Section 3.15

Displaying Multiline text in a TextBox: AppendText, VbCrLf, Clear

Choose a textbox from the list of controls in the toolbox. Put it on the form, and resize it to roughly 2 inches square.

We intend to put several lines of text into the textbox, so you need to modify the properties. Note that VB has named it TextBox1 for you.

  • set its Scrollbars property to Both
  • set its Multi-line property to True
Look at this program:
Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    TextBox1.AppendText("AA" & "CC" & "CC")
End Sub
If you run it, the text box shows:
AABBCC

Now run this one:

Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
    TextBox1.AppendText("AA" & "CC" & VbCrLf & "CC")
End Sub
Now, it displays:
AABB
CC

We see that AppendText puts data into a text box. The data in (...) can be just the same as the message box, except we also plan for multiple lines, e.g::
  • strings in "..."
  • strings joined with & (if & is used with a numeric variable, the variable gets converted to a string behind the scenes.)
  • variables
  • VbCrLf - stands for 'VB carriage return, line feed' - a shorthand way of saying - 'move to the start of the next line'.
Here are some examples:

    Dim age As Integer=22
    Dim name as string = "Dylan "

    TextBox1.AppendText(name & "my age is " & age & VbCrLf)
    TextBox1.AppendText("I am " & age & " years old")
    TextBox1.AppendText(CStr(age))         'nb CStr converts to  a string
Note: the program displays:
Dylan my age is 22
I am 22 years old22

How would you get the final 22 on a line by itself?
  • AppendText means to add text at the end of what is in the text box already
  • use vbcrlf to get an end-of-line inserted. If you get all your text on one long line, you have missed this!
  • Text boxes display strings, so TextBox1.AppendText(age) is wrong, because age is an integer, not a string. Note the use of CStr(...) to convert something to a string.

    However, TextBox1.AppendText(name) does not need CStr, because the name variable is a string already.

The last thing you need to know, is that you can clear (empty) a textBox with:

TextBox1.Clear
 


Section 3.16

Problems - variables and multi-line text box

do the 'Problems - variables and message boxes' but this time use a multi-line text box.  


Section 3.17

The assignment statement =

= stores the value of anything on its right into the variable on its left. For example:

mark = 50
The thing on the right can involve numbers, variables, operators (such as +,- *, / etc). Example:

Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
' set up some variables for the example
Dim mark As Integer
Dim deduction As Integer
Dim total As Integer

mark = 50
deduction = 10
total = mark - deduction
MessageBox.Show("Final total is: " & total)

End Sub
run it.

How it works:


total = mark - deduction
         50          10
on the right of = , values are looked up. 40 is calculated.

The second step is to store 40 into total (mark and deduction are unchanged.)

Whatever was stored in mark before is wiped - it is 'overwritten' by 40.

What if we put


mark = mark + 1
The same process happens. The right hand side works out to 51.

The next step is to store 51 into mark. This 'add 1 to a variable' concept is very common in programming.  


Section 3.18

Debugging / tracing / break points - F8 (F11)

Using the above program, we will 'step' it a line at a time, and inspect the current values of variables.

Instead of running, press the F8 key. The program runs but a line at a time. Each further F8 moves on one line. (You may find that your version of VB uses F11 key).

You will see a line highlighted in YELLOW. This line is ABOUT to be executed.

Hover the mouse over a variable name to see its current value.

At times, you may need to click a button on your form to continue. Practice it!

We are tracing through the program. This can help you find errors (to debug it) when variables do not have their expected value.

Note that - for the first press of F8, you need to click the button on your form. Also, when the 'end sub' line is reached, you need to click on Form1 on the task bar at the bottom of the screen to continue with the program.

Sometimes - with longer programs - the error might require a lot of F8 presses to get to where you want. To get round this, you can put a BREAK POINT near the problem area, and then just run the program normally, at full speed. When it reaches the break point, it pauses, and lets you use f8 to step slowly. You place a break point by clicking at the very left of the line of code - a circle appears. Click the circle if you want to remove it.  


Section 3.19

problems -with + - * /

In each program, display the answers in both a text box and in message boxes (you would not nomally use both - it is just for practice). In fact the choice of message box or text box depends on the problem.
  1. Declare two variables: deductions and salary as doubles. Place suitable values in them. The program should display the salary, the deductions, and the amount after deductions are subtracted.
  2. Declare double variables for a student's income per month, and the amount spent on food, drink, clothes, rent (5 variables in all). Make up values. Display their values, and display the amount that the student has left after spending.
  3. Pi is 3.141 approx. We have a 12" diameter pizza . If 3 people share it, how many sq inches do they get each?
  4. A camera memory card holds 256 megabytes. One photo takes up 1.3 megabytes. How many photos can I fit on a card?
 


Section 3.20

Assignment with control properties

We have used variables, as in

Dim n As Integer
n = 4
n = n + 1
etc
Here, n is a simple double item. But a control (e.g. a button or a label ) is not so simple. It has lots of properties, such as its height, its colour, the text it is displaying, the font of the text ... In programming, such a thing is known as an object, and we use the 'dot' notation to say which property we want to use.

Each property is often a simple thing, such as an integer.

Here is an example. Put a button on a form, then double-click on it to get to the code editor. Enter the following code (between private and end-sub), giving:


Private Sub Button1_Click(ByVal sender...etc  ( VB creates this line )
Dim n As Integer
n = 100
n = n + 10
' sizes are in  pixels
Button1.Height = Button1.Height + 50  'add 50 to height property

End Sub

run it - note that we can manipulate the Button1.height property in a similar way that we can manipulate n. (Later we will look at VB controls in more details.)  


Section 3.21

Problems - controls

  1. Enhance the program to add 50 to the width as well, and to display the current width and height in two messageBoxes.
  2. Look at the other properties of a button, and make the button move to the right at the same time as it gets bigger.
 


Section 3.22

More on Variables - Expressions

Here we provide more detail on operators + - * / and some new ones. Expressions are introduced here via assignment statements, but in fact the expression is allowed in many other contexts - it is an important concept. In general:

	variable = expression
'=' should be read as 'becomes', NOT 'equals'. An expression can be a simple number, or a calculation. here we look at the rules for calculations.  


Section 3.23

Arithmetic Operators

The above examples assumed you would guess what '+' meant, and it does indeed represent addition. It is an example of an arithmetic operator, and the complete set is:
  • + addition
  • - subtraction
  • * multiplication
  • / division
  • \ integer division
  • Mod : integer remainder of integer division
  • ^ exponent - 'to power of '
Consider the expression:

6+4*2
Does it result in 20 or 14 ?

In fact, VB follows the algebra convention in performing multiply before add, so the result is 14. The priority of calculation is

  • innermost brackets ( ) first - see below.
  • ^
  • * / \ Mod next
  • + - last.
If all the operators have the same priority, left to right order is used.

fixed The \ means: integer division. It only works on integer numbers or variables. It truncates (downwards), as in:


dim a as integer = 11
dim x as integer
x = a \ 6          ' x is 1
x = a \ 11         ' x is 1
x = a \ 4          ' x is 2

Most programming tasks don't involve a rote conversion of algebraic formulae into VB assignments, but let's have a look at tricky areas:

AlgebraVB
(a) y=mx+c y = m*x+c
(b) x=(a-b)(a+b) x = (a-b)*(a+b)
(c) y=3[(a-b)(a+b)]-x y = 3*((a-b)*(a+b))-x
(d) y=1-2a
       3b
y = 1-(2*a)/(3*b)
(e) a=-b a = -b
(f) a=sin x a = sin(x)

In (a) and (b) the * is not assumed, as it is in maths.

In (c), we are forced to use () in every case.

In (d), if we had written 2*a / 3*b , this would have divided by 3 then multiplied by b.

In (e), we have used - for negation.

In (f), we use the standard(built-in) function sin(). These are covered later. The appendix lists all the built-in functions.

To complete our look at the arithmetic operators, let us look at integer division, and the MOD remainder (or modulo ) operator. We can find what the integer remainder is by:


	a = 3 Mod 2		‘ a becomes  1
	a = 3 Mod 3		‘ a becomes  0
Typical use of mod: convert 371 pennies into separate pounds and pence

'all vars are integer
pence=371
pounds = pence \ 100   ' integer divide - gives 3 exactly
penceLeft=pence Mod 100  ' remainder  71
For integers, VB gives a decimal place result, so 7/3 gives 2.333333333333

 


Section 3.24

problems - expressions

1 What are the final values of a,b,c after the following assignment statements? (work it out on paper first, the run the code with F8 to check)

Dim a, b, c As Integer
a = 1
b = 2
c = 3
a = b+c
a = a+1
b = a
b = a+b*10
c = b Mod 10

Key Points

Variables and the assignment ( = ) statement occur in all languages.

Module Admin   Contents, Index