Friday, February 29, 2008

If Statements and Strings

We are able to compare strings using If statements. This means that we can see if two strings are the same string [i.e. "george" = "george"], but more importantly we are able to compare the relationship between strings. That is, we can tell if a certain string comes before another string:

Dim strA, strB As String
strA = "cat"
strB = "dog"

If strA < strB Then
MsgBox(strA & " comes before " & strB, "")
ElseIf strA > strB Then
MsgBox(strA & " comes after " & strB, "")
Else
MsgBox(strA & " equals " & strB, "")
End If


Gives answer of "cat comes before dog"

One important thing to remember, however is that capital letters come before lowercase letters. This is because of the ASCII/ANSI coding of each letter in the computer.

The computer does not understand the word "cat" as we humans do. For the computer each letter has a binary value [binary = 1's and 0's]. Letters are given numbers in sequential order from 65-90 for A-Z and 97-122 for a-z. Since the capital letters have lower values, they are less than the lowercase letters and therefore "come first."


Dim strA, strB As String
strA = "cat"
strB = "Zebra"

If strA < strB Then
MsgBox(strA & " comes before " & strB, "")
ElseIf strA > strB Then
MsgBox(strA & " comes after " & strB, "")
Else
MsgBox(strA & " equals " & strB, "")
End If


Gives answer of "Zebra comes before cat"

If you want to eliminate case, you can use the .ToUpper and .ToLower functions.

If / ElseIf / Else [Continued]

We learned in class that If statements could be more complicated than just one case or the other. We learned that there may be more than one thing that we want to check, and we can do this by using a different If/ElseIf/Else structure:

If condition1 Then
'Do these statements for condition 1
ElseIf condition2 Then
'Do these statements for condition 2
Else
'Do these default statements
End If


We also learned that there can be several ElseIf statements before hitting the final Else.

More Boolean Operators
We learned that we can check more than one relationship at a time by combining them using one of two special operators:

Operator            Example
And 0 <= x And x <= 10
Or 0 <= x Or x <= 10
Not Not ( x = y )


The And operator is only true if both conditions on either side are true. If either side is false, then the entire combined expression is false.

The Or operator is different, because it only need one of the expressions to be true in order for the entire expression to be true. So if one side is true then the entire expression is true, and if both sides are false then the entire combined expression is false.

Truth Tables
We can make truth tables in order to clarify these expressions.

Suppose we use x to represent Condition 1 and y to represent Condition 2. So we have the following relationships:


+-----+-----+--------+----------+----------+
| x | y | Not x | x And y | x Or y |
+-----+-----+--------+----------+----------+
| T | T | F | T | T |
+-----+-----+--------+----------+----------+
| T | F | F | F | T |
+-----+-----+--------+----------+----------+
| F | T | T | F | T |
+-----+-----+--------+----------+----------+
| F | F | T | F | F |
+-----+-----+--------+----------+----------+


T represents True
F represents False

So if the conditions x and y are combined with an And operator, the entire combined condtion is only true if both x and y are True [T]. We can see this in the table above. And of course: x And Not x results in a column of all False entries.

Also, anytime that x or y are True and are combined with an Or operator the entire combined condition is True. We can see this relationship in the table as well.

Not is an operator that takes the current condition and makes its value the opposite. That is, if a condition is True then Not condition makes it False.

Thursday, February 28, 2008

If Statements

We are covering If Statements this week. Let's see how if statements work:

If condition Then
'Do these statements
Else
'Do these alternate statements
End If


The condition is what we have to check, and if it is true then we do the statements that are immediately inside the If statement, otherwise we do what is in the Else statement. An English pseudocode example could be:

If It's sunny outside Then
'Go play frisbee outside
Else
'Stay inside and read
End If


Of course this is only an English example and will not make sense to the computer in this format.

Operators
Most often what we are trying to figure out has to do with relationships of things. For example, we had a calculator problem with a potential bug of division by 0. We could use If statements to decide If we are trying to divide by 0. In order to do this, we need to use some boolean operators. These operators allow us to figure out the relationship between two things, for example, is a number larger than another number, smaller than the other number or equal to it?

Our operators are:

= Equal to
<> Not Equal to
< Less Than
> Greater Than
<= Less Than or Equal to
>= Greater Than or Equal to


These operators compare the item on the left to the item on the right and return True if the relationship is true or False if the relationship is false. The items that we compare could be Numbers or Strings.

Therefore, if we want to see if a number is Equal to another number (in this case zero) we would use the equals operator. If num2 is equal to zero then we output an error message, otherwise we do the division (which is not shown here):

If num2 = 0 Then
MsgBox("Division by zero error!",,"ERROR")
Else
'Do Division
End If


Now we have a piece of code that we can use, or modify if we like. We could have used a different method by using the Not Equals Operator:

If num2 <> 0 Then
'Do Division
Else
MsgBox("Division by zero error!",,"ERROR")
End If


This says that if num2 is NOT equal to zero then do the division, otherwise output an error message.

Note: We do not have to have an Else with each If statement. We could just write:

If num2 <> 0 Then
'Do Division
End If


But nothing happens if a division by zero is attempted. The user might like to know why nothing happened, especially if they accidentally wrote 0 instead of another number like 10

In the next class we will go over this longer example.

String formatting

As promised, here are the notes on section 3.5 Input/Output (by Alex)
________________________________________________________________

Formatting:

There are various ways of formatting output in VB. One way is with some more built in functions:

FormatNumber( number or variable to format, places to round )

This will take a number and format it to a certain number of decimal places. Below is an example of using this function:

FormatNumber( 12345.628, 2) will evaluate to 12,345.63
FormatNumber( 444212.333, 0) will evaluate to 444,212

FormatCurrency( number or variable to format, places to round )

This will take a number and format it to a currency value to a certain number of decimal places. Below is an example of using this function:

FormatCurrency( 12345.628, 2) will evaluate to $12,345.63
FormatCurrency( 345.4426, 3) will evaluate to $345.443

FormatPercent( number or variable to format, places to round )

This will take a number and format it to a percentage value to a certain number of decimal places. Below is an example of using this function:

FormatPercent( 0.185, 2) will evaluate to 18.50%


Now, notice with the Percent and Currency function, the appropriate symbol is added to the outputted value. There are other Format functions available but these are again the most frequently used.

To format a string output, you use something called zones. Since I cannot draw once again, I will have to refer you to the textbook example 1 in section 3.5. But here is how the formatting variable will look:

Dim fmtStr As String
fmtStr = "{0,15}{1,8}{2,9}"

Here is how that looks. Notice that there is no spaces between the curly braces inside the string. Also notice each section has two numeric values. The first value is the zone number so in the above example they would be 0...1...2. The second value is the number of spaces to format so these would be 15...8...9. Here is how to use it in a program:

lstOut.Items.Add( String.Format( fmtStr,item 1, item 2, item 3 ) )

The number of items in the above line needs to match the number of zones you declare in the formatting string. Again, see example 1 for the full diagram as well as a short program.

Monday, February 11, 2008

String Lecture notes (from Alex)

I am available for tutoring in A205. My schedule is posted online at the department's website.
_____________________________________________________________________________

Formally, a string is a sequence of characters that can be treated as a single item. In other words, anything and everything together. Here are some examples:

"34huwnacbui23h4r"
"The quick brown fox."
"My name is: John Doe"

Here is how to declare a string variable:

Dim varName As String

By default, the string variable is automatically set to empty, or Nothing.

(See example 1 in 3.4 for a basic example)

For the purpose of the HW assignment (37-40 in section 3.4), you were gathering certain information from textboxes. Again, by default, anything you gather from a textbox is a stored as a string. So as a brief example, say you entered a number and tried to place it in the appropriate variable. This will not work since a string cannot be placed into a variable declared of a numeric type. There is a way to fix this. In VB, there are built-in functions that will correctly convert a string to a number or certain other variable types. Below are some examples of that:

CDbl() -- means Convert to a double. This is the most commonly seen conversion function in the textbook since most variables are declared as a Double type. This will convert the string entered into a double.

CInt() -- means Convert to an integer. Will take a string and convert to the Integer type.

CLng() -- means Convert to a Long integer. Will take a string and convert to the Long type.

CStr() -- means Convert to a String. Yes, there is a function that will "go the other way" so to speak. This will be used for output purpose mostly though there may be an occasion to use for input purpose.

Below is a short program to demonstrate some conversion functions:

Private Sub btnAdd_Click(...) Handles btnAdd.Click

'This program will gather two numbers from the user and output the sum
Dim num1, num2, sum As Double

num1 = CDbl(txtNum1.Text)
num2 = CDbl(txtNum2.Text)

sum = num1+num2

txtOut.Text = CStr("The sum is: " & sum)

End Sub

Now, just one note from the above program. In the last line, you see a & symbol. This is called the concatenation symbol. It will join two or more pieces of data together. So in this case, the user will see the following message in the textbox if the sum was 7: The sum is: 7 Concatenation will be seen quite frequently for the rest of the semester.

(See example 3 for an example of concatenation).

STRING FUNCTIONS:

In VB, there are certain functions that you can apply to strings. Below are some examples using them. For the purpose of all the examples below, use the following definition of a string:

Dim str As String

str.Length()
-will return the length of a string as an integer. Say the string was "Hello". You will get an answer of 5.

str.ToUpper()
-will change the string to all uppercase characters (not numbers or symbols). Say the string is "Hello James 1234!", the function will change this to "HELLO JAMES 1234!"

str.ToLower()
-just the opposite of ToUpper()

str.Trim()
-will eliminate all the white spaces at the front and end of a string. Say the string is " Hello "
Applying this function, you will get "Hello"

The following two functions contain something called parameters (explained more in chapter 4). These are data values that are required for the function. Also, these functions require the knowledge of how a string looks in memory. Since I cannot draw with the blog, I will do my best to show it. The pipe symbol | will be used to separate the individual characters:

Say you declare a string variable and give it the value, somewhere in the program, "John". Here is how it would look:

J | o | h | n | \0
0 | 1 | 2 | 3 | 4

The numbers appearing below the string are called indices's. They are the "position" of the certain character. The \0 is called the terminating character or the null string. This is basically the end of the string. So let's look at the function:

str.IndexOf( string ) OR str.IndexOf( string, starting position ).

This function will return the index of the FIRST OCCURRENCE of a string you give it to find. If it cannot find it, it will give you -1. So let's use the string "fanatic". Looking at it in memory (this is the best I could do):

f | a | n | a | t | i | c | \0
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7

Let's apply the function.

str.IndexOf("ati") will give you an answer of 3 since the first occurrence of this string begins at position, or index of 3.

str.IndexOf("a") will give you an answer of 1 since the first occurrence of this string begins at position, or index, 1.

str.IndexOf("nt") will give you an answer of -1 since this string does not exist!

str.IndexOf("a", 4) will give you an answer of -1 since starting at position 4, there is no matching string.

Now let's look at the following function called the sub string:

str.SubString( starting position, how many places to move ) OR str.SubString( starting position )

This function will now return a portion of a string instead of the index of a portion of a string. If you do not specify the second parameter, it will go all the way to the end of a string. So now let's use the "fanatic" string again.

str.SubString( 0, 3 ) will return "fan" since beginning at position 0 and going 3 places you get "fan"

str.SubString( 4, 2) will return "ti" since beginning at position 4 and going 2 places, you get "ti"

str.SubString( 4 ) will return "tic" since beginning at position 4 and going to the end you get "tic"

(See example 5 in 3.4 for a great example of the previous string functions).

For what we covered on Input Boxes and Message Boxes, please refer to the end of that chapter since I cannot draw on the blog. If there are any concerns about them, please let me know next week.

Monday, February 4, 2008

Chapter 3.3: Numbers

We went over numbers in the second to last class. We also learned about listboxes. A listbox is an object in which we can add things (like a list) one line at a time. There are two actions that we learned with listboxes:

listbox1.Items.Add( ... )
listbox1.Items.Clear()

Note: With the .Add() feature, the item that is to be added to the listbox is in the parentheses. Therefore we can add numbers to the listbox by placing them in the parentheses of .Add().

.Clear() simply erases whatever is in the listbox.

Example:

lstResults.Clear()
lstResults.Items.Add(8)
lstResults.Items.Add(4+3)
lstResults.Items.Add(3*9)


First the listbox is cleared (erased) with the Clear() statement. Then we will see the following:

8
7
27

Notice that the mathematic expressions are evaluated before the answer is printed.

Built-in Functions

We learned about some mathematical functions that we can use to make calculations easier:

  • Math.Sqrt()
  • Int()
  • Math.Round()


Math.Sqrt() returns the square root of the mathematical expression placed in the parentheses.

Int() returns the lower bound integer value of the mathematical expression in placed in the parentheses.

Math.Round() returns the upper bound real value of the mathematical expression in placed in the parentheses. We are able to specify the number of decimal places we would like to round the value to as well.

So the following code:

listbox1.Items.Add( Math.Sqrt( 16 ) )
listbox1.Items.Add( Math.Round( 9.2675 ) )
listbox1.Items.Add( Int( -9.2675 ) )

would yield the following results:

4
9.268
-10

Also remember that we can place any mathematical expression in the parentheses so we could even evaluate things as complicated as:

Math.Round( Math.Sqrt(19*20)/50+79, 3 )

Variables
A variable is just a name for a place in memory that we can use as temporary storage. We learned that we could use variables to store numerical values in order to make our arithmetic operations more flexible.

First we must declare the variable:

Dim varname As Type

varname can be any name we choose as long as it:
  1. begins with a letter
  2. uses legal characters such as letters, numbers and underscores
  3. is not used somewhere else in the program. For example the name of a form or listbox


The Type must also be given when the variable is declared. There are two types for numbers: Integer and Double. The type must be given when a variable is declared so that the compiler will know how much memory to allocate for the variable, and every type has a different amount of memory that it needs.

So here is an example declaration:

Dim num As Integer

You will notice that the intellisense menu will pop up as you are declaring variables.

Sunday, February 3, 2008

Installation of VB Studio

You can go to:

http://msdn2.microsoft.com/en-us/vstudio/aa718407.aspx

and click on Download and save the executable. After it finishes downloading double click the executable file to install Visual Studio 2005.

The system requirements are listed on the right-hand-side of the page. Installation should work with default choices. Make sure that you register your installation so that you can keep using it for the semester. You can use fake information if you like, though I think you have to use a real email address to get the registration key.

Feel free to email me if you have problems.