Programming for Computing 07 - 08

Chapter: Built-in Functions

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 5.0

VB has a wide range of functions ready for use - the VB help has details, and some of them are listed below Also you may write your own functions (similar to procedures).

You have already used these functions: InputBox, CStr, CInt, CDbl

The general form of a function call is:


   someVariable  =  functionName(parameter1, parameter2,   etc....)
though - as you will see - we sometimes use the result directly, without storing it anywhere. If the function needs no parameters (also known as arguments) then you just use the function name followed by empty ( ) )

The parameters are inputs to the function, which produces a result. A function call is also an expression, so we must handle the result in some way - e.g. store it.

However, VB is not very uniform - there are differences in how we call functions. For example, for mathematical functions (sqrt, sin, cos etc) we precede the name by Math. (Math is the name of a collection of related functions)


x = Math.sin(y)

For functions which manipulate strings, the string comes before the function name.


s = myName.Substring(2,3)
Some 'functions' are provided as properties.

n = myName.Length       'nb you have seen the 'dot' notation before
Here are some examples, using sqrt, length and substring.

   Dim s as string
   dim n as integer
   dim j as integer
   dim x as double

   ' sqrt - square root - one parameter, numeric result
   i = Math.sqrt(9)                 ' i is 3
   i = Math.sqrt(4)+Math.sqrt(9)          ' i is 5

   ' below, the inner sqr() is evaluated first
   x = Math.sqrt( Math.sqrt(4)  )               

     

    'Substring - returns a substring from  a longer string
    '  - it has 2 parameters:
    '     the starting position to extract from.  (the first chracter is numbered 0 )
    '     the length of the extracted string
    'NB the string to be worked on precedes the Substring
    'Examples:
    dim s as string = "position"     'NB p is at 0, o is at 1, etc
    dim answer as string
    answer = s.Substring(2, 3)       ' answer becomes sit



    'Length of a string - how many chars it contains
    dim s1 as String = "Sheffield"
    n = s1.Length                 ' n is 9
With function calls, you can imagine them being evaluated by replacing the function name and parameters with the result - inner ones first, so:

    n = Math.sqrt( Math.sqrt(16)) +1
is processed behind the scenes like:

    n = Math.sqrt(   4    ) +1
    n =            2        +1
    n=          3
 


Section 5.1

new (added stuff on rounding, formatting)

List of common functions

There are hundreds, so here is a small selection of ones you might find useful. They are shown by example.

'some vars for the examples:
Dim i,j as Integer
Dim s, s1 as String
Dim a,b as Double
a = 2.34
b = 5.67
y = Math.cos(a)        ' cosine - also sin, sqrt, tan
i = Math.Max(a, b)   ' max of 2 values  - also Min
i = Math.Round(a)    ' rounds to nearest int - i.e. Math.Round(3.4) is 3
a = Math.PI          ' not a function -  a constant  (a becomes 3.141...etc)


'random numbers - needs 2 steps:
'do this once, just under the 'Class Form1 ...' line
Private myRandom As Random = New Random() 
'then do   
i = myRandom.Next(1,11)   ' i is a random number from 1 to 10 inclusive
i = myRandom.Next(1,11)   ' and another one



'strings
s= "  hello there!    "
s1 = s.SubString(2,3)
i = s.Length
s = s1.ToLower()      'convert s1 to lower-case.    Also ToUpper
s = s1.Trim()         ' trim  (remove) spaces from each end of s1
If IsNumeric(TextBox1.Text) then ..etc   ' test if a string holds a number

'position of substring (if s="guitar", then i is 4.  i=-1 if not found)
i = s.IndexOf("a") Then ...
   
If s.StartsWith("www.") Then ...etc  'if s starts with "www."  Also EndsWith

'formatting results:
Dim d as double = 3.56789
   s = String.Format("{0:n3}", n)     ' nb curly brackets
   messageBox.show(d)    ' displays 3.568  - i.e rounds to 3dp

d = 3.567
j = math.Floor(x)   ' j is 3  - truncates - rounds down
 


Section 5.2

problems - using functions

1. Here is an example. Calculate the square root of 23.4

Private Sub Button1_Click(etc...    )
dim n as Double
dim answer as Double
n = 23.4
answer = Math.sqrt(n)
MessageBox.Show("Result is " &  answer)
End Sub
For this very small problem we don't even need variables:

Private Sub Button1_Click(etc...   )
MessageBox.Show(CStr( sqr(23.4)))           
End Sub
Now do:

A square office space is advertised as 3000 sq metres. How long is a side? (Do it the long way, using variables.)

2. Ask the user to enter their name, thenm display the first and last letters of the name, in 2 text boxes. (Use substring).  


Section 5.3

Key Points

Rather than diving in to a problem and coding it all, use VB help - or google - to look for existing functions which might be useful.

Module Admin   Contents, Index