VB Lecture Notes - Assignment Statements
Objective #1: Use assignment statements to calculate and store mathematical results and to change the properties of objects.
- An assignment statement is a statement that is used to store a value into a variable or object's property.
- Assignment statements evaluate the mathematical expression on the right-hand side of the assignment operator and assigns the resulting value into the variable on the left-hand side
of the equals symbol (which is known as the "assignment operator").
- For example, the statement
numDonuts = 5
is an assignment statement that stores the value 5 into the variable named numDonuts.
Instead of a simple numerical value like 5, a more complicated mathematical expression can be typed on the right side of the equals symbol as in
totalCost = numDonuts * 2 * 1.06
where the right-hand side of the equals symbol must be simplified first before the final result is assigned to the variable answer.
- Never type an assignment statement with a mathematical expression on the left of the equals symbol ( e.g. )
since it causes a compile error. For example the following examples would cause a compile error
5 = totalCost
2 * numDonuts = totalCost
- An assignment statement can also store a numeric value into an Integer or Double variable as in the following examples
Dim numDonuts As Integer = 0
numDonuts = 5
or
Dim numDonuts As Integer = 0
numDonuts = Val(txtNumDonuts.Text)
- An assignment statement can also store a string value (which is a word or phrase) into a String variable as in the following examples
Dim name As String
name =
"Wyomissing"
or
Dim name As String
name = lblName.Text
- An assignment statement can also store a string variable or a literal string value into the Text property of an object such as a label:
lblName.Text = name
lblName.Text = "Wyomissing"
- The concatenation operator ( + ) can be used in assignment statements. For example,
lblName.Text = "Wyomissing" + " Area High School"
or
lblName.Text = firstName + " " + lastName
or
lblName.Text = "Mr. " + lastName
- You can assign the empty string (aka null string) to a string variable or the Text property of an object such as a label. For example,
name = ""
or
lblName.Text = ""
The empty string is represented as two double quote symbols typed next to each other with no space in between.
- You can even make an object disappear by using the Visible property in the following statement
lblMessage.Visible = False
The Visible property is used to make an object or invisible depending on certain conditions during a program's execution. Even though
a textbox with a Text Property, "You have won the game.", may be present on a form, it may be made invisible for the duration of a game. Then, only if the
user actually wins the game, would the Visible Property be changed to True in order for the user to know that he or she won the game.
- If a statement is cut-off along the right edge of the paper when a program is printed out, it is necessary to break up the statement so that it appears over two lines of code.
This can be done by typing the line continuation operator ( _ ) after a space anywhere next to an operator. The continued second line of code should be indented for good style. For
example, rather than
price = PRICE_PER_BOOK * numBooks + PRICE_PER_BOOK * numBooks * TAX_RATE
you could type out
price = PRICE_PER_BOOK * numBooks + PRICE_PER_BOOK * _
numBooks * TAX_RATE
Objective #2: Convert string values to numeric values.
- You must be careful distinguish between string data and numeric data (which includes Integer & Double).
For example, the string "13" is not equivalent to the number 13 just as the string "19610" (pronounced "one nine six one zero" like Wyomissing's zip code) is not equivalent to the number 19610 (pronounced "nineteen thousand six hundred and ten.")
- Double quotations are used to show that the "13" is being treated as a string value and therefore it should not be added, subtracted, etc. with a number. Wouldn't it be dumb to add 13 to your zip code!?
- With the Val function, one could change "13" into
13 as in
numBooks = Val("13")
or
numBooks = Val(txtNumBooks.Text)
- The CInt function can also be used
to change "13" into 13 as in
num = CInt("13")
There are some subtle differences between the Val and CInt functions however but you are not responsible for knowing these differences in this VB course.
Objective #3: Convert numeric values to string values.
- The Str function can be used to change
the numerical value 19610 into the string "19610" as in
Dim zipCode As String
zipCode = Str(19610)
- The ToString method can also be used
to change a numeric variable into a string. The statement
Dim num As Integer = 19610
Dim zipCode As String = "00000"
zipCode = num.ToString()
causes the string "19610" to be stored in zipCode. Notice the required empty parentheses after the ToString method.
Objective #4: Write a method that uses declaration and assignment statements.
- So let's say that you want to write a computer program that computes your grade for a class at school.First you must be able to compute
your grade by hand with a calculator or scratch paper. How can you train a computer to compute your grade if you do not know how to perform the algorithm yourself? So you add up the points earned
on all of your homeworks and tests and divide by the sum of the points possible for those assignments. This gives you your grade percentage. Okay, so how many numbers do you end up scribbling onto
your scratch paper as partial subtotals or intermediate calculations? Probably three. You added up the points earned as one subtotal. You added up the points possible as another subtotal. And, the
quotient that you calculated by dividing those two numbers was a third important number that you wrote down.
What would be three good, descriptive variable names for those three values and
are they whole numbers or decimal numbers? The variable names pointsEarned and pointsPossible would be good names for the first two and there data type should be Integer since they would always
be whole numbers. Do not use short variable names like x and y since you probably wouldn't remember what those cryptic names mean if you needed to update your program a few
years later. In fact, ask your math teacher sometime why you've been using x and y as varaible names in math class all of these years. Those problems don't seem to relate to the real world like computer
programs where every program has meaning and variable names that explain the purpose of a given program. The other variable could be named
gradeAverage and it should be a Double rather than an
Integer since it is likely to store decimal numbers.
Next you need to declare these variables with declaration statements and initialize them to the appropriate values.
Dim pointsEarned As Integer = 90
Dim pointsPossible As Integer = 100
Dim gradeAverage As Double = 0
Then you write one or more assignment statements to perform the calculation
gradeAverage = pointsEarned / pointsPossible
Finally you decide that you want to display the answer in a message box with the statement
MessageBox.Show(gradeAverage)
All of this code could be typed into the Click method of a button named btnCompute as in
Private Sub btnCompute_Click( )
Dim pointsEarned As Integer = 90 ' total pts earned
Dim pointsPossible As Integer = 100 ' total pts possible
Dim gradeAverage As Double = 0 ' student's grade average
gradeAverage = pointsEarned / pointsPossible
MessageBox.Show(gradeAverage)
End Sub
- It is usually possible to accomplish a task with many variables or with no variables! For example, the following two code segments
produce the same results
Short Version
lblAve.Text = Str((Val(txtScore1.Text) + _
Val(txtScore2.Text) + Val(txtScore3.Text)) / 3)
Long Version
Dim test1 As Integer = 0 ' student's 1st test score
Dim test2 As Integer = 0 ' student's 2nd test score
Dim test3 As Integer = 0 ' student's 3rd test score
Dim average As Double = 0 ' student's average test score
test1 = Val(txtScore1.Text)
test2 = Val(txtScore2.Text)
test3 = Val(txtScore3.Text)
sum = text1 + test2 + test3
average = sum / 3.0
lblAve.Text = Str(average)
There are a number of differences between the two code segments besides the obvious difference in length. The short version does not use any variables. Instead, it
computes the results by directly working with the textboxes and label. This saves minimal memory and with modern computers and mobile devices, it does not save significant memory to argue that it is worth avoiding the use of unnecessary variables. Using variables makes the code easier to read and undestand. Using vaiables also make it easier to maintain and upgrade a program in the future if a company hires you to add features to the software. The use of variables will make it easier to find the exact place in the code where you need to add something new.
The use of variables in the long version also gives the programmer the opportunity to document and explain each of the variables with extra comment statements that furthermore make the program easier for others to understand.
For example, in the long version, it is not understood that it is a student's test scores that are being averaged. Someone could look at the short version and reasonably guess (incorrectly) that 3 bowling game scores are being averaged together. The long version is nicely spaced out as well making the code easier to read and
analyze. In summary there are at least 4 reasons why the long version is better than the short version:
1. easier to read
2. more organized
3. easier to upgrade
4. easier to debug
- Assignment statements can be used to overwrite the values stored in variables as the program executes from top to bottom.
Dim x As Integer = 1
Dim y As Integer = 2
Dim result As Integer = x + y
lblResult.Text = Str(result) ' lblResult contains 3
x = 5
lblResult.Text = Str(result) ' lblResult still contains 3 not 7
intResult = x + y
lblResult.Text = Str(result) ' lblResult now contains 7
Some students mistakenly believe that result is initially tied to the formula x + y. This is incorrect since only the current values stored in x and y are used to create the sum that's
initially stored in result.
Objective #5: Trace code that uses variables and assignment statements.
- When a method executes the code inside the method executes from top down. First variables are declared. Then the variables usually take on values that come from text boxes where the user typed in numbers. This is followed by calculations. Lastly, the final values are displayed in labels.
Here's an example,
' computes the cost of purchasing donuts
Private Sub btnCompute_Click(...)
' *********************** declaration statements *******
Dim numDonuts As Integer = 0 ' # of donuts purchased
Dim totalCost As Double = 0 ' total cost of purchases
Const PRICE_PER_DONUT As Double = 0.75 ' price per donut
Const TAX_RATE As Double = 1.06 ' PA state sales tax
' ********************* obtain user input **************
numDonuts = Val(txtDonuts.Text)
' ********************** calculations ******************
totalCost = numDonuts * PRICE_PER_DONUT * TAX_RATE
' ********************** display the output ************
lblTotalCost.Text = "$" + Str(totalCost)
End Sub
In this example, the variables are declared and set equal to zero in the Dim declaration statements. Since the variable numDonuts was declared with the data type Integer, the value typed into the textbox named txtDonuts must be converted to an Integer with the Val command. The assignment statement
totalCost = numDonuts * PRICE_PER_DONUT * TAX_RATE
executes "from right to left". That is, the value obtained from multiplying numDonuts times PRICE_PER_DONUT times TAX_RATE is stored (i.e. assigned into) the variable named totalCost. Note that multiplying an integer (numDonuts) with a decimal number (PRICE_PER_DONUT) and another decimal number (TAX_RATE) will likely result in a decimal number. That is why the data type for totalCost must be Double so that it can store a decimal number.
Next, the decimal number stored in totalCost must be converted to a String. This is due to the fact that it is going to be stored in the label named lblTotalCost. Label's can only store strings and since totalCost is a number it must be converted to a String with the Str command. Also, it needs to be concatenated with the "$" string.
- "Tracing a code segment" means that you analyze and follow the code from top-down keeping track of the values stored in the variables along the way. You need to be able to predict the output that will be displayed. This is an important skill for any computer programmer since it is the typical way that you find logic mistakes in your program.
Trace the following code segment and predict the output:
Dim numDonuts As Integer = 0
Const PRICE_PER_DONUT As Double = 1.50
Const DISCOUNT As Double = 0.75
Dim totalCost As Double = 0
numDonuts = 2
totalCost = numDonuts * PRICE_PER_DONUT - DISCOUNT
lblTotalCost.Text = "$" + Str(totalCost)
The output that shows up in the label named lblTotalCost.Text is: ______________________________