ELECTRICAL ENGINEERING DEPARTMENT SULTAN HAJI AHMAD SHAH POLYTECHNIC 1 List of Visual Basic data types and the range of values each one can contain.
2 2.1 Data Type Data Type Value Range Boolean True or False Byte 0 to 255 (unsigned) Char A single Unicode character Date 0:00:00 (midnight) on January 1, 0001, through 11:59:59 p.m. on December 31, 9999 UNIT 2: VISUAL BASIC FUNDAMENTALS Data Type Value Range Decimal 0 through +/ 79,228,162,514,264,337,593,543,950,335, with no decimal point; +/ 7.9228162514264337593543950335, with 28 places to the right of the decimal. Use this data type for currency values Double 1.79769313486231570E+308 through 4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values Integer 2,147,483,648 to 2,147,483,647 (signed). This is the same as the data type Int32. 3 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS Data Type Value Range Long 9, 223,372,036,854,775,808 to 9,223,372,036,854,775,807 (signed). This is the same as data type Int64. Object Any type can be stored in a variable of type Object. SByte 128 through 127 (signed) Short 32,768 to 32,767 (signed). This is the same as data type Int16. 4 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS Data Type Value Range Single 3.4028235E+38 through 1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values String 0 to approximately 2 billion Unicode characters UInteger 0 through 4,294,967,295 (unsigned) ULong 0 through 18,446,744,073,709,551,615 (1.8...E+19) (unsigned) UShort 0 through 65,535 (unsigned) 5 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS Helpful guidelines for using data types: To store text, use String data type. The String data type can be used to store any valid keyboard character, including numbers and non-alphabetic characters. To store only the value True or False, use the Boolean data type. To store a number that doesn't contain decimal places and is greater than 32,768 and smaller than 32,767, use the Short data type. To store numbers without decimal places, but with values larger or smaller than Short allows, use the Integer or Long (long integer) data types. 6 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS Helpful guidelines for using data types: To store numbers that contain decimal places, use the Single data type. The Single data type should work for almost all values containing decimals, except for incredibly complex mathematical applications or need to store very large numbers. In that case, use a Double. To store currency amounts, use the Decimal data type. To store a date and/or a time value, use the Date data type. When you use the Date data type, VB recognizes common date and time formats. Eg. if you store the value 7/22/2008, VB doesn't treat it as a simple text string; it knows that the text represents July 22, 2008. 7 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS Helpful guidelines for using data types: Different data types use different amounts of memory. To preserve system resources, it's best to use the data type that consumes the least amount of memory and still provides the ability to store the full range of possible values. Eg. if you're storing only the numbers from 1 to 10, use a Short instead of a Long.
8 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS The Object data type requires special attention. If you define a variable or array as an Object data type, you can store just about any value you care to in it; VB determines what data type to use when you set the variable's value. Object data types take up more memory than the other data types. VB takes a little longer to perform calculations on Object data types. Unless you have a specific reason to do so and there are valid reasons, such as when you don't know the type of data to be stored ahead of time don't use the Object data type 9 2.1 Data Type UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables A variable is an element in code that holds a value. We might create a variable that holds the name of a user or the user's age, for example. Each variable (storage entity) must be created before it can be used. The process of creating a variable is known as declaring a variable. Each variable is declared to hold data of a specific type, such as text (called a string) for name or a number for age. When we reference a variable's name in code, VB substitutes the variable's value in place of the variable name during code execution (at runtime the moment the variable is referenced.) Variables can have their values changed at any time.
10 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Declaring Variables The act of defining a variable is called declaring (sometimes dimensioning), which is most commonly accomplished using the keyword Dim (short for dimension).
Dim variablename As datatype Example:
11 Dim Number As Integer UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables An example of a variable declaration is
This statement creates a variable called strFirstName. This variable is of type String, which means that it can hold any text you choose to put into it. 12 Dim strFirstName As String UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables We don't have to specify an initial value for a variable It is a useful feature of VB to create a new String variable and initialize it with a value, eg, you could use two statements like this:
If you know the initial value of the variable at design time, you can include it in the Dim statement, like this:
13 Dim strName As String strName = Alibaba Dim strName As String = Alibaba" UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Note: all data types have a default initial value. For the string data type, the value is "Nothing" Empty strings are written in code as "". For numeric data types, the default value is 0; the output of the following statements would be 2:
14 Dim sngMyValue As Single Debug.WriteLine (sngMyValue + 2) UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Passing Values to a Variable The syntax of assigning a literal value such as 6 or six") to a variable depends on the variable's data type. For strings, you must pass the value in quotation marks, like this:
For Date values, you enclose the value in # symbols, like this:
For numeric values, you don't enclose the value in anything:
15 strCollegeName = POLISAS" dteBirthDate = #7/22/1969# intAge = 42 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Using Variables in Expressions Variables can be used anywhere an expression is expected. Eg. The arithmetic functions, operate on expressions. You could add two literal numbers and store the result in a variable like this:
In addition, you could replace either or both literal numbers with numeric variables or constants, as shown here:
16 intSum = 2 + 5 intSum = intFirstValue + 5 intSum = 2 + intSecondValue intSum = intFirstValue + intSecondValue UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variables are a fantastic way to store values during code execution, and you'll use variables all the time from performing decisions and creating loops to using them as a temporary place to stick a value. Remember to use a constant when you know the value at design time and the value won't change. When you don't know the value ahead of time or the value might change, use a variable with a data type appropriate to the variable's function 17 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope Constants, variables, and arrays are useful ways to store and retrieve data in VB code. Hardly a program is written that doesn't use at least one of these elements. To properly use them, however, it's critical that you understand scope.
18 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope Code is written in procedures and procedures are stored in modules. Scope refers to the level at which a constant, variable, array, or procedure can be "seen" in code. For a constant or variable, scope can be one of the following: Block level Procedure level (local) Module level Global (also called namespace scope)
19 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 1. Block Scope (or Structure Scope) - a variable dimensioned within a structure, is given a structure scope. - Structures are coding constructs that consist of two statements, eg. If..Then statement, Do..Loop Statement If expression Then statements to execute when expression is True End If
20 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 1. Block Scope (or Structure Scope) Do statements to execute in the loop Loop - If a variable is declared within a structure, the variable's scope is confined to the structure; the variable isn't created until the Dim statement occurs, and it's destroyed when the structure completes. - If a variable is needed only within a structure, consider declaring it in the structure to give it block scope 21 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 1. Block Scope (or Structure Scope) - Consider the following example:
- By placing the Dim statement within the If structure, you ensure that the variable is created only if it's needed.
22 If blnCreateLoop Then Dim intCounter As Integer For intCounter = 1 to 100 ' Do something Next intCounter End If UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 2. Procedure-Level (Local) Scope. A constant or variable declared within a procedure, has procedure-level or local scope. Most of the variables created will have procedure scope. A local constant or variable can be referenced within the same procedure, but it isn't visible to other procedures.
23 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 2. Procedure-Level (Local) Scope. If a local constant or variable is referenced from a procedure other than the one in which it's defined, VB returns a compile error; to the procedure making the reference, the variable or constant doesn't exist. It's a best practice to declare all local variables at the top of a procedure, but VB doesn't care where we place the Dim statements within the procedure. Note that if you place a Dim statement within a structure, the corresponding variable will have block scope, not local scope. 24 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 3. Module-Level Scope Constant or variable with module-level scope, can be viewed by all procedures within the module containing the declaration. the constant or variable doesn't exist to procedures in all other modules. To create a constant or variable with module-level scope, the declaration is placed within a module but not within a procedure. There is a Declarations section at the top of each module. Use module-level scope when many procedures must share the same constant or variable and when passing the value as a parameter is not a workable solution.
25 UNIT 2: VISUAL BASIC FUNDAMENTALS Variable Scope 4. Global (Namespace) Scope A global scope (or namespace scope) constant or variable can be seen and referenced from any procedure, regardless of the module in which the procedure exists. One common use of a global variable is storing a reference to a database connection so that all code that needs access to the database can do so via the variable. Creating global constants and variables is similar to declaring module- level constants and variables. Global constants and variables must be declared in a module's Declarations section, just like module level constants and variables. The difference between a module-level declaration and a global-level declaration is the use of the keyword Public. 26 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 4. Global (Namespace) Scope To declare a global constant, begin the constant declaration with the word Public: Public Const MyConstant As Integer = 1 To dimension a variable as a global variable, replace the keyword Dim or Private with the word Public: Public strMyVariable as String
27 UNIT 2: VISUAL BASIC FUNDAMENTALS Working with Variables Variable Scope 4. Global (Namespace) Scope To create a constant or variable of global scope, you must declare the constant or variable in a standard module, not a class-based module. We can't have two variables of the same name in the same scope, but we can use the same variable name for variables with different scope. when referencing the variable name in the procedure containing the local variable, VB would use the local variable. When accessing the variable from another procedure, the local variable is invisible, so the code would reference the global variable
28 UNIT 2: VISUAL BASIC FUNDAMENTALS Understanding Constants a constant represent an identifier having a specific value at design time, and that value never changes throughout the life of your program. Constants offer the following benefits: 1. They eliminate or reduce data-entry problems 2. Code is easier to update 3. Code is easier to read
29 UNIT 2: VISUAL BASIC FUNDAMENTALS Understanding Constants Constant definitions have the following syntax:
Const name As datatype = value
Example: Statement to define a constant to hold the value of pi
Const pi As Single = 3.14159265358979
30 UNIT 2: VISUAL BASIC FUNDAMENTALS Understanding Constants After a constant is defined, we can use its name in code in place of its value. For example, to calculate the value of Circle_area, we use:
Using the constant is much easier and less prone to error than typing this:
31 Circle_area=pi*radius^2 Circle_area=3.14159265358979 * radius^2 UNIT 2: VISUAL BASIC FUNDAMENTALS Naming Convention To make code more self-documenting and to reduce the chance of programming errors, you need an easy way to determine the exact data type of a variable or the exact type of a referenced control in VB code.
32 UNIT 2: VISUAL BASIC FUNDAMENTALS Naming Convention 1. Using Prefixes to Denote Data Type.
33 Data Type Prefix Sample Value Boolean bln blnLoggedIn Byte byt bytAge Char chr chrQuantity Date dte dteBirthday Decimal dbc decSalary Double dbl dblCalculatedResult Integer int intLoopCounter Long lng lngCustomerID Object obj objWord Short sho shoTotalParts Single sng sngMortgageRate String str strFirstName UNIT 2: VISUAL BASIC FUNDAMENTALS Naming Convention 1. Denoting Scope Using Variable Prefixes
In particularly large applications, a scope designator is a necessity. Visual Basic doesn't care whether you use prefixes, but consistently using prefixes benefits you as well as others who have to review your code
34 Prefix Description Example g_ Global g_strSavePath m_ Module-level m_blnDataChanged s_ Static variable s_blnInHere No prefix Nonstatic variable, local to procedure Prefix Description Example UNIT 2: VISUAL BASIC FUNDAMENTALS Related Links: http://msdn.microsoft.com/en- us/library/gg145045(v=VS.100).aspx
.Net Framework Class Library contains many predefined classes that are grouped into namespaces which uses Import statement to specify the namespaces used in a program Example: Import System.Windows.Forms
The declaration above will enable the program to use classes in this namespace, such as class MessageBox.
35 UNIT 2: VISUAL BASIC FUNDAMENTALS Related Links: http://msdn.microsoft.com/en-us/library/zdf6yhx5.aspx http://msdn.microsoft.com/en-us/library/system.console.readline.aspx http://msdn.microsoft.com/en-us/library/system.console.aspx http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#DFormatString
ReadLine : Reads the next line of characters from the standard input stream. WriteLine : Writes the current line terminator to the standard output stream. Write : Writes the text representation of the specified value or values to the standard output stream.
36 UNIT 2: VISUAL BASIC FUNDAMENTALS 37 UNIT 2: VISUAL BASIC FUNDAMENTALS Format specifier Name Description Examples "C" or "c" Currency Result: A currency value. Supported by: All numeric types. Precision specifier: Number of decimal digits. Default precision specifier: Defined by System.Globalization.NumberFormatInfo. More information: The Currency ("C") Format Specifier. 123.456 ("C", en-US) -> $123.46 123.456 ("C", fr-FR) -> 123,46 123.456 ("C", ja-JP) -> 123 -123.456 ("C3", en-US) -> ($123.456) -123.456 ("C3", fr-FR) -> -123,456 -123.456 ("C3", ja-JP) -> -123.456 "D" or "d" Decimal Result: Integer digits with optional negative sign. Supported by: Integral types only. Precision specifier: Minimum number of digits. Default precision specifier: Minimum number of digits required. More information: The Decimal("D") Format Specifier. 1234 ("D") -> 1234 -1234 ("D6") -> -001234 "E" or "e" Exponential (scientific) Result: Exponential notation. Supported by: All numeric types. Precision specifier: Number of decimal digits. Default precision specifier: 6. More information: The Exponential ("E") Format Specifier. 1052.0329112756 ("E", en-US) -> 1.052033E+003 1052.0329112756 ("e", fr-FR) -> 1,052033e+003 -1052.0329112756 ("e2", en-US) -> - 1.05e+003 -1052.0329112756 ("E2", fr_FR) -> - 1,05E+003 38 UNIT 2: VISUAL BASIC FUNDAMENTALS Format specifier Name Description Examples "F" or "f" Fixed-point Result: Integral and decimal digits with optional negative sign. Supported by: All numeric types. Precision specifier: Number of decimal digits. Default precision specifier: Defined by System.Globalization.NumberFormatInfo. More information: The Fixed-Point ("F") Format Specifier. 1234.567 ("F", en-US) -> 1234.57 1234.567 ("F", de-DE) -> 1234,57 1234 ("F1", en-US) -> 1234.0 1234 ("F1", de-DE) -> 1234,0 -1234.56 ("F4", en-US) -> -1234.5600 -1234.56 ("F4", de-DE) -> -1234,5600 "G" or "g" General Result: The most compact of either fixed-point or scientific notation. Supported by: All numeric types. Precision specifier: Number of significant digits. Default precision specifier: Depends on numeric type. More information: The General ("G") Format Specifier. -123.456 ("G", en-US) -> -123.456 123.456 ("G", sv-SE) -> -123,456 123.4546 ("G4", en-US) -> 123.5 123.4546 ("G4", sv-SE) -> 123,5 -1.234567890e-25 ("G", en-US) -> - 1.23456789E-25 -1.234567890e-25 ("G", sv-SE) -> - 1,23456789E-25 "N" or "n" Number Result: Integral and decimal digits, group separators, and a decimal separator with optional negative sign. Supported by: All numeric types. Precision specifier: Desired number of decimal places. Default precision specifier: Defined by System.Globalization.NumberFormatInfo. More information: The Numeric ("N") Format Specifier. 1234.567 ("N", en-US) -> 1,234.57 1234.567 ("N", ru-RU) -> 1 234,57 1234 ("N", en-US) -> 1,234.0 1234 ("N", ru-RU) -> 1 234,0 -1234.56 ("N", en-US) -> -1,234.560 -1234.56 ("N", ru-RU) -> -1 234,560 39 UNIT 2: VISUAL BASIC FUNDAMENTALS Format specifier Name Description Examples "P" or "p" Percent Result: Number multiplied by 100 and displayed with a percent symbol. Supported by: All numeric types. Precision specifier: Desired number of decimal places. Default precision specifier: Defined by System.Globalization.NumberFormatInfo. More information: The Percent ("P") Format Specifier. 1 ("P", en-US) -> 100.00 % 1 ("P", fr-FR) -> 100,00 % -0.39678 ("P1", en-US) -> -39.7 % -0.39678 ("P1", fr-FR) -> -39,7 % "R" or "r" Round-trip Result: A string that can round-trip to an identical number. Supported by: Single, Double, and BigInteger. Precision specifier: Ignored. More information: The Round-trip ("R") Format Specifier. 123456789.12345678 ("R") -> 123456789.12345678 -1234567890.12345678 ("R") -> - 1234567890.1234567 "X" or "x" Hexadecimal Result: A hexadecimal string. Supported by: Integral types only. Precision specifier: Number of digits in the result string. More information: The HexaDecimal ("X") Format Specifier. 255 ("X") -> FF -1 ("x") -> ff 255 ("x4") -> 00ff -1 ("X4") -> 00FF Refer Unit2 eg1.vbp Syntax Represents Literals a = 5; Integer Numerals 1776707-273 75 decimal &O43 octal &HFF3 hexadecimal "Z"C char vbCR a carriage-return character for print and display functions. vbTab a tab character for print and display functions. vbCrLf a carriage-return character combined with a linefeed character for print and display functions. vbNullString a zero-length string for print and display functions, and for calling external procedures. 40 UNIT 2: VISUAL BASIC FUNDAMENTALS If used, the Option Explicit statement must appear in a file before any other source code statements. When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time. Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear. If the Option Explicit statement is not used, all undeclared variables are of Object type. 41 UNIT 2: VISUAL BASIC FUNDAMENTALS Restricts implicit data type conversions to only widening conversions. If used, the Option Strict statement must appear in a file before any other source code statements. VB allows conversions of many data types to other data types. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity. A run-time error occurs if such a narrowing conversion fails. Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided. 42 UNIT 2: VISUAL BASIC FUNDAMENTALS An operation is at least one value combined with a symbol to produce a new value. A more complex operation can involve more than one value and possibly more than one symbol. A value involved in an operation is called an operand. A symbol involved in an operation is called an operator.
43 UNIT 2: VISUAL BASIC FUNDAMENTALS Types of operators: Arithmetic operators Boolean operators Relational operators Bitwise operators unary operators. - Operators that work with only one operand are called binary operators - operators who work with two operands are called
44 UNIT 2: VISUAL BASIC FUNDAMENTALS Symbol Syntax Example ^ result = number^exponent Dim MyValue MyValue = 2 ^ 2 'Returns 4. MyValue = 3 ^ 3 ^ 3 'Returns 19683. MyValue = (-5) ^ 3 'Returns -125. * multiply two numbers. result = number1*number2 Dim MyValue MyValue = 2 * 2 ' Returns 4. MyValue = 459.35 * 334.90'Returns 153836.315. / divide two numbers and return a floating-point result. result = number1/number2 Dim MyValue MyValue = 10 / 4 ' Returns 2.5. MyValue = 10 / 3 ' Returns 3.333333. \ divide two numbers and return an integer result. result = number1\number2 Dim MyValue MyValue = 11 \ 4 ' Returns 2. MyValue = 9 \ 3 ' Returns 3. MyValue = 100 \ 3 ' Returns 33. 45 1. Arithmetic Operators UNIT 2: VISUAL BASIC FUNDAMENTALS Symbol Syntax Example Mod divide two numbers and return only the remainder result = number1 Mod number2. Dim MyResult MyResult = 10 Mod 5 ' Returns 0. MyResult = 10 Mod 3 ' Returns 1. MyResult = 12 Mod 4.3 ' Returns 0. MyResult = 12.6 Mod 5 ' Returns 3. + sum two numbers. result = expression1+expression2 Dim MyNumber, Var1, Var2 MyNumber = 2 + 2 ' Returns 4. MyNumber = 4257.04 + 98112 ' Returns 102369.04. Var1 = "34": Var2 = 6 ' Initialize mixed variables. MyNumber = Var1 + Var2 ' Returns 40. Var1 = "34": Var2 = "6" ' Initialize variables with strings. MyNumber = Var1 + Var2' Returns "346" (string concatenation). 46 UNIT 2: VISUAL BASIC FUNDAMENTALS 1. Arithmetic Operators Symbol Syntax Example - Used to find the difference between two numbers or to indicate the negative value of a numeric expression. result = number1number2 number Dim MyResult MyResult = 4 - 2 ' Returns 2. MyResult = 459.35 - 334.90 ' Returns 124.45. & Used to force string concatenation of two expressions. result = expression1 & expression2 Dim MyStr MyStr = "Hello" & " World" ' Returns "Hello World". MyStr = "Check " & 123 & " Check" ' Returns "Check 123 Check". 47 UNIT 2: VISUAL BASIC FUNDAMENTALS 1. Arithmetic Operators Symbol Syntax Meaning = X = Y X is equal to Y <> X <> Y X is not equal to Y > X > Y X is greater than Y < X < Y X is less than Y >= X >= Y X is greater than or equal to Y <= X <= Y X is Less than or equal to Y Like result = string Like pattern Used to compare two strings. 48 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Equality and Relational Operators 49 UNIT 2: VISUAL BASIC FUNDAMENTALS 3. Logical (Boolean) operators Symbol Syntax Example Not Used to perform logical negation on an expression. result = Not expression Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = Not(A > B) 'Returns False. MyCheck = Not(B > A) 'Returns True. MyCheck = Not(C > D)' Returns Null. MyCheck = Not A 'Returns -11 (bitwise comparison). And Used to perform a logical conjunction on two expressions. result = expression1 And expression2 Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B And B > C ' Returns True. MyCheck = B > A And B > C ' Returns False. MyCheck = A > B And B > D ' Returns Null. MyCheck = A And B ' Returns 8 (bitwise comparison). Or Used to perform a logical conjunction on two expressions result = expression1 Or expression2 Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Or B > C ' Returns True. MyCheck = B > A Or B > C ' Returns True. MyCheck = A > B Or B > D ' Returns True. MyCheck = B > D Or B > A ' Returns Null. MyCheck = A Or B ' Returns 10 (bitwise comparison). 50 UNIT 2: VISUAL BASIC FUNDAMENTALS 3. Logical (Boolean) operators Symbol Syntax Example Xor Used to perform a logical exclusion on two expressions. [result =] expression1 Xor expression2 Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Xor B > C ' Returns False. MyCheck = B > A Xor B > C ' Returns True. MyCheck = B > A Xor C > B ' Returns False. MyCheck = B > D Xor A > B ' Returns Null. MyCheck = A Xor B ' Returns 2 (bitwise comparison). Eqv Used to perform a logical equivalence on two expressions. result = expression1 Eqv expression2 Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Eqv B > C ' Returns True. MyCheck = B > A Eqv B > C ' Returns False. MyCheck = A > B Eqv B > D ' Returns Null. MyCheck = A Eqv B ' Returns -3 (bitwise comparison). Imp Used to perform a logical implication on two expressions result = expression1 Imp expression2 Dim A, B, C, D, MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = A > B Imp B > C ' Returns True. MyCheck = A > B Imp C > B ' Returns False. MyCheck = B > A Imp C > B ' Returns True. MyCheck = B > A Imp C > D ' Returns True. MyCheck = C > D Imp B > A ' Returns Null. MyCheck = B Imp A ' Returns -1 (bitwise comparison). Symbol Function Example << Performs an arithmetic left shift on a bit pattern. Dim pattern As Short = 192' The bit pattern is 0000 0000 1100 0000.Dim result As Shortresult = pattern << 4 pattern is 192 0000 0000 1100 0000 result is 3072 0000 1100 0000 0000 >> Performs an arithmetic right shift on a bit pattern. Dim pattern As Short = 2560' The bit pattern is 0000 1010 0000 0000.Dim result As Shortresult2 = pattern >> 4 pattern is 2560 0000 1010 0000 0000 result is 160 0000 0000 1010 0000 >>= Performs an arithmetic right shift on the value of a variable or property and assigns the result back to the variable or property <<= Performs an arithmetic left shift on the value of a variable or property and assigns the result back to the variable or property. 51 UNIT 2: VISUAL BASIC FUNDAMENTALS 4. Bitwise Operators Compound assignment operator Sample expression Explanation += c+=7 c=c+7 -= c-=3 c=c-3 *= c*=4 c=c*4 /= c/=2 c=c/2 \= c\=3 c=c\3 ^= c^=2 c=c^2 &= d&=llo d=d&llo <<= c<<=1 c=c<<1 >>= c>>= c=c>>1 52 UNIT 2: VISUAL BASIC FUNDAMENTALS 5. Compound Assignment Operators In VB we have two operators for string concatenation. The plus + operator and the & ampersand operator.
53 Option Strict On
Module Example
Sub Main()
Console.WriteLine(Politeknik " & Sultan " & Haji Ahmad Shah") Console.WriteLine(Politeknik " + Sultan " + Haji Ahmad Shah")
End Sub
End Module UNIT 2: VISUAL BASIC FUNDAMENTALS 6. Concatenating Strings operators Dim strA As String Dim strB As String Dim intA As Short Dim dblB As Decimal strA = "POLITEKNIK " strB = "SULTAN HAJI AHMAD SHAH " intA = 1234 dblB = 1234.567 Console.WriteLine(strA & strB) Console.WriteLine(strA + strB) Console.WriteLine(intA & dblB) Console.WriteLine(intA + dblB) 54 UNIT 2: VISUAL BASIC FUNDAMENTALS 6. Concatenating Strings Operator Operation 1 ^ Exponentiation 2 +,- Sign operations 3 *,/ Multiplication and Division 4 \ Integer division 5 Mod Modulus 6 +,- Addition and Subtraction 7 & concatenation 8 <<, >> Bitwise 9 =, <>, <, <=, >=, Like, Is Relational 10 Not Logical NOT 11 And, AndAlso Logical AND 12 Or, OrElse Logical inclusive OR 13 Xor Logical exclusive OR 14 =, +=, -=, *=, /=, \=, ^=, &= Assignment 55 UNIT 2: VISUAL BASIC FUNDAMENTALS Hierarchy of Operators Precedence Decision-making or Selection Control Structures are coding structures that enable you to execute or omit code based on a condition, such as the value of a variable. VB includes two constructs that enable you to make any type of branching decision you can think of:
If...Then...Else and Select Case.
56 UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement 1. If..Then statement Syntax: If expression Then ... ' code to execute when expression is True. End If If the expression evaluates to True, the code placed between the If statement and the End If statement gets executed. If the expression evaluates to False, Visual Basic jumps to the End If statement and continues execution from there, bypassing all the code between the If and End If statements.
57 UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement Example:
58 If IsNumeric(txtInput.Text) Then MessageBox.Show("The text is a number.") End If UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement Examples: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If RadioButton1.Checked = True Then MsgBox("RadioButton1 selected") End If If RadioButton2.Checked = True Then MsgBox("RadioButton2 selected") End If End Sub 59 UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement 2. Else Statement to execute some code when expression evaluates to False, include an Else statement between If and End If: Syntax: If expression Then ... ' code to execute when expression is True. Else ... ' code to execute when expression is False. End If
60 UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement Example: If IsNumeric(txtInput.Text) Then MessageBox.Show("The text is a number.") Else MessageBox.Show("The text is not a number.") End If
61 UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement 3. ElseIf Statement The ElseIf statement allows you to evaluate a second expression when an If...Then statement equates to False. Syntax: If expression Then ... ElseIf expression2 Then ... End If
62 UNIT 2: VISUAL BASIC FUNDAMENTALS Example: If RadioButton1.Checked = True Then MsgBox("RadioButton1 selected") ElseIf RadioButton2.Checked = True Then MsgBox("RadioButton2 selected") End If 63 UNIT 2: VISUAL BASIC FUNDAMENTALS The If Statement 3. Nested If..Then Syntax: If expression Then ... Else If expression2 Then ... End If End If
64 UNIT 2: VISUAL BASIC FUNDAMENTALS Example: If RadioButton1.Checked = True Then If CheckBox1.Checked = True Then MsgBox("RadioButton1 and CheckBox1 selected") Else : MsgBox("radioButton1 and ChechBox2 selected") End If ElseIf RadioButton2.Checked = True Then If CheckBox1.Checked = True Then MsgBox("RadioButton2 and CheckBox1 selected") Else : MsgBox("radioButton2 and ChechBox2 selected") End If End If 65 UNIT 2: VISUAL BASIC FUNDAMENTALS The Select case statement Syntax: Select Case expression Case value1 ... Case value2 ... Case value3 ... Case Else ... End Select
66 Case Else is used to define code that executes only when expression doesn't evaluate to any of the values in the Case statements. Use of Case Else is optional. UNIT 2: VISUAL BASIC FUNDAMENTALS The Select case statement for Multiple Selections The Select Case statement enables you to create some difficult expression comparisons. Eg. specify multiple comparisons in a single Case statement by separating the comparisons with a (,).
67 UNIT 2: VISUAL BASIC FUNDAMENTALS The Select case statement Examples:
68 Select Case lngAge Case 1 To 7 ' Code placed here executes if lngAge is 1, 7 or any number in between. End Select Select Case strName Case "Hartman" To "White" ' Code placed here executes if the string is Hartman, White, ' or if the string falls alphabetically between these two names. End Select
UNIT 2: VISUAL BASIC FUNDAMENTALS The Select case statement Examples:
69 Select Case lngAge Case < 10 ... Case 10 To 17 ... Case 18 To 20 ... Case Else ... End Select
UNIT 2: VISUAL BASIC FUNDAMENTALS The Select case statement Dim Number Number = 8 ' Initialize variable. Select Case Number ' Evaluate Number. Case 1 To 5 ' Number between 1 and 5, inclusive. Console.WriteLine("Between 1 and 5") Case 6, 7, 8 ' Number between 6 and 8. Console.WriteLine("Between 6 and 8") Case 9 To 10 ' Number is 9 or 10. Console.WriteLine("Greater than 8") Case Else ' Other values. Console.WriteLine("Not between 1 and 10") End Select 70 UNIT 2: VISUAL BASIC FUNDAMENTALS 1. For...Next Loop Syntax: For countervariable = start To end [Step step] ... [statements to execute in loop] [Exit For] ... [statements to execute in loop] Next [countervariable]
71 UNIT 2: VISUAL BASIC FUNDAMENTALS 1. For...Next Loop Components of a for loop: 72 Part Description countervariable A previously declared variable of a numeric data type (Integer, Long, and so on). This variable is incremented each time the loop occurs. start The number you want to start counting from. end The number you want to count to. When countervariable reaches the end number, the statements within the For...Next loop are executed a final time, and execution continues with the line following the Next statement. step The amount by which you want countervariable incremented each time the loop is performed. step is an optional parameter; if you omit it, countervariable is incremented by 1. Exit For A statement that can be used to exit the loop at any time. When Exit For is encountered, execution jumps to the statement following Next. UNIT 2: VISUAL BASIC FUNDAMENTALS 1. For...Next Loop Examples:
73 Dim intCounter As Integer For intCounter = 1 To 10 Console.WriteLine(intCounter) Next intCounter
Dim intCounter As Integer For intCounter = 1 To 10 Console.WriteLine(intCounter) Next
Note: Both examples will produce the same results. UNIT 2: VISUAL BASIC FUNDAMENTALS 1. For...Next Loop Example: 74 Dim intCounter As Integer Dim intSecondCounter As Integer For intCounter = 1 To 5 For intSecondCounter = 1 To 5 Console.WriteLine(intSecondCounter) Next intSecondCounter Next intCounter UNIT 2: VISUAL BASIC FUNDAMENTALS 1. For...Next Loop Using step Step is used in a For...Next statement to designate the value by which to increment the counter variable each time the loop occurs. Example:
75 Dim intCounter As Integer For intCounter = 1 To 100 Step 4 Console.WriteLine(intCounter) Next intCounter UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop Syntax: Do [Statements] Loop
You could start a For...Next loop specifying an upper limit that you know is larger than the number of loops needed, check for a terminating condition within the loop, and exit the loop using an Exit For statement when the condition is met. 76 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop Example: Dim counter As Integer = 10 Do Console.WriteLine(counter) Loop Caution: This is an infinite loop. Why???? 77 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop More complete Syntax: Do [Statements] If expression Then Exit Do Loop
In this code, the loop would execute until expression evaluates to True. 78 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do..Loop Example: Dim counter As Integer = 1 Do Console.WriteLine(counter) counter += 2 If counter > 10 Then Exit Do Loop
79 Loop Control Structure UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do..Loop Flowchart: 80 If Counter >10
Start or initialize Counter =1
Yes
No
Increment (counter+=2)
Display value of counter
Loop Control Structure UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop More Syntax: Do While expression [Statements] Loop
As long as expression evaluates to True, this loop continues to occur. If expression evaluates to False when the loop first starts, the code between the Do While and Loop statements doesn't execute not even once 81 Loop Control Structure UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop Example: Dim counter As Integer = 1 Do While (counter < 10) Console.WriteLine(counter) counter += 2 Loop 82 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop More Syntax: Do Until expression [Statements] Loop the loop executes repeatedly until expression evaluates to True
83 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop Example: Dim counter As Integer = 1 Do Until (counter > 10) Console.WriteLine(counter) counter += 2 Loop
84 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do..Loop Flowchart: 85 If Counter >10
Start or initialize Counter =1
Yes
No
Increment (counter+=2)
Display value of counter
UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop More Syntax: Do [Statements] Loop While expression
This loop executes as long as expression evaluates to True
The difference between the Do...While and Do...Loop While loops: Code between the Do and the Loop While statements always executes at least once; expression isn't evaluated until the loop has completed its first cycle. Again, such a loop always executes at least once, regardless of the value of expression. 86 Loop Control Structure UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop
Example: Dim counter As Integer = 1 Do Console.WriteLine(counter) counter += 2 Loop While (counter < 10) 87 Loop Control Structure UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop More Syntax:
Do [Statements] Loop Until expression
This loop executes until expression evaluates to True. However, the code within this loop always executes at least once; expression isn't evaluated until the loop completes its first cycle.
88 UNIT 2: VISUAL BASIC FUNDAMENTALS 2. Do . . . Loop Example: Dim counter As Integer = 1 Do Console.WriteLine(counter) counter += 2 Loop Until (counter > 10) 89 UNIT 2: VISUAL BASIC FUNDAMENTALS 3. While...End While Loop Statement Syntax While condition [statements] End While
90 UNIT 2: VISUAL BASIC FUNDAMENTALS 3. While...End While Loop Statement Example: Dim Counter As Short = 1 While Counter < 10 Counter += 2 Console.WriteLine(Counter) End While
91 UNIT 2: VISUAL BASIC FUNDAMENTALS 3. While...End While Loop Statement Flowchart 92 If Counter <10