Numeric expressions with constants

Before reading this note, read the notes on data types and data type conversion functions. Computers work with many types of data, but in this note we restrict ourselves to numeric data. Let's start with a simple example of a numeric expression: 7 + 3.

The value of this expression is 10. Note that when the computer evaluates an expression, it boils it down to a single value. (Recall that all expressions, no matter how complex, have a single value). The expression consists of two numeric operands, 7 and 3, and the arithmetic operator +. VB has other numeric operators, including:

Operator Meaning
+ addition
- subtraction
* multiplication
/ division
\ integer division
^ exponentiation

Run our demonstration program illustrating numeric expressions using constants. As you see, it evaluates and displays the values of several numeric expressions. The following is a listing of the event handler for clicking on the "Evaluate some numeric expressions" button:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

   'expressions using the +, -, *, /, ^, and \ operators
   Label1.Text = "3 + 4"
   Label2.Text = CStr(3 + 4)
   Label3.Text = "(3 + 4) * 2 - 1"
   Label4.Text = CStr((3 + 4) * 2 - 1)
   Label5.Text = "4 ^ 3"
   Label6.Text = CStr(4 ^ 3)
   Label7.Text = "19 / 4"
   Label8.Text = CStr(19 / 4)
   Label9.Text = "19 \ 4"
   Label10.Text = CStr(19 \ 4)

  'expressions with floating point results
   Label11.Text = "7 / 2"
   Label12.Text = CStr(7 / 2)
   Label13.Text = "1 / 3"
   Label14.Text = CStr(1 / 3)

  'a long expression
   Label15.Text = "3 + 14 / 2 + 6 - 4 + (8 - 2) * 2"
   Label16.Text = CStr(3 + 14 / 2 + 6 - 4 + (8 - 2) * 2)

End Sub

Study the event handler, and the values of the expressions displayed by the program. If any are unclear, ask someone for an explanation. You can experiment with numeric expressions by writing a small program like the one above.

Note that the even numbered assignment statements use the CStr function to convert the numeric result to a string which can be assigned to the Text property of the corresponding label.

Note that the program contains explanatory comments. Comments are preceded by an apostrophe ('), and are ignored during execution. They are solely for the benefit of people reading the program.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.