| |
|
|
| |
|
|
| |
| |
|
Basic data types in VB 2005
Integers:
Byte (1 byte)
Short or Int16 (2 bytes)
Long or Int32 (4 bytes)
Int64 (8 byte)
Strings and characters:
Boolean (2 bytes)
Date (8 bytes)
Notice that strict type checking does not allow implicit conversion
between data types in cases where data might get lost (may implicitly
convert from Short
to Long, but not
from Long to Short).
Control flow
Loops:
Say 'Hello world...' five times:
Public Class Hello
Shared Sub Main()
Dim i As Short
For i = 1 To 5 Step 1
System.Console.WriteLine("Hello World...")
System.Console.WriteLine()
Next i
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Exit")
System.Console.ReadLine()
End Sub
End Class
Nested For loop: multiplication table:
Public Class Hello
Shared Sub Main()
Dim i, j As Short
For i = 1 To 10 Step 1
For j = 1 To 10 Step 1
System.Console.Write(CStr(i * j) + " ")
Next j
System.Console.WriteLine()
Next i
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Exit")
System.Console.ReadLine()
End Sub
End Class
Do While loops:
Say 'Hello, world...' five times:
Public Class Hello
Shared Sub Main()
Dim i As Short = 1
Do While i <= 5
System.Console.WriteLine("Hello, World...")
System.Console.WriteLine()
i = i + CShort(1)
Loop
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quite.")
System.Console.ReadLine()
End Sub
End Class
Nested Do While loop: multiplication table:
Public Class Hello
Shared Sub Main()
Dim i, j As Short
i = 1
Do While i <= 10
j = 1
Do While j <= 10
System.Console.Write(CStr(i * j) + " ")
j = j + CShort(1)
Loop
System.Console.WriteLine()
i = i + CShort(1)
Loop
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quite.")
System.Console.ReadLine()
End Sub
End Class
Decide if a number is prime (make sure you understand the logic of the code below. For instance, note that is_prime() returns a Boolean):
Public Class Hello
Shared Sub Main()
Dim count As Short = 1
Dim number As Integer = 1
Do While count <= 100
If is_prime(number) = True Then
System.Console.WriteLine(CStr(count) + ": " + CStr(number))
count = count + CShort(1)
End If
number = number + 1
Loop
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quite.")
System.Console.ReadLine()
End Sub
Shared Function is_prime(ByVal number As Integer) As Boolean
Dim Root As Double
Dim i As Integer
If number < 4 Then
Return True
End If
If number Mod 2 = 0 Then
Return False
End If
Root = Math.Sqrt(number)
For i = 3 To CInt(Root) Step 2
If number Mod i = 0 Then
Return False
End If
Next i
Return True
End Function
End Class
Notice how the above program is not very efficient; e.g., it checks dividing by 9, 15 , 21, etc., even after division by 3 fails.
Arrays:
Memory construct to hold a 'row' of variables of identical type; e.g. 10 shorts
Dim i(9) as Short
Gives you 10 shorts all addressed by referring to i.
Note!!! the 9 in Dim i(9) denotes the upper bound of the array!
How to get to individual ones? Index into the array using a subscript.
i(1) = 45
i(2) = 45
Store and print the first 100 multiples of 2:
Public Class Hello
Shared Sub Main()
Dim i(99), j As Short
For j = 0 To 99 Step 1
i(j) = CShort(2) * (j + CShort(1))
Next j
For j = 0 To 99 Step 1
System.Console.Write(CStr(i(j)) + " ")
Next j
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quite.")
System.Console.ReadLine()
End Sub
End Class
Notice how the array element subscripts start at 0 (as in C/C++/Java) and how this forces us to add 1 to j when doing the arithmetic.
Also note how VB 2005 forces us to explicitly convert 1 and 2 into shorts using the CShort() function.
What happens when you violate the bounds of your array:
When reading: garbage results (try it!).
When writing: who knows?
Public Class Hello
Shared Sub Main()
Dim table(9,9), i,j As Integer
For i = 0 To 9 Step 1
For j = 0 To 9 Step 1
table(i,j) = (i+1) * (j+1)
Next j
Next i
For i = 0 To 9 Step 1
For j = 0 To 9 Step 1
System.Console.Write(CStr(table(i,j)) + " ")
Next j
System.Console.WriteLine()
Next i
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quite.")
System.Console.ReadLine()
End Sub
End Class
By reference: a reference to the array is passed (this is
how you pass arrays in C; by means of a pointer/address): Fill a small
array in Main();
then pass it to a subroutine to have each of its elements doubled:
Public Class Hello
Shared Sub Main()
Dim i(4), j As Short
For j = 0 To 4 Step 1
i(j) = CShort(2) * (j + CShort(1))
Next j
For j = 0 To 4 Step 1
System.Console.Write(CStr(i(j)) + " ")
Next j
do_this(i, 4)
For j = 0 To 4 Step 1
System.Console.Write(CStr(i(j)) + " ")
Next j
End Sub
Shared Sub do_this(ByRef num() As Short, ByVal length As Short)
Dim i As Short
System.Console.WriteLine()
For i = 0 To length Step 1
num(i) = num(i) * CShort(2)
Next i
End Sub
End class
By value: an array of references back to the elements in the original is passed. This is not possible in C: same code as above; just change ByRef into ByVal.
Notice!! Works either way but is not at all the same!!! Passing an array ByVal generates an array with references to the elements of the original array on the receiving end (weird!!), whereas passing the array ByRef generates a single reference back to the array held by the caller. There is almost never a good reason to pass an array ByVal.
Passing a two-dimensional array to a subroutine where it's printed out (notice the notation for receiving this array in the subroutine):
Public Class Hello
Shared Sub Main()
Dim table(9,9), i,j As Integer
For i = 0 To 9 Step 1
For j = 0 To 9 Step 1
table(i,j) = (i+1) * (j+1)
Next j
Next i
print_them_out(table)
End sub
Shared Sub print_them_out(ByRef table(,) as Integer)
Dim i, j as Short
For i = 0 To 9 Step 1
For j = 0 To 9 Step 1
System.Console.Write(CStr(table(i,j)) + " ")
Next j
System.Console.WriteLine()
Next i
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quite.")
System.Console.ReadLine()
End Sub
End Class
array_name.GetUpperBound(array_dimension_for_which_the_upper_bound_is_needed)
I/O: Input Output: Getting external information to and from your program:
Write() and WriteLine() are output functions. Information is sent from your program to an output device, in this case, the console window.
Programs read from (input) and write to (output) so-called I/O streams. I/O streams can be 'hooked up' to a device, e.g., printer, file, port, etc.
Example: Get an integer from the keyboard and print it to the console:
Public Class Hello
Shared Sub Main()
Dim i As Short
System.Console.WriteLine("give me an integer")
System.Console.WriteLine()
i = CShort(System.Console.ReadLine())
System.Console.WriteLine()
System.Console.WriteLine("You gave me: " + CStr(i))
System.Console.WriteLine()
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quit.")
System.Console.ReadLine()
End Sub
End Class
The string version:
Public Class Hello
Shared Sub Main()
Dim str As String
System.Console.WriteLine("give me a name")
System.Console.WriteLine()
str = System.Console.ReadLine()
System.Console.WriteLine()
System.Console.WriteLine("You gave me: " + str)
System.Console.WriteLine()
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quit.")
System.Console.ReadLine()
End Sub
End Class
Create both an in.txt file and an out.txt file and place them in C:\temp\. Include an integer on the first line of in.txt.
Public Class Hello
Shared Sub Main()
'Declare two streams (FileStream) for the input and output files:
Dim InFile As IO.FileStream
Dim OutFile As IO.FileStream
Dim my_int As Short
'Declare StreamReader and StreamWriter for reading and writing:
Dim Reader As IO.StreamReader
Dim Writer As IO.StreamWriter
'Open the streams by hooking them up to the files:
InFile = New IO.FileStream("c:\temp\in.txt", IO.FileMode.Open, IO.FileAccess.Read)
OutFile = New IO.FileStream("c:\temp\out.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
'Connect the StreamReader and StreamWriter to the streams:
Reader = New IO.StreamReader(InFile)
Writer = New IO.StreamWriter(OutFile)
'Read And Write the integer from and to the Reader/Writer
my_int = CShort(Reader.ReadLine())
Writer.WriteLine(CStr(my_int))
'Close the Reader and Writer
Reader.Close()
Writer.Close()
End Sub
End Class
Now go check the files!
Note the line continuation characters. (_)
Note the comment lines. (')
Exception/Error Handling
What to do if the input file c:\temp\in.txt is not present?
Remove c:\temp\in.txt and rerun the program. What do you observe?
Unhandled Exception: System.IO.FileNotFoundException
Program dies!
Notice that there is no error in the code itself; the problem is that the code does not cover for this situation.
Golden rule of programming: Your program should never die.
Include exception detection and handling in your code:
Public Class Hello
Shared Sub Main()
Dim my_int As Short
Dim InFile As IO.FileStream
Dim OutFile As IO.FileStream
Dim Reader As IO.StreamReader
Dim Writer As IO.StreamWriter
Try
InFile = New IO.FileStream("C:\temp\in.txt", IO.FileMode.Open, IO.FileAccess.Read)
Catch Ex As Exception
System.Console.WriteLine("Error opening 'in' file...")
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quit.")
System.Console.ReadLine()
System.Environment.Exit(1)
End Try
Try
OutFile = New IO.FileStream("C:\temp\out.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
Catch Ex As Exception
System.Console.WriteLine("Error opening 'in' file...")
System.Console.WriteLine()
System.Console.WriteLine("Press Enter to Quit.")
System.Console.ReadLine()
System.Environment.Exit(1)
End Try
Reader = New IO.StreamReader(InFile)
Writer = New IO.StreamWriter(OutFile)
my_int = CShort(Reader.ReadLine())
Writer.WriteLine(CStr(my_int))
Reader.Close()
Writer.Close()
End Sub
End Class
Notice the Try ... Catch ... End Try blocks.
Notice how we return the exit status of the program to the OS (nonzero for programs that run into a 'lethal' exception).
Notice that hardwiring the absolute path of the file in the code is bad!!! It is done here for demonstrative purposes only. Always!!! write your code so that it is entirely independent of the local file/machine system.
The Visual Studio.NET Debugger
As in most integrated development environments (IDEs), VS 2005
contains a debugger for stepping through code and for inspecting the
contents of variables and memory as the program runs.
When you 'build' your VB 2005 program, debug information is
automatically linked into your code; i.e., the compiler registers the
various instructions to particular lines in the source file. Although
you can run the debugger stand-alone, it is handy using it from inside
the IDE.
To run your program in the debugger, first decide where in your code
you want to interrupt its execution. In the IDE, click your left mouse
button at the very beginning of that line (in the narrow, gray,
vertical band at the left of the text editor) and notice how the line
is now marked as a so-called 'breakpoint.' You
can set multiple breakpoints.
To now activate the debugger select Start Debugging from the Debug
menu. The application will run but execution will be interrupted as the
debugger reaches one of your breakpoints. At this point you can mouse
over your variables and have their value displayed. For more complex
variables, such as arrays, you can have them displayed by selecting
them with the mouse and then selecting the QuickWatch... option from
the Debug menu.
Changed the first sentence to reflect new commands.
Once you're ready to move on to the next set of instructions, you have
several options:
Debug --> Continue will continue execution until the next breakpoint is reached.
Debug --> Step Over will execute the next line of code, but not debug it; i.e., if the next line of code is a function or subroutine call, the function will be executed in its entirety.
Debug --> Step Into
will execute the next line of code and debug it; i.e., if the next line
of code is a function or subroutine call, the debugger will act as if
the first line of code in the function or subroutine has a breakpoint
on it.
Debug --> Stop Debugging
will quit the debugger (you must stop debugging before you can edit
your source code).
!!! Make sure you feel at home
with the VS 2005 debugger. It is a very powerful tool
for diagnosing runtime problems. Without it, finding the causes
of these problems is very, very laborious. !!!
Practice exercises
In case you would like to train yourself using the above VB 2005
language constructs, try one or more of the following exercises:
Prompt your user for how many Fibonnaci numbers (0, 1, 1, 2, 3, 5, 8, 13, ...) to compute, then compute them and calculate the average ratio between adjacent numbers (should be close to 1.61804).
Write an HTML multiplication table. Prompt your user to give you the dimensions for the multiplication table (e.g., 10x10, or 5x5, or 10x5). Your program builds an HTML page containing the multiplication table and writes it to a file. Pick it up with your browser to see if the HTML is correct.