Sei sulla pagina 1di 107

http://www.studyvb.

com/

All Chapters and Topics

Chapter : Introduction to Visual Basic

Topic Output and Comments in Modules


Topic Variables
Topic Some Operators
Topic Reading Input from the User
Topic Introduction to Selections
Topic Introduction to Iterations
Topic Nested Structures
Topic Iterations
Topic Selections
Topic Boolean Datatype and Expressions
Topic Logical Operators And, Or and Not
Topic Boolean Logical
Topic Logical Disjunction Operator Xor
Topic Logical Shortcircuit Operators AndAlso and OrElse
Topic Operators
Topic Numeric Integral Datatypes - Byte Short Integer Long
Topic Numeric Decimal Datatypes - Single Double Decimal
Topic Floating Point Notation - Single Double Decimal
Topic Numeric Literals and Type Coercion
Topic Char and String Datatypes
Topic Temporal Datatype Date
Topic Constants

Chapter : Arrays

Topic Introduction to Arrays


Topic Multidimensional Arrays
Topic Dynamical Arrays
Topic Array Initializers
Topic For Each Next
Topic Array Datatype
Topic Jagged Arrays
Topic Searching through Arrays - Linear Search
Topic Searching through Arrays - Binary Search
Topic Sorting Arrays - Selection Sort
Topic Sorting Arrays - Bubble Sort
Topic Sorting Arrays - Insertion Sort

Chapter : Procedures and Functions

Topic Introduction to Procedures


Topic Arguments - ByVal and ByRef
Topic Local Variables and Argument Variables
Topic Module Variables
Topic Static Variables
Topic Statementblcok Variables
Topic Introduction to Functions
Topic Method Overloading
Topic Optional Arguments
Topic Arrays as Arguments
Topic Returning Arrays
Topic Parameter Arrays - ParamArray
Topic Output and Comments in Modules

Hello World

Following example will bring the text "Hello World" to the console.

Module Example ' (1)


Sub Main() ' (2)
' following instruction writes some text to the console ' (3)
Console.WriteLine("Hello World !") ' (4)
'
Console.ReadLine() ' (5)
End Sub ' (6)
End Module ' (7)

Output :
Hello World !

Comments

Each line beginning with a single quote ( ' ) (3) is a comment line. These lines are ignored by the compiler, and will
not alter the programs execution.

I would advise to use comment lines to clarify your program. This will help you later on when adaptations need to
be made. Keep in mind, that when you make adaptations that you also update your comment lines. If you do not,
your comment lines will lose their purpose.

Visual Studio : When default settings are used, comments are shown green.

REM ( abbreviation for remark ) is an alternative for the single quote : REM This is a comment line.

Modules

A module is a simple code block in which we write our sourcecode. Our sourcecode is written between Module (1)
and End Module.

Visual Studio : To start a module in Visual Studio, you can click "Debug" and "Start Debugging".
Identifiers and Keywords

Each module has a name, also called the identifier. For each module we can choose an identifier.
Certain rules for identifier have to be followed, namely :
- The name has to be one word, no spaces can be used.
- The identifier has to be unique. For example each module in a certain project has to have a different name.
- The following characters can be used to form the name: a to z, A to Z, 0 to 9 and an underscore ( _ ); although
identifiers cannot start with a number.
- The identifier may not start with a number.
- The identifier cannot be a reserved keyword. These are already used in the language for specific constructions,
for example Module(1), Sub (2) and End (6)(7) . As a consequence the compiler would not interpret these as
identifiers , except when we put them between brackets, for example [Module] . In this case the compiler would
recognize it as an identifier and not as a reserved keyword.

Visual Studio : When default settings are used for the editor, keywords are shown in blue.

Procedures

The above module Example has a procedure with the identifier Main.

In a procedure we can write an algorithm to perform a certain routine.

A procedure starts with Sub (2) and ends with End Sub (6).

More than one procedure can be added to a module, but the execution of the program can only start with one
procedure, this is always the Main procedure.

Output

Console.WriteLine() will write the value expressed between the parentheses to the console.

Input

After executing the code in the Main procedure the application is ended, and the console is closed. To avoid
closing the console we can put a Console.ReadLine() at the end of the Main procedure. This will give us the
opportunity to see what output we have on the console ( other uses for Console.ReadLine() will be explained
later on ).
Console.ReadLine() will read a line from the console. A line consists of zero or more characters ending with an
endline character. An endline characters delimits a line. When the input is coming from the user, the endline is
formed by pressing the "Enter" key.
Only after the user presses "Enter" the program will continue with the instructions after Console.ReadLine().
When there are no following instructions ( like in the above example ), the program ( and console ) will close.
Strings and Literals

The above example will always bring the text "Hello World !" to the console.
This text is a constant, and will not vary at runtime. To express this text ( also called "string" ), we can use constant
expressions, like "string literals", which are quoted within double quotes ( "..." ).

Visual Studio : When default settings are used, string literals are shown in red.

What are Variables

This example will also bring the text "Hello World" to the console, but this time we will use variables.

Variables are dataholders which can be used at runtime to save information.


The content of the variable can change/vary at runtime.

Module Example
Sub Main()
Dim message As String ' declaration (1)
message = "Hello World !" ' initial assignment (2)
'
' or :
' Dim message As String = "Hello World !" ' initialization (3)
'
Console.WriteLine(message)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Hello World !

Declaration of a Variable

Before our algorithm can use a variable, we will declare this variable to the compiler.

When declaring the variable we'll defined :


- the identifier of the variable
- the datatype of the variable, by using a "type specifier" in the form of an As-clause, keyword As followed by the
name of the datatype

Keyword Dim is needed to mark this line as a declaration.


Datatypes

Two often used datatypes are :


- String : used for alphanumeric data ( text )
- Integer : used for numeric data ( integral values )

The datatype specifies what information the variable can contain, and what actions we can perform on or with that
variable. For instance, two numeric variables can contain numeric values which can be added, multiplied, divided,
... .

Assignment

To set a variable to a specific value, the value has to be assigned to this variable. An assignation often looks like
this : left-part = right-part

= is the assignation operator.

The value expressed by the right-part is assigned to the left-part.

The value ( to assign ) can be expressed is all kinds of forms. In the above example a String literal is used. But
this could also be expressed by referring to another String variable.

It is also possible to initialize the variable in the declaration line.


Just put an assignation-clause ( = followed by the expression expressing the value to assign ) after the type
specifier.

Between the parentheses of Console.WriteLine we place an expression that will evaluated to the value we
want to output to the console.

Some Operators

Next example will print two values and their sum.

Module Example
Sub Main()
Dim value1 As Integer
Dim value2 As Integer
Dim sum As Integer
value1 = 1
value2 = 2
sum = value1 + value2
'
' or :
' Dim value1 As Integer = 1
' Dim value2 As Integer = 2
' Dim sum As Integer = value1 + value2
'
' or :
' Dim value1 As Integer = 1, value2 As Integer = 2, _
' sum As Integer = value1 + value2
'
Console.WriteLine(value1 & " + " & value2 & _
" = " & sum)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1 + 2 = 3

Arithmetical Operators

The above example illustrates the use of the addition operator +.

Other arithmetical operators are :


- subtraction operator -
- multiplication operator *
- division operator /
- integral division operator \
- modulo operator Mod
- exponential operator ^

All the above operators use two operands ( left and right operator ).

Concatenation Operator

The concatenation operator & will combine two Strings ( to one String ).

Nextline Operator

The nextline operator _ can be used to maintain readability of your code.


The compiler interprets the instruction on the line following an underscore as if it was on the position of that
underscore.

Multiple Declarations

A declaration line can contain more than one variable. After the type specifier ( of the declaration of some variable )
a comma is place, followed by the declaration of the next variable.

Reading Input from the User

Accepting or Reading Input

Module Example accepts some input ( name and age ) from the user.
An Example

Module Example
Sub Main()
Dim name As String
Dim age As Integer
'
Console.WriteLine("Name ?")
name = Console.ReadLine()
'
Console.WriteLine("Age ?")
age = Console.ReadLine()
'
Console.WriteLine("Your name is " & name & ".")
Console.WriteLine("Your age is " & age & ".")
'
Console.ReadLine()
End Sub
End Module

Output :
Name ?
John
Age ?
50
Your name is John.
Your age is 50.

Console ReadLine

Console.ReadLine() will read a line from the console. A line consists of zero or more characters ended with an
endline character. When the input is coming from the user, the endline is formed by pressing the "Enter" key.

Console.ReadLine() also forms an expression that will evaluate to the value ( the text ) before the endline (
entered before the "Enter" key is pressed ). This value is assigned to the variables.
Exercises

Task :

Make a program based on the following output ( input is in italic ).


Output :
Number ?
5
Square of 5 is 25.

Solution :

Module Exercise1Solution
Sub Main()
Dim number, square As Integer
'
Console.WriteLine("Number ?")
number = Console.ReadLine()
'
square = number ^ 2
'
Console.WriteLine("Square of " & number & " is " & square & ".")
'
Console.ReadLine()
End Sub
End Module

Task :

Make a program based on the following output ( input is in italic ).

Output :
Name ?
John
Length ?
185
John you're 1 meter and 85 centimetres.

Solution :

Module Exercise2Solution
Sub Main()
Dim name As String
Dim length As Integer
'
Console.WriteLine("Name ?")
name = Console.ReadLine()
'
Console.WriteLine("Length ?")
length = Console.ReadLine()
'
Console.WriteLine(name & " you're " & _
(length \ 100) & " meter and " & _
(length Mod 100) & " centimetres.")
'
Console.ReadLine()
End Sub
End Module

Introduction to Selections

Making Decisions or Selections

So far, all instructions were executions in sequence. After the first instruction was executed, the second was
executed, and so on.
In this sequential technique all instructions are executed in the same order as they are defined.

Besides this sequence technique, other techniques are required to form more complex algorithms.
Suppose we need a program that outputs half of a numeric value when an even number is entered, and double
of that value when an odd number is entered.

In this case are algorithm needs to make a decision. The algorithm needs to decide whether to output the half or
the double of the entered value.

We can code this decision/selection with a decision structure. This structure is centered around a specific
conditional, formed by a conditional expression.
Conditional expressions ( also called "boolean expressions" ) can only evaluate to True or False.
If ... Else ... End If

Module Example
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
If value Mod 2 = 0 Then
Console.WriteLine("Half of " & value & " is " & value / 2 & ".")
Else
Console.WriteLine("Double of " & value & " is " & value * 2 & ".")
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
5
Double of 5 is 10.
Output :
Value ?
10
Half of 10 is 5.

Comparison Operators

In the above example the decision is coded with an If ... End If. The If is followed with the condition.
When the condition evaluated as true, the instruction in the If part are executed. When the condition is not
fulfilled the instructions and there is an Elsepart present, the instructions in the Else part are executed.

Comparison operator = can be used to check for equality. The same symbol is used for the assignment operator,
don't confuse the two.
Other comparison operators are : <> ( not equal to ), > ( more than ),
> ( less than ), >= ( more than or equal to ) and <= ( less than or equal to ).

Exercise

Task :

Make a program based on the following output ( input is in italic ).

Output :
Value ?
0
Zero.

Output :
Value ?
123
Value 123 is not equal to zero.

Solution :

Module ExerciseSolution
Sub Main()
Dim value As Integer
'
Console.WriteLine("Value ?")
value = Console.ReadLine()
'
If value = 0 Then
Console.WriteLine("Zero.")
Else
Console.WriteLine("Value " & value & " is not equal to zero.")
End If
'
Console.ReadLine()
End Sub
End Module

Introduction to Iterations

Why use Iterations

Following example gives us all numbers from one to three.

Module Example1
Sub Main()
Console.WriteLine(1)
Console.WriteLine(2)
Console.WriteLine(3)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3

The above example is very statically defined. Suppose we need all numbers from one to hundred, then 97
instructors need to be added.

A more dynamic solution can be defined when using the iteration technique.

Module Example2
Sub Main()
Dim value As Integer
'
value = value + 1
Console.WriteLine(value)
'
value = value + 1
Console.WriteLine(value)
'
value = value + 1
Console.WriteLine(value)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3

Do While ... Loop Iteration

As you can see in the above solution the same instructions are repeated three times.

In stead of repeating the same instructions, we can code them between a Do While and Loop of an iteration.

Do While is followed by a condition, expression how long the instructions ( between Do While and Loop )
should be repeated.
As long as the condition evaluates as true the instructions are repeated. From the moment the condition
evaluates as false the iteration is ended, and the instructions following the iteration are executed.

Module Example3
Sub Main()
Dim value As Integer
'
Do While value < 3
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3

The algorithm can be coded even more dynamical by adding a start- and endvalue.

Module Example4
Sub Main()
Dim startValue As Integer = 10
Dim endValue As Integer = 15
'
Dim value As Integer = startValue - 1
Do While value < endValue
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
10
11
12
13
14
15

Exercises

Task :

Make a program that brings all numbers from 20 to 10 on the console.

Output :
20
19
18
17
16
15
14
13
12
11
10
Solution :

Module Exercise1Solution
Sub Main()
Dim value As Integer = 21
'
Do While value > 10
value = value - 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Make a program that brings all powers of 2 smaller ( starting with exponent 1 ) than 1000 on the console.

Output :
base : 2, exponent : 1, result : 2
base : 2, exponent : 2, result : 4
base : 2, exponent : 3, result : 8
base : 2, exponent : 4, result : 16
base : 2, exponent : 5, result : 32
base : 2, exponent : 6, result : 64
base : 2, exponent : 7, result : 128
base : 2, exponent : 8, result : 256
base : 2, exponent : 9, result : 512

Solution :

Module Exercise2Solution
Sub Main()
Dim base As Integer = 2
Dim exponent As Integer = 1
Dim result As Integer = base ^ exponent
'
Do While result < 1000
Console.WriteLine("base : " & base & _
", exponent : " & exponent & _
", result : " & result)
exponent = exponent + 1
result = base ^ exponent
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Nested Structures

Suppose we need to bring to the console whether an entered value is "Zero.", "More than zero." or "Less than
zero.".

We know that based on a condition of an If-statement we can let our algorithm decide between two options.
What to do when the condition is true, and what to do when the condition is false.

But in this case, we have more than two options, we have three options. So we're going to need at least two
conditions to make it possible for our algorithm to decide what option to take.

Module Example1
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
If value = 0 Then
Console.WriteLine("Zero.")
Else
If value > 0 Then
Console.WriteLine("Above zero.")
Else
Console.WriteLine("Bellow zero.")
End If
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
0
Zero.

Output :
Value ?
5
Above zero.
Output :
Value ?
-5
Bellow zero.

The above example illustrates how a decision ( a selection ) can be selected.

Suppose we need to print out the multiplication tables of one to nine.

Output :
1 x 1 = 1
1 x 2 = 2
...
1 x 9 = 9
2 x 1 = 1
...
9 x 9 = 81

Obviously iterations are needed. Almost identical lines follow each other.

What is being iterated here? Some base value ( starting with one and ending with nine ) is being multiplied with
all factors from one to nice.

We can start with an iteration that prints out all numbers from one to nine.

Module Example2
Sub Main()
Dim baseValue As Integer = 1
'
Do While baseValue < 10
Console.WriteLine(baseValue)
baseValue = baseValue + 1
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9

In stead of just printing out these numbers, each number should be multiplied with all factors from one to nine.

Lets write an algorithm to print out all multiplications ( with all factors ) of a certain basevalue.

Module Example3
Sub Main()
Dim baseValue As Integer = 5
Dim factor As Integer = 1
Dim multiplication As Integer
'
Do While factor < 10
multiplication = baseValue * factor
Console.WriteLine(baseValue & " x " & factor & " = " & _
multiplication)
factor = factor + 1
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45

Now we only need to integrate both above algorithms.

Module Example4
Sub Main()
Dim baseValue As Integer = 1
Dim factor As Integer = 1
Dim multiplication As Integer
'
Do While baseValue < 10
Do While factor < 10
multiplication = baseValue * factor
Console.WriteLine(baseValue & " x " & factor & " = " & _
multiplication)
factor = factor + 1
Loop
baseValue = baseValue + 1
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9

In the above solution the iteration Do While factor < 10 ( which gives a table for a certain basevalue ) is
repeated for each basevalue ( Do While baseValue < 10 ).

Notice that the output only contains the table for basevalue 1, and not for all following basevalues.

When we add the line factor = 1 at the end ( or beginning ) of iteration factor = 1 this problem is solved.

Module Example5
Sub Main()
Dim baseValue As Integer = 1
Dim factor As Integer = 1
Dim multiplication As Integer
'
Do While baseValue < 10
Do While factor < 10
multiplication = baseValue * factor
Console.WriteLine(baseValue & " x " & factor & " = " & _
multiplication)
factor = factor + 1
Loop
baseValue = baseValue + 1
factor = 1
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1 x 1 = 1
1 x 2 = 2
...
1 x 9 = 9
2 x 1 = 1
...
9 x 9 = 81

As the above example illustrates an iteration can be iterated.

Iterations can be iterated, selections can be selected. And of course, iterations be selected or selections can be
iterated.

Suppose we need to print out for all numbers from one to ten if they are even or odd.

Output :
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
10 is even.

A decision have to be taken by our algorithm to selected whether to print out "even" or to print out "odd". This
decision then has to iterated for all numbers starting with one up to nine.

It's easy to start with an algorithm that print out if a certain value is odd or even.

Module Example6
Sub Main()
Dim value As Integer = 5
'
If value Mod 2 = 0 Then
Console.WriteLine(value & " is even.")
Else
Console.WriteLine(value & " is odd.")
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
5 is odd.

This decision has to be iterated for all numbers starting with one up to nine.

Module Example7
Sub Main()
Dim value As Integer
'
Do While value < 10
value = value + 1
If value Mod 2 = 0 Then
Console.WriteLine(value & " is an even number")
Else
Console.WriteLine(value & " is an odd number")
End If
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
10 is even.

As the above example illustrates a selection can be iterated.

By using sequentially defined instruction, iterations and decisions, the most complex algorithms can be formed.

Exercises

Task :

Make a program that repeatedly asks for a number. When a value less than zero is entered, the highest
entered number is brought on the console.
Output :
Value ?
3
Value ?
8
Value ?
4
Value ?
-1
Highest Value : 8

Solution :

Module Exercise1Solution
Sub Main()
Dim value As Integer
Dim highestValue As Integer
'
Do While value >= 0
Console.WriteLine("Value ?")
value = Console.ReadLine()
'
If value > highestValue Then
highestValue = value
End If
Loop
'
Console.WriteLine("Highest Value : " & highestValue)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Make a program that prints out all numbers ( from small to big ) between two values entered by the user.

Output :
Value ?
-4
Value ?
3
Row :
-3
-2
-1
0
1
2

Output :
Value ?
2
Value ?
2
Row :

Output :
Value ?
2
Value ?
-1
Row :
0
1

Output :
Value ?
2
Value ?
3
Row :

Solution :

Module Exercise2Solution
Sub Main()
Dim value1, value2 As Integer
Dim smallestValue, highestValue As Integer
'
Console.WriteLine("Value ?")
value1 = Console.ReadLine()
Console.WriteLine("Value ?")
value2 = Console.ReadLine()
'
If value1 > value2 Then
highestValue = value1
smallestValue = value2
Else
highestValue = value2
smallestValue = value1
End If
'
Console.WriteLine("Row :")
Do While smallestValue + 1 < highestValue
Console.WriteLine(smallestValue + 1)
smallestValue = smallestValue + 1
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Make a program that accepts a positive numeric value ( not zero ).


When the value is even, the value is divided by 2 and printed out.
When the value is odd, the value is multiplied by 3, added with 1 and printed out.
Repeat this until the value is 1.

Output :
Value ?
10
Row :
10
5
16
8
4
2
1

Solution :

Module Exercise3Solution
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Console.WriteLine("Row : ")
Do While value <> 1
Console.WriteLine(value)
'
If value Mod 2 = 0 Then
value = value / 2
Else
value = value * 3 + 1
End If
Loop
Console.WriteLine(value)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Iterations

Do While ... Loop

Following example brings all number from 1 to 10 to the console.

Module Example1
Sub Main()
Dim value As Integer
'
Do While value < 10
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

Do Until ... Loop

A variation of previous example could use Until instead of While.

When While is used, the body of the iteration will repeat while the condition is True, or until the condition is
False.
In case of Until, the body of the iteration will repeat until the condition is True, or while the condition is False.

Module Example2
Sub Main()
Dim value As Integer
'
Do Until value >= 10
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

Do ... Loop While ... and Do ... Loop Until ...

It is also possible to place the While or Until clause at the end of the iteration ( following Loop ). In that case
the condition is evaluated after execution of the body of the iteration. The body of the iteration will execute at
least one time.

Following examples use a Do ... Loop with a While or Until clause at the end of the iteration to bring all
numbers from 1 to 10 to the console.

Module Example3
Sub Main()
Dim value As Integer
'
Do
value = value + 1
Console.WriteLine(value)
Loop While value < 10
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

Module Example4
Sub Main()
Dim value As Integer
'
Do
value = value + 1
Console.WriteLine(value)
Loop Until value >= 10
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

To convert a condition of a While to Until iteration, or vice versa, you need to invert the condition.
A value is only not "less than ten" when it is "more than or equal to ten". _
So iteration While value < 10 can be converted to Until value >= 10.

Later on we'll see how condition can be inverted with the 'Not' operator.

Suppose we need a program that iterates over all integral value ( starting with 1 ) up to the value provided by
the user.

Module Example5
Sub Main()
Console.WriteLine("Highest Value ?")
Dim highest As Integer = Console.ReadLine()
'
Console.WriteLine("Row :")
Dim value As Integer
Do
value = value + 1
Console.WriteLine(value)
Loop Until value >= highest
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Highest Value ?
5
Row :
1
2
3
4
5

The problem with the above algorithm is that when we enter 0, we don't get an empty row, but the row contains
1.

Output :
Highest Value ?
0
Row :
1

By placing the condition before the body of the iteration that problem gets solved.

Module Example6
Sub Main()
Console.WriteLine("Highest Value ?")
Dim highest As Integer = Console.ReadLine()
'
Console.WriteLine("Row :")
Dim value As Integer
Do Until value >= highest
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Highest Value ?
5
Row :
1
2
3
4
5

Output :
Highest Value ?
0
Row :

For ... Next

Instead of stating how long ( While ) or until when ( Until ) some instructions need to be repeated, one could
use a For ... Nextiteration that repeats instructions for every value a variable can take within a defined
range.

Again all value from 1 to 10 are brought to the console.

Module Example7
Sub Main()
Dim value As Integer
'
For value = 1 To 10
Console.WriteLine(value)
Next
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

The body of this iteration is repeated 10 times, or repeated for every value from 1 to 10 ( including 1 and 10 ),
with a default step of 1.

It is not necessary to start with 1, every value the countervariable ( value ) can take, is a legal startvalue.

Module Example8
Sub Main()
Dim value As Integer
'
For value = 10 To 15
Console.WriteLine(value)
Next
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
10
11
12
13
14
15

An optional Step clause can be used to divert from the default stepvalue 1.

Module Example9
Sub Main()
Dim value As Integer
'
For value = 2 To 10 Step 2
Console.WriteLine(value)
Next
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
2
4
6
8
10

Negative stepvalue are possible. But make sure the startvalue is more than the endvalue, otherwise the body
would never execute.

Module Example10
Sub Main()
Dim value As Integer
'
For value = 10 To 0 Step -2
Console.WriteLine(value)
Next
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
10
8
6
4
2
0

The countervariable can be of any numeric datatype ( including enumeration types ).

Automatically the countervalue is raised with the stepvalue when reaching Next.

Variables ( or any variable expression ) can be used to define then start-, end- and stepvalues.

Module Example11
Sub Main()
Dim countValue As Integer
Dim startValue As Integer = 1
Dim endValue As Integer = 10
Dim stepValue As Integer = 2
'
Console.WriteLine("values during iteration :")
For countValue = startValue To endValue Step stepValue
Console.WriteLine("count-value : " & countValue)
'
countValue = countValue + 1
startValue = startValue + 1
endValue = endValue + 1
stepValue = stepValue + 1
Next
'
Console.WriteLine("values after iteration :")
Console.WriteLine("count-value : " & countValue)
Console.WriteLine("start-value : " & startValue)
Console.WriteLine("end-value : " & endValue)
Console.WriteLine("step-value : " & stepValue)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
values during iteration :
count-value : 1
count-value : 4
count-value : 7
count-value : 10
values after iteration :
count-value : 13
start-value : 5
end-value : 6
step-value : 6

Be aware of the fact that start-, end- or stepvalues are evaluated only once for the For ... Next iteration.
If start-, end- or stepvalues change within the body of the iteration, this will have no effect on the iteration itself.

It is inadvisable to change start-, end- or stepvalues within the body of the iteration. As you can see in the
above example, this leads to code that is very difficult to read/understand.

For Each ... Next

Later on we'll see how we can iterate over the elements of an iteration using a 'For Each ... Next' iteration.

Exercises

Task :
Create a program to calculate the factorial for a given value.

The factorial of a value X equals X * (X-1) * (X-2) * ... * 1, for instance 5! = 5 * 4 * 3 * 2 * 1 = 120.

Output :
Value ?
5
5! = 120

Solution :

Module Exercise1Solution
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Dim factorial As Integer = value
Dim factor As Integer = value - 1
'
For factor = value - 1 To 2 Step -1
factorial = factorial * factor
Next
'
Console.WriteLine(value & "! = " & factorial)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Bring all seconds of all minutes of all hours to the console. Do this in following format.

Output :
00h00m00s
00h00m01s
...
00h00m59s
00h01m00s
...
00h59m59s
01h00m00s
...
23h59m59s
Solution :

Module Exercise2Solution
Sub Main()
Dim hours, minutes, seconds As Integer
Dim timeLabel As String
For hours = 0 To 23
For minutes = 0 To 59
For seconds = 0 To 59
timeLabel = ""
If hours < 10 Then
timeLabel = "0"
End If
timeLabel = timeLabel & hours & "h"
If minutes < 10 Then
timeLabel = timeLabel & "0"
End If
timeLabel = timeLabel & minutes & "m"
If seconds < 10 Then
timeLabel = timeLabel & "0"
End If
timeLabel = timeLabel & seconds & "s"
Console.WriteLine(timeLabel)
Next
Next
Next
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Create a program that converts seconds to a format using days, hours, minutes and seconds.

The conversions are repeated until the user enters 0.

When a negative value is entered, an error is produced.

Only include number of days, hours, minutes or seconds when the amounts are above 0.

Output :
Seconds ?
-1
Error : Only positive values are accepted !
Seconds ?
1000000
Result :
days
13 hours
46 minutes
40 seconds
Seconds ?
999960
Result :
11 days
13 hours
46 minutes
Seconds ?
49600
Result :
13 hours
46 minutes
40 seconds
Seconds ?
2800
Result :
46 minutes
40 seconds
Seconds ?
2760
Result :
46 minutes
Seconds ?
0
End.

Solution :

Module Exercise3Solution
Sub Main()
Dim totalSeconds, remainingSeconds As Integer
Dim days, hours, minutes, seconds As Integer
'
Do
Console.WriteLine("Seconds ?")
totalSeconds = Console.ReadLine()
If totalSeconds = 0 Then
Console.WriteLine("End.")
Else
If totalSeconds < 0 Then
Console.WriteLine("Error : " & _
"Only positive values are accepted !")
Else
remainingSeconds = totalSeconds
days = remainingSeconds \ 86400
remainingSeconds = remainingSeconds - days * 86400
hours = remainingSeconds \ 3600
remainingSeconds = remainingSeconds - hours * 3600
minutes = remainingSeconds \ 60
seconds = remainingSeconds - minutes * 60
Console.WriteLine("Result :")
If days > 0 Then
Console.WriteLine(days & " days")
End If
If hours > 0 Then
Console.WriteLine(hours & " hours")
End If
If minutes > 0 Then
Console.WriteLine(minutes & " minutes")
End If
If seconds > 0 Then
Console.WriteLine(seconds & " seconds")
End If
End If
End If
Loop Until totalSeconds = 0
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Make a program to add values. The number of values to add is undefined.

Output :
1
+
2
+
3
+
4
+
5
+
0
=
15

Output :
0
=
0

Solution :

Module Exercise4Solution
Sub Main()
Dim number, sum As Integer
'
number = Console.ReadLine()
Do Until number = 0
Console.WriteLine("+")
sum = sum + number
number = Console.ReadLine()
Loop
Console.WriteLine("=")
Console.WriteLine(sum)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Make a program to add or subtract values. The number of values to add is undefined.

The program needs to support the + ( to add ), - ( to subtract ) and = ( to get the result ) operators.

Output :
1
=
1

Output :
1
+
2
=
3

Output :
1
-
-5
=
6

Output :
1
+
2
-
3
-
4
+
5
-
0
+
0
=
1

Solution :

Module Exercise5Solution
Sub Main()
Dim number, result As Integer
Dim operatorSymbol As String
'
result = Console.ReadLine()
operatorSymbol = Console.ReadLine()
Do Until operatorSymbol = "="
number = Console.ReadLine()
If operatorSymbol = "+" Then
result = result + number
Else
If operatorSymbol = "-" Then
result = result - number
End If
End If
operatorSymbol = Console.ReadLine()
Loop
Console.WriteLine(result)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Selections

Suppose we need to bring to the console whether an entered value is "Zero.", "More than zero." or "Less than
zero.".

We know that based on a condition of an If-statement we can let our algorithm decide between two options.
What to do when the condition is true, and what to do when the condition is false.

But in this case, we have more than two options, we have three options. So we're going to need at least two
conditions to make it possible for our algorithm to decide what option to take.

Two nested Ifs can be used to achieve this.

Module Example1
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
If value = 0 Then
Console.WriteLine("Zero.")
Else
If value > 0 Then
Console.WriteLine("Positive value.")
Else
Console.WriteLine("Negative value.")
End If
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
0
Zero.

Output :
Value ?
5
Positive value.

Output :
Value ?
-5
Negative value.

We also could place 3 selections ( Ifs ) in a sequential order.

Module Example2
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
If value = 0 Then Console.WriteLine("Zero.")
If value > 0 Then Console.WriteLine("Positive value.")
If value < 0 Then Console.WriteLine("Negative value.")
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
0
Zero.

Output :
Value ?
5
Positive value.

Output :
Value ?
-5
Negative value.

As you can see a complete If statement can be written on 1 coding line.


This is only possible when only 1 instruction needs to be executed when the condition is correct.

Although resulting in the same output, the above example is less efficient than the first example. This first
example will in worst case scenario ( when the value is not equal to zero ) evaluate 2 conditions ( value =
0 which results in False and value > 0 ), in best case scenario only 1 condition needs to be evaluated
( value = 0 ).
The above example will in every scenario ( best, worst or something in between ) evaluate all 3 conditions.

Another variation can be build using ElseIf.

Module Example3
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
If value = 0 Then
Console.WriteLine("Zero.")
ElseIf value > 0 Then
Console.WriteLine("Positive value.")
Else
Console.WriteLine("Negative value.")
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode
Output :
Value ?
0
Zero.

Output :
Value ?
5
Positive value.

Output :
Value ?
-5
Negative value.

Again this results in the same output.

Performance is equal to the first example. In best case scenario only 1 condition is evaluated, in worst case 2
conditions are evaluated.

The ElseIf part is optional, but can be used more than once.

The instruction in the Else will only be execution when all the above conditions fail.

The syntax of an If statement looks like this :

If <condition> Then
...
[ ElseIf <other-condition> Then
... ] * ' optional, can be used more than once
[ Else
... ] ' optional, can be used once
End If

Although the first and the third examples are equally efficient, one could prefer the first construction.
Suppose we also need to print out the double of the entered value when the value is not equal to zero. We
could achieve this by adding one line of code to the Else part of the first selection.

Module Example4
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
If value = 0 Then
Console.WriteLine("Zero.")
Else
If value > 0 Then
Console.WriteLine("Positive value.")
Else
Console.WriteLine("Negative value.")
End If
Console.WriteLine("Double : " & (value * 2)) '
added
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
0
Zero.

Output :
Value ?
5
Positive value.
Double : 10

Output :
Value ?
-5
Negative value.
Double : -10

To achieve the same result when adapting the third example, we need to add 2 identical lines of code, 1 to
the If and 1 to the Elsepart of the second selection.
The more you can avoid writing identical line of code, the better.

Select Case ... End Select

Suppose we need to bring some information ( "One.", "Two.", "Three" of "Not one, two or three." ) about an
entered value to the console.
We have 4 each other excluding option, so 3 nested selections would be sufficient.

To avoid nesting lot of selections, one could use a Select Case ... End Select. This often leads up to
more elegant code.
Module Example5
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Select Case value
Case 1
Console.WriteLine("One.")
Case 2
Console.WriteLine("Two.")
Case 3
Console.WriteLine("Three.")
Case Else
Console.WriteLine("Not one, two or three.")
End Select
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
1
One.

Output :
Value ?
2
Two.

Output :
Value ?
3
Three.

Output :
Value ?
4
Not one, two or three.

The keywords Select Case are followed by an expression that will be evaluated.
Between Select Case and End Select all relevant cases ( and the corresponding instructions ) are
defined.

In this situation we have 4 cases, case value equals 1, case value equals 2, case value equals 3 and the case
where value doesn't equals 1 or 2 or 3.
Only the instructions of the first case - that's valid - will be executed.

The optional 'Case Else' contains the instructions that will be executed only when all the above case aren't
valid.

In best case scenario ( value is equal to 1 ) only 1 condition will be evaluated, in worst case scenario ( value is
not equal to 1, 2 or 3 ) 3 conditions will be evaluated.
So looking at the number of conditions that will be evaluated, there is no performance overhead for using
a Select Case ... EndSelect.

Suppose we need to bring the information "One.", "Two, three or four.", _


"Value from 5 to 10." or "More than 10." to the console.

Module Example6
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Select Case value
Case 1
Console.WriteLine("One.")
Case 2, 3, 4
Console.WriteLine("Two, three or four.")
Case 5 To 10
Console.WriteLine("Value from 5 to 10.")
Case Is > 10
Console.WriteLine("More than 10.")
End Select
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
1
One.

Output :
Value ?
3
Two, three or four.

Output :
Value ?
8
Value from 5 to 10.
Output :
Value ?
12
More than 10.

A number of possible values can be defined using commas to separate the values ( for instance Case 2, 3,
4 ).

A range of possible values can be defined using To ( for instance Case 5 To 10 ). This is only useful when
evaluating a numeric expression.

Also more general conditions ( about the expression ) can be formulated.


Case is here fore followed by Is and a comparison operator ( for instance Case Is > 10 defines the case
when value is more than 10 ).

Suppose we need to bring the information "More than 10.", "More than 100." or "More than 1000." to the
console.

Module Example7
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Select Case value
Case Is > 10
Console.WriteLine("More than 10.")
Case Is > 100
Console.WriteLine("More than 100.")
Case Is > 1000
Console.WriteLine("More than 1000.")
End Select
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
11
More than 10.

Output :
Value ?
101
More than 10.
Output :
Value ?
1001
More than 10.

The program functions correctly when we enter 11, "More than 10." is the result. But when we enter 101, we
get the same result.
This is correct, 101 is more than 10, but probably not really the result we were hoping on.

The above Select Case ... End Select defines overlapping cases. When a value is more than 1000, it
is also more than 100 and more than 10.

Be aware of the sequence in which you define overlapping cases. The above example is probably more useful
when we reorder the different cases.

Module Example8
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Select Case value
Case Is > 1000
Console.WriteLine("More than 1000.")
Case Is > 100
Console.WriteLine("More than 100.")
Case Is > 10
Console.WriteLine("More than 10.")
End Select
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value ?
11
More than 10.

Output :
Value ?
101
More than 100.

Output :
Value ?
1001
More than 1000.

Exercise

Task :

Make a program to give information about a - by the user - entered value. The options are "Less than -100.",
"Less than -50.", "Number from -50 to -1.", "Zero.", "One or eleven.", "Number from 1 to 50.", "More than 50."
and "More than 100.".
Try to be as precise as possible, 101 for example is rather "More than 100." than "More than 50.".

Output :
Value ?
11
One or eleven.

Output :
Value ?
101
More than 100.

Output :
Value ?
-101
Less than -100.

Output :
Value ?
51
More than 50.

Output :
Value ?
0
Zero.

Solution :
Module ExerciseSolution
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
'
Dim info As String
Select Case value
Case Is > 100
info = "More than 100."
Case Is > 50
info = "More than 50."
Case 1, 11
info = "One or eleven."
Case 2 To 50
info = "Number from 1 to 50."
Case 0
info = "Zero."
Case -50 To -1
info = "Number from -50 to -1."
Case Is < -100
info = "Less than -100."
Case Is < -50
info = "Less than -50."
End Select
'
Console.WriteLine(info)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Boolean Datatype and Expressions

In both If and Do statements we need to work with conditions. These conditions are formed by conditional
expressions.

In a statically types programming language like Visual Basic all expressions are of a - by the compiler know -
datatype. Conditional expressions are of type Boolean, therefore they are also called Boolean expressions.

Boolean expressions can only evaluated to two possible values, True or False.

Just like any other datatype variables can be declared of type Boolean.

Module Example1
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
Dim value1Higher As Boolean = value1 > value2
'
If value1Higher Then
Console.WriteLine(value1 & " > " & value2)
Else
Console.WriteLine(value1 & " <= " & value2)
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
10
Value 2 ?
5
10 > 5

Output :
Value 1 ?
5
Value 2 ?
10
5 <= 10

Variable value1Higher is declared of type Boolean, and is assigned a Boolean value.

A iteration ( Do ) or decision ( If ) can use this variables of type Boolean to form the condition.

In the above example variable value1Higher represents a value ( True or False ) whether ( True ) or not (
False ) value1 is more thanvalue2.

When we want to check equality ( is value1 equal to value2 ) the equality operator = can be used ( value1
= value2 ).

Module Example2
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
Dim equal As Boolean = value1 = value2 '
(1)
'
If equal Then
Console.WriteLine(value1 & " = " & value2)
Else
Console.WriteLine(value1 & " <> " & value2)
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
5
5 = 5

Output :
Value 1 ?
5
Value 2 ?
10
5 <> 10

Don't confuse the equality operator '=' with the assignment operator '='.
The same symbol is used, but for a different purpose, depending on the syntactical use.

A more readable version of line (1) can be formed when using parentheses :

Dim equal As Boolean = (value1 = value2)

Default Values and Literals

Module Example3
Sub Main()
Dim integerVariable As Integer
Console.WriteLine("Integer default value : " & integerVariable)
integerVariable = 5
Console.WriteLine("Integer changed value : " & integerVariable)
'
Dim stringVariable As String
Console.WriteLine("String default value : " & stringVariable)
stringVariable = "text"
Console.WriteLine("String changed value : " & stringVariable)
'
Dim booleanVariable As Boolean
Console.WriteLine("Boolean default value : " & booleanVariable)
booleanVariable = True
Console.WriteLine("Boolean changed value : " & booleanVariable)
booleanVariable = False
Console.WriteLine("Boolean changed value : " & booleanVariable)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Integer default value : 0
Integer changed value : 5
String default value :
String changed value : text
Boolean default value : False
Boolean changed value : True
Boolean changed value : False

The above example illustrates the default values of the different datatypes.
A default value is a value a variable hold after declaration ( without initialization ).

- 0 for Integer variables ( and all other numeric datatypes )


- Nothing for String variables ( printed out as "" ( no characters ) )
- False for Boolean variables

You can also see how literals ( constant expressions ) are formed with these datatypes :

- Integer literals are formed by an integral value ( between -2147483648 and +2147483647 )
- String literals are formed with Nothing or surrounding double quotes ( " )
- Boolean literals are formed with True or False

Logical Operators And, Or and Not

Conjunction Operator And

Suppose we need to print the sum of two entered values if both values are positive ( above zero ).

Module Example1
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 Then
If value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10

Output :
Value 1 ?
5
Value 2 ?
-10

Output :
Value 1 ?
-5
Value 2 ?
-10

The goal is achieved by nesting two Ifs. Only if value1 is more than 0,
and value2 is more than 0, the sum will be given.

An alternative would be to use the logical operator And.


This operator combines two Boolean expressions to one Boolean expression.

Module Example2
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 And value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10

Output :
Value 1 ?
5
Value 2 ?
-10

Output :
Value 1 ?
-5
Value 2 ?
-10

Only if both ( combined ) Boolean expressions are correct ( True ) the result is True :

condition-1 condition-2 condition-1 And condition-2


True True True
True False False
False True False
False False False

When two nested Ifs are used, each failing condition can have its alternate instructions, for instance to give
specific errors like "Value 1 not positive." and "Value 2 not positive.".

Module Example3
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 Then
If value2 > 0 Then
Console.WriteLine("Sum : " & _
(value1 + value2))
Else
Console.WriteLine("Value 2 not positive.")
End If
Else
Console.WriteLine("Value 1 not positive.")
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10
Value 1 not positive.

Output :
Value 1 ?
5
Value 2 ?
-10
Value 2 not positive.

Output :
Value 1 ?
-5
Value 2 ?
-10
Value 1 not positive.

It the And operator is used, only one general error "Value 1 and/or 2 not positive." can be given.

Module Example4
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 And value2 > 0 Then
Console.WriteLine("Sum : " & _
(value1 + value2))
Else
Console.WriteLine("Value 1 and/or 2 not positive.")
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10
Value 1 and/or 2 not positive.

Output :
Value 1 ?
5
Value 2 ?
-10
Value 1 and/or 2 not positive.

Output :
Value 1 ?
-5
Value 2 ?
-10
Value 1 and/or 2 not positive.

Therefore one could prefer the solution with the nested Ifs above the solution with the And operator.

The solution using the And operator is less efficient than the solution with the two nested Ifs.

The expression with the And operator will always evaluate both ( combined ) expressions.
The version with the two nested Ifs will only evaluate value2 > 0 in worst case scenario ( if value1 > 0 is
correct ).

Later on we'll see how the 'AndAlso' operator can be used to avoid unnecessary checks.

Disjunction Operator Or

Suppose we need to give the sum of two entered values if at least one of the values is positive ( above zero ).

Module Example5
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
Else
If value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode
Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10
Sum : 5

Output :
Value 1 ?
5
Value 2 ?
-10
Sum : -5

Output :
Value 1 ?
-5
Value 2 ?
-10

Again by using two nested Ifs this result can be achieved.

ElseIf can also be used.

Module Example6
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
ElseIf value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10
Sum : 5

Output :
Value 1 ?
5
Value 2 ?
-10
Sum : -5

Output :
Value 1 ?
-5
Value 2 ?
-10

Another solution could use the logical operator Or.


This operator combines two Boolean expressions and results in one Boolean expression.

Module Example7
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 Or value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15

Output :
Value 1 ?
-5
Value 2 ?
10
Sum : 5

Output :
Value 1 ?
5
Value 2 ?
-10
Sum : -5

Output :
Value 1 ?
-5
Value 2 ?
-10

When at least one of the combined conditions is True the result will be True :

condition-1 condition-2 condition-1 Or condition-2


True True True
True False True
False True True
False False False

Negation Operator Not


Following example prints out all values from 1 to 10.

Module Example8
Sub Main()
Dim value As Integer
'
Do While value < 10
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

When we want to convert the Do While to a Do Loop, we need to invert the condition.

A value is not less than 10 only when it is more than 10 or equal to 10.

Module Example9
Sub Main()
Dim value As Integer
'
Do Until value >= 10
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

An easier way to invert a condition is by using the negation operator Not.


This operator inverts one Boolean expression.

condition-1 Not condition-1


True False
False True

Module Example10
Sub Main()
Dim value As Integer
'
Do Until Not value < 10
value = value + 1
Console.WriteLine(value)
Loop
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1
2
3
4
5
6
7
8
9
10

Boolean Logical
Suppose we need to give the sum of two entered values if the first value is not more than 10 and the second
value is not less than or equal to 100.

The condition Not value1 > 10 And Not value2 <= 100 can be used.

Module Example1
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If Not value1 > 10 And Not value2 <= 100 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
11
Value 2 ?
200

Output :
Value 1 ?
9
Value 2 ?
200
Sum : 209

Equal resulting conditional expressions are value1 <= 10 And value2 > 100 and Not (value1 >
10 Or value2 <= 100) ( parentheses are required ).

Module Example2
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If Not (value1 > 10 Or value2 <= 100) Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
11
Value 2 ?
200

Output :
Value 1 ?
9
Value 2 ?
200
Sum : 209

Lets examine some situations to see if both solutions will result in identical behaviour.

Suppose the first value is 11 and the second value is 200. The first value exceeds 10, so no sum may be
printed out.

Output :
Value 1 ?
11
Value 2 ?
200

Not value1 > 10 And Not value2 <= 100 with value1 11 and value2 200 :
= Not 11 > 10 And Not 200 <= 100
= Not True And Not False
= False And True
= False
No sum will be printed out.

Not (value1 > 10 Or value2 <= 100) with value1 11 and value2 200 :
= Not (11 > 10 Or 200 <= 100)
= Not (True Or False)
= Not True
= False
No sum will be printed out.
Suppose the first value is 9 and the second value is 200. In this case the sum may be printed out.

Output :
Value 1 ?
9
Value 2 ?
200
Sum : 209

Not value1 > 10 And Not value2 <= 100 with value1 9 and value2 200 :
= Not 9 > 10 And Not 200 <= 100
= Not False And Not False
= True And True
= True
The sum will be printed out.

Not (value1 > 10 Or value2 <= 100) with value1 9 and value2 200 :
= Not (9 > 10 Or 200 <= 100)
= Not (False Or False)
= Not False
= True
The sum will be printed out.

Generally :

Not X And Not Y = Not (X Or Y)

And :

Not X Or Not Y = Not (X And Y)

These are called the rules of "De Morgan".

These rules can also be proven by following truth table :

Not X And Not Y = Not (X Or Y) :

X | Y | Not X | Not Y | X Or Y | Not X And Not Y | Not (X Or Y)


True | True | False | False | True | False | False
True | False | False | True | True | False | False
False | True | True | False | True | False | False
False | False | True | True | False | True | True
Last two columns have identical result, so :

Not X And Not Y = Not (X Or Y)

For :

Not X Or Not Y = Not (X And Y) :

X | Y | Not X | Not Y | X And Y | Not X Or Not Y | Not (X And Y)


True | True | False | False | True | False | False
True | False | False | True | False | True | True
False | True | True | False | False | True | True
False | False | True | True | False | True | True

Last two columns have identical result, so :

Not X Or Not Y = Not (X And Y)

Beside the rules of De Morgan other rules exist to simplify conditional expressions.

p And False = False


p Or False = p
p And True = p
p Or True = True
p And p = p
p Or p = p
p And (Not p) = False
p Or (Not p) = True
Not (Not p) = p

Commutativity :

(p And q) = (q And p) -> And is commutative


(p Or q) = (q Or p) -> Or is commutative

Distributivity :

p And (q Or r) = (p And q) Or (p And r) -> And distributes over Or


p Or (q And r) = (p Or q) And (p Or r) -> Or distributes over And
Associativity :

p And (q And r) = (p And q) And r -> And is associative


p Or (q Or r) = (p Or q) Or r -> Or is associative

Logical Disjunction Operator Xor

An "exclusive or" operator Xor exists. A combination of two Boolean expressions with this operator will only
result in True when exactly one of the two combined expressions is True :

condition-1 condition-2 condition-1 Xor condition-2


False False False
False True True
True False True
True True False

Suppose we need to give the sum of two entered values only if exactly one of the two values is positive ( above
zero ).

Module Examplel
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 Xor value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
-10
Sum : -5
Output :
Value 1 ?
-5
Value 2 ?
10
Sum : 5

Output :
Value 1 ?
5
Value 2 ?
10

Output :
Value 1 ?
-5
Value 2 ?
-10

Logical Shortcircuit Operator AndAlso

Suppose we need to give the sum of two entered values only if both values are positive ( above zero ).

Module Example1
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 And value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15
Output :
Value 1 ?
-5
Value 2 ?
10

Output :
Value 1 ?
5
Value 2 ?
-10

Output :
Value 1 ?
-5
Value 2 ?
-10

A more efficient solution would use the short-circuit conjunction operator AndAlso.

Module Example2
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 > 0 AndAlso value2 > 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Value 1 ?
5
Value 2 ?
10
Sum : 15
Output :
Value 1 ?
-5
Value 2 ?
10

Output :
Value 1 ?
5
Value 2 ?
-10

Output :
Value 1 ?
-5
Value 2 ?
-10

The result will always be False if the first evaluated condition is False :

condition-1 condition-2 condition-1 And(Also) condition-2


True True True
True False False
False True False
False False False

AndAlso will only evaluate the second condition if the first condition is True.

Logical Shortcircuit Operator AndAlso

The short-circuit disjunction operator OrElse will only evaluate the second condition if the first condition
is False. The result will always be True if the first condition is True.

condition-1 condition-2 condition-1 Or(Else) condition-2


True True True
True False True
False True True
False False False

To improve performance short-circuit operators ( AndAlso and OrElse ) should be used when available.
Only in a few rare circumstances the normal operators ( And and Or ) are needed. Later more about this
circumstances.

Exercises

Task :

Give the sum of two entered values only if exactly one value is positive ( above zero ).

Do this without using the Xor operator.

Output :
Value 1 ?
5
Value 2 ?
-10
Sum : -5

Output :
Value 1 ?
-5
Value 2 ?
10
Sum : 5

Output :
Value 1 ?
5
Value 2 ?
10

Output :
Value 1 ?
-5
Value 2 ?
-10

Solution :

Module Exercise1Solution
Sub Main()
Console.WriteLine("Value 1 ?")
Dim value1 As Integer = Console.ReadLine()
'
Console.WriteLine("Value 2 ?")
Dim value2 As Integer = Console.ReadLine()
'
If value1 <> 0 AndAlso Not value2 <> 0 OrElse _
Not value1 <> 0 AndAlso value2 <> 0 Then
Console.WriteLine("Sum : " & (value1 + value2))
End If
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Task :

Make a program that calculates the sum of all entered values, while values are entered that are between 10
and 20, more than 100 or smaller than or equal to 0.

Do this with a Do While and a Do Loop.

Output :
Value ?
15
Value ?
150
Value ?
0
Value ?
-5
Value ?
5
Sum : 160

Solution :

Module Exercise2Solution
Sub Main()
Dim value, sum As Integer
'
' 'Do While ... Loop' :
Do While (value > 10 AndAlso value < 20) OrElse _
(value > 100) OrElse (value <= 0)
sum = sum + value
Console.WriteLine("Value ?")
value = Console.ReadLine()
Loop
'
'' 'Do Until ... Loop' : version 1 :
'Do Until Not ((value > 10 AndAlso value < 20) OrElse _
' (value > 100) OrElse (value <= 0))
' sum = sum + value
' Console.WriteLine("Value ?")
' value = Console.ReadLine()
'Loop
'
'' 'Do Until ... Loop' : version 2 :
'Do Until (value <= 10 OrElse value >= 20) AndAlso _
' (value <= 100) AndAlso (value > 0)
' sum = sum + value
' Console.WriteLine("Value ?")
' value = Console.ReadLine()
'Loop
'
Console.WriteLine("Sum : " & sum)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

D2 na me… >>> e2 po ay for machine experiment no.2 thanks LORD

Operators
Operator Precedence

An expression can be composed of many subexpressions combined with different operators. Some
subexpressions are evaluated before other subexpressions are evaluated. The order in which these
subexpressions are evaluated is based on the priority of the used operator.

The two operators with highest priority are ^ and - ( ^ has a higher priority than - ) :

1 -> '^' ( exponentiation )


2 -> '-' ( unary negation )

The order in which expressions combined with these operators are evaluated can be confusing, some examples to
illustrate this :

Module Example1
Sub Main()
Dim x As Integer = 2
Dim y As Integer = 3
'
Console.WriteLine(x ^ -y)
'
y = -3
'
Console.WriteLine(x ^ -y)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
0,125
8

'x ^ -y' with 'x' 2 and 'y' 3 -> 2 ^ -3 = 1 / (2 ^ 3) = 0.125


'x ^ -y' with 'x' 2 and 'y' -3 -> 2 ^ +3 = = 8

Before the power can be calculated, then y has to be negated.

Module Example2
Sub Main()
Dim x As Integer = -2
Dim y As Integer = 4
'
Console.WriteLine(-x ^ y)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
-16

'-x ^ y' with 'x' -2 and 'y' -> -(-2 ^ 4) = -16

In normal mathematics this would result in +16.

The exponential operator precedes ( in priority ) the negation operator.

Priority List :

1. arithmetic and concatenation operators :

1.a -> '^' ( exponentiation )


1.b -> '-' ( unary negation )
1.c -> '*' ( multiplication ) and / ( division )
1.d -> '\' ( integer division )
1.e -> 'Mod' ( modulus )
1.f -> '+' ( addition ) and - ( subtraction )
1.g -> '&' ( string concatenation )

2. comparison operators, with identical priority :

-> '=', '<>', '<', '<=', '>' and '>='

3. logical operators :

3.a -> 'Not' ( negation )


3.b -> 'And' and 'AndAlso' ( conjunction )
3.c -> 'Or', 'OrElse' and 'Xor' ( disjunction )

When on the same line, the operators have identical priority. These will be evaluated from left to right.

Parentheses can be used to alter the priority. Often these are also used for readability.

Module Example3
Sub Main()
Console.WriteLine(Not 10 * -4 / 2 ^ 2 + 11 = 8 Mod 10 \ -5 ^ 2 / 5 + 1 _
OrElse -8 ^ -2 <= 1 AndAlso True = False)
' exponentiation and unary negation :
' 2 ^ 2 -> 4
' -5 ^ 2 -> -(5 ^ 2) -> -25
' -8 ^ -2 -> -(8 ^ -2) -> -0.015625
Console.WriteLine(Not 10 * -4 / 4 + 11 = 8 Mod 10 \ -25 / 5 + 1 _
OrElse -0.015625 <= 1 AndAlso True = False)
' multiplication :
' 10 * -4 -> -40
Console.WriteLine(Not -40 / 4 + 11 = 8 Mod 10 \ -25 / 5 + 1 _
OrElse -0.015625 <= 1 AndAlso True = False)
' division :
' -40 / 4 -> -10
' -25 / 5 -> -5
Console.WriteLine(Not -10 + 11 = 8 Mod 10 \ -5 + 1 _
OrElse -0.015625 <= 1 AndAlso True = False)
' integer division :
' 10 \ -5 -> -2
Console.WriteLine(Not -10 + 11 = 8 Mod -2 + 1 _
OrElse -0.015625 <= 1 AndAlso True = False)
' modulus
' 8 Mod -2 -> 0
Console.WriteLine(Not -10 + 11 = 0 + 1 _
OrElse -0.015625 <= 1 AndAlso True = False)
' addition and subtraction :
' -10 + 11 -> 1
' 0 + 1 -> 1
Console.WriteLine(Not 1 = 1 OrElse -0.015625 <= 1 AndAlso True = False)
' comparison :
' 1 = 1 -> True
' -0.015625 <= 1 -> True
' True = False -> False
Console.WriteLine(Not True OrElse True AndAlso False)
' negation :
' Not True -> False
Console.WriteLine(False OrElse True AndAlso False)
' conjunction :
' True AndAlso False -> False
Console.WriteLine(False OrElse False)
' disjunction :
' False OrElse False -> False
Console.WriteLine(False)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Compound Assignment Operators

Although we have only used assignmentoperator =, other assignmentoperators exist.

Operator += for instance will combine an addition with an assignment :

value += 1

is identical to

value = value + 1

Other combined ( numeric ) operators are -=, *=, /=, \= and ^=.

Module Example4
Sub Main()
Dim value As Integer = 2
'
value *= 3 + 4 ' (1)
'
Console.WriteLine(value)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
14
Line (1) can also be written as :

value = value * (3 + 4)

For Strings a comparison operator exists : &=.

Module Example5
Sub Main()
Dim message As String = "Hello"
'
message &= " World !"
'
Console.WriteLine(message)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Hello World !

Logical Bitwise Operators

Logical operators Not, And, Or and Xor can handle integral operands in a bitwise fashion. These bitwise
operations handle the operands in binary format.

Module Example6
Sub Main()
Console.WriteLine(7 And 10)
Console.WriteLine(7 Or 10)
Console.WriteLine(7 Xor 10)
'
Console.WriteLine(7 And Not 7)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
2
15
13
0

The corresponding bits ( of the binary format ) of the operands are used for the operation :

X Y X And Y X Or Y X Xor Y Not X


0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

For And, Or and Xor :

111 And 1010 111 Or 1010 111 Xor 1010


Binary : 111 1010 0010 1111 1101
Decimal : 7 10 2 15 13

For Not

Decimal : 7
=
sign bit value bits
Binary : 0 000 0000 0000 0000 0000 0000 0000 0111

Not 7
=
sign bit value bits
Binary : 1 111 1111 1111 1111 1111 1111 1111 1000
Decimal : -8

7 And Not 7
Binary :
0000 0000 0000 0000 0000 0000 0000 0111
And
1111 1111 1111 1111 1111 1111 1111 1000
=
0000 0000 0000 0000 0000 0000 0000 0000
Decimal : 0

The 'AndAlso' and 'OrElse' operators don't support bitwise operations.

Every operand of a bitwise operator needs to be an integral value.


Why Use Bitwise Operators
Although nowadays programs rarely use data-units smaller then one byte, it could happen you want to handle
individual bits. Bitwise operations can be used for this type of situations.

Saving memory and performance improvement are the main advantages.

Suppose we need to manage the state of a "tamagotchi". Possible states are "happy", "thirsty", "hungry", and
"tired".

A Boolean variable could be used to represent a state.

An alternative would be to combine all individual states into one variable.

This is how the states could be represented :

state : binary representation : decimal value :


"happy" 0001 1
"thirsty" 0010 2
"hungry" 0100 4
"tired" 1000 8

Decimal value 4 indicates that the tamagotchi is hungry, but also that the tamagotchi is not happy, thirsty or tired.

Decimal value 9 indicates that the tamagotchi is happy and tired, and not thirsty or hungry.

Module Example7
Sub Main()
Dim tamagotchiState As Integer = 5
' ...
If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry") ' (1)
If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
Console.WriteLine()
'
Console.WriteLine("making tamagotchi not hungry ...")
tamagotchiState = tamagotchiState And Not 4 ' (2)
Console.WriteLine()
'
If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
Console.WriteLine()
'
Console.WriteLine("making tamagotchi thirsty ...")
tamagotchiState = tamagotchiState Or 2 ' (3)
Console.WriteLine()
'
If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
Console.WriteLine()
'
Console.WriteLine("making tamagotchi happy, hungry and tired ...")
tamagotchiState = tamagotchiState Or 1 Or 4 Or 8
Console.WriteLine()
'
If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
Console.WriteLine()
'
Console.WriteLine("making tamagotchi not hungry and not tired ...")
tamagotchiState = tamagotchiState And Not 4 And Not 8
Console.WriteLine()
'
If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
Console.WriteLine()
'
Console.WriteLine("inverting states ...")
tamagotchiState = Not tamagotchiState
Console.WriteLine()
'
If (tamagotchiState And 1) = 1 Then Console.WriteLine("happy")
If (tamagotchiState And 2) = 2 Then Console.WriteLine("thirsty")
If (tamagotchiState And 4) = 4 Then Console.WriteLine("hungry")
If (tamagotchiState And 8) = 8 Then Console.WriteLine("tired")
'
Console.ReadLine()
End Sub
End Module
Download Broncode

The And operator can be used to check whether the tamagotchi is in a particular state (1).

The expression tamagotchiState And 4 will only evaluate to 4 if the third bit from the right
of tamagotchiState is 1.
So (tamagotchiState And 4) = 4 will only evaluate to True if the tamagotchi is in that state.

Generally :

If (tamagochiState And state) = state Then


... tamagochi is in state ...
Else
... tamagochi is not in state ...
End If

For line (1) :

tamagotchiState 5 0101
And
"hungry" 4 0100
=
0100

When we want to remove the individual state hungry from the tamagotchi we can combine the old state with the
negation of the state to remove (2). Whether the tamagotchi is hungry or not, the result will be not hungry.

"hungry" = 4 = 0100 -> Not 4 = Not 0100 = 1011


'tamagotchiState' "not hungry" = 0000 -> 0000 And 1011 = 0000 ( "not hungry" )
'tamagotchiState' "hungry" = 0100 -> 0100 And 1011 = 0000 ( "not hungry" )

To add the individual state thirsty, we can simple add 2 to the old state of the tamagotchi :

tamagotchiState += 2

When the old tamagotchi state would be 2, and we add 2, the result is 4, or "hungry" and not "not thirty".

To add individual state thirsty ( 2 ) we can :

tamagotchiState = tamagotchiState Or 2

The result will always contain state thirsty :

"thirsty" = 2 = 0010
'tamagotchiState' "not thirsty" = 0000 -> 0000 Or 0010 = 0010 ( "thirsty" )
'tamagotchiState' "thirsty" = 0010 -> 0010 Or 0010 = 0010 ( "thirsty" )

Bitshift Operators

Bitshift operators >> and << shift the bits of an integral operand ( left operand ) to the right ( >> ) of left ( << ). How
many positions the bits are shifted is defined by the right operand.

Module Example8
Sub Main()
Console.WriteLine(7 << 2)
Console.WriteLine(7 >> 1)
'
Dim number As Integer = 7
number <<= 2 ' (1)
Console.WriteLine(number)
number = 7
number >>= 1 ' (2)
Console.WriteLine(number)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
28
3
28
3

When the bits of 111 ( decimal 7 ) are shifted 2 positions to the left, the result is 11100 ( decimal 28 ). The extra
bits on the right, are zero bits.
Shifting 1 bit to the left, is equal to multiplying the value with 2.

When the bits of 111 ( decimal 7 ) are shifted 1 position to the right, the result is 11 ( decimal 3 ).
Shifting 1 bit to the right, is equal to dividing the value by 2.

These forms of multiplication ( by 2 ) and dividing ( by 2 ) are more efficient than the normal multiplication and
division operations.

Bitshift and Assignment Operators

<<= ( see line (1) ) and >>= ( see line (2) )

Why Use Bitshift Operators

Suppose we need to know the position of the rightmost one-bit of a given value. The operators And and >> could
be used to determine that position (1).

An alternative would be to count how many time one can divide the value by 2 until the remainder of the division by
2 is 0 (2).

Module Example9
Sub Main()
Dim value As Integer
Dim position As Integer
Dim counter As Integer
Dim start As Integer
'
value = 12
position = 1
Do While (value And 1) = 0 ' (1)
value >>= 1
position += 1
Loop
Console.WriteLine("12 : Bit at position " & position & _
" from the right is 1.")
'
value = 12
position = 1
Do While value Mod 2 <> 1 ' (2)
value /= 2
position += 1
Loop
Console.WriteLine("12 : Bit at position " & position & _
" from the right is 1.")
'
start = Environment.TickCount()
For counter = 1 To 10000000 ' (3)
value = counter
position = 0
'
Do While (value And 1) = 0 ' (1)
value >>= 1
position += 1
Loop
Next
Console.WriteLine("Bitwise calculation done in " & _
Environment.TickCount() - start & " tickcounts.")
'
start = Environment.TickCount()
For counter = 1 To 10000000 ' (3)
value = counter
position = 0
'
Do While value Mod 2 <> 1 ' (2)
value /= 2
position += 1
Loop
Next
Console.WriteLine("Normal calculation done in " & _
Environment.TickCount() - start & " tickcounts.")
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
12 : Bit at position 3 from the right is 1.
12 : Bit at position 3 from the right is 1.
Bitwise calculation done in 125 tickcounts.
Normal calculation done in 499 tickcounts.

The above output can be slightly different on your system, but you will see how the bitwise calculation (1) is done a
lot faster than the normal _-
calculation (2).
Exercises

Task :

Try to simplify following conditional expressions.

You can do this by using a truth table.

-> p Or (p And q)
-> p And (p Or q)
-> p And ((Not p) Or q)
-> p Or Not p And q
-> Not p Or p And q
-> Not p Or p And Not q

Solution :

-> p Or (p And q)

p | q | p And q | p Or (p And q)
True | True | True | True
True | False | False | True
False | True | False | False
False | False | False | False

Column 1 and column 4 have identical results, so :

p Or (p And q) = p

-> p And (p Or q)

p | q | p Or q | p And (p Or q)
True | True | True | True
True | False | True | True
False | True | True | False
False | False | False | False

Column 1 and column 4 have identical results, so :

p And (p Or q) = p

-> p And ((Not p) Or q)

p | q | Not p | (Not p) Or q | p And ((Not p) Or q)


True | True | False | True | True
True | False | False | False | False
False | True | True | True | False
False | False | True | True | False

Column 5 shows us how the result is only True if p and q are True, just like the result of p And q would be :

p | q | p And ((Not p) Or q) | p And q


True | True | True | True
True | False | False | False
False | True | False | False
False | False | False | False

Column 3 and column 4 have identical results, so :

p And ((Not p) Or q) = p And q

-> p Or Not p And q

p | q | Not p | Not p And q | p Or Not p And q


True | True | False | False | True
True | False | False | False | True
False | True | True | True | True
False | False | True | False | False

Column 5 shows us how the result is only False if p and q are False, just like the result of p Or q would be :

p | q | p Or Not p And q | p Or Q
True | True | True | True
True | False | True | True
False | True | True | True
False | False | False | False

Column 3 and column 4 have identical results, so :

p Or Not p And q = p Or q

-> Not p Or p And q

p | q | Not p | p And q | Not p Or p And q


True | True | False | True | True
True | False | False | False | False
False | True | True | False | True
False | False | True | False | True

For the row with result False you could state :


Not p Or p And q = False

only if

p and Not q

p | q | Not q | p And Not q | Not p Or p And q


True | True | False | False | True
True | False | True | True | False
False | True | False | False | True
False | False | True | False | True

Column 4 is the negation of column 5, so :

Not p Or p And q = Not (p And Not q) = Not p Or q

-> Not p Or p And Not q

p | q | Not p | Not q | p And Not q | Not p Or p And Not q


True | True | False | False | False | False
True | False | False | True | True | True
False | True | True | False | False | True
False | False | True | True | False | True

Only for row p And q ( p is True and q is True ) the result is False, so :

Not p Or p And Not q

is always True if

Not (p And q)

or

Not p Or Not q

Task :
What will be the output of following module ?

Module Exercise2Task
Sub Main()
Dim value1, value2, value3 As Integer
'
value1 += 5
value2 -= value1 * 6 + 1
value3 += value1 + 5 * value2
value3 *= value3 / -3
value1 /= 1 / (value2 + 41)
value2 \= 10 + value1 / 5
'
Console.WriteLine(value1) ' ?
Console.WriteLine(value2) ' ?
Console.WriteLine(value3) ' ?
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Solution :

Module Exercise2Solution
Sub Main()
Dim value1, value2, value3 As Integer
'
value1 += 5
' value1 = value1 + 5
' = 0 + 5
' = 5
value2 -= value1 * 6 + 1
' value2 = value2 - (value1 * 6 + 1)
' = 0 - (5 * 6 + 1)
' = 0 - (30 + 1)
' = -31
value3 += value1 + 5 * value2
' value3 = value3 + (value1 + 5 * value2)
' = 0 + (5 + 5 * -31)
' = 0 + (5 + -155)
' = 0 + -150 = -150
value3 *= value3 / -3
' value3 = value3 * (value3 / -3)
' = -150 * (-150 / -3)
' = -150 * 50
' = -7500
value1 /= 1 / (value2 + 41)
' value1 = value1 / (1 / (value2 + 41))
' = 5 / (1 / (-31 + 41))
' = 5 / (1 / 10)
' = 50
value2 \= 10 + value1 / 5
' value2 = value2 \ (10 + value1 / 5)
' = -31 \ (10 + 50 / 5)
' = -31 \ (10 + 10)
' = -31 \ 20
' = -1
'
Console.WriteLine(value1) ' 50
Console.WriteLine(value2) ' -1
Console.WriteLine(value3) ' -7500
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
50
-1
-7500

Numeric Integral Datatypes - Byte Short Integer Long

To represent integral values ( without digits after the decimal separator ) :

Byte Byte 1 byte 0 <-> 255 ( unsigned )


SByte SByte 1 byte -128 <-> +127 ( signed )

Short Int16 2 bytes -32,768 <-> +32,767 ( signed )


UShort UInt16 2 bytes 0 <-> 65,535 ( unsigned )

Integer Int32 4 bytes -2,147,483,648 <-> +2,147,483,647 ( signed )


about -2 to +2 billion ( short scale )
about -2 to +2 milliard ( long scale )
UInteger UInt32 4 bytes 0 <-> 4,294,967,295 ( unsigned )
0 to about 4 billion ( short scale )
0 to about 4 milliard ( long scale )

Long Int64 8 bytes -9,223,372,036,854,775,808 <->


+9,223,372,036,854,775,807 ( signed )
about -9 to +9 quintillion ( short scale )
about -9 to +9 trillion ( long scale )
ULong UInt64 8 bytes 0 <-> 18,446,744,073,709,551,615 ( unsigned )
0 to about 18 quintillion ( short scale )
0 to about 18 trillion ( long scale )

The first column contains the Visual Basic names for these datatypes. These are specific for the use within the
language Visual Basic.
The second column contains the .NET names for these datatypes. These can also be used within each CLR (
Common Language Runtime ) compliant language ( including Visual Basic ).
All .NET languages use common datatypes, these datatypes are defined in the CLT ( Common Language Types )
of .NET.
The S and U prefixes stand for "Signed" and "Unsigned", indicating whether or not a sign-bit is used for these
datatypes.

Unsigned Integral Datatypes

Unsigned datatype Byte internally uses 1 byte ( or 8 bits ) to represent its value. If 8 bits can be either 0 or 1, 2^8 (
or 256 ) possible values can be represented.
Starting with 0 ( [0000 0000] ), up to 255 ( [1111 1111] ).

Signed Integral Datatypes

The most significant bit ( MSB ) ( leftmost bit ) is used for the sign. Positive is indicated with 0, negative with 1. All
other bits ( for instance all 7 other bits of type 'SByte' ) are used to represent the value in two's compliment.

We know condition 7 And Not 7 = 0 evaluates to True. 7 is binary represented as [0000 0111], Not 7 must
then be [1111 1000], because [0000 0111] And [1111 1000] results in [0000 0000].
The first [1] of [1111 1000] indicates this is a negative value. The rest of of the bits [111 1000] is in twos
compliment, so well have to invert then and add [1], so [000 0111] + [1] results in [000 1000] ( or 8). Not 7 is -
8.

Some numbers in SByte representation :

sign-bit
0 -> [0 000 0000]

+1 -> [0 000 0001]


+2 -> [0 000 0010]
+126 -> [0 111 1110]
+127 -> [0 111 1111] -> maximum value

-1 -> [1 111 1111]


-2 -> [1 111 1110]
-126 -> [1 000 0010]
-127 -> [1 000 0001]
-128 -> [1 000 0000] -> minimum value

All other unsigned integral datatypes ( Short, Integer en Long ) use identical internal representation, but use
more bits for it, leading to larger values that can be represented.

Numeric Decimal Datatypes - Single Double Decimal

To represent numbers with digits after the decimal separator :


Single 4 bytes ( 32-bit floating-point notation )
range : negative values : -3.4028235E+38 <-> -1.401298E-45
zero
positive values : +1.401298E-45 <-> +3.4028235E+38

Double 8 bytes ( 64-bit floating-point notation )


range : negative values : -1.7976931348623157E+308 <->
-4.94065645841247E-324
zero
positive values : +4.94065645841247E-324) <->
+1.7976931348623157E+308

Decimal 16 bytes ( 128-bit floating-point notation ( base 10 ) )


range ( without digits after the decimal separator ) :
-79228162514264337593543950335 <->
+79228162514264337593543950335
range ( with maximum 28 digits after the decimal separator ) :
-7.9228162514264337593543950335 <->
+7.9228162514264337593543950335
smallest values : -0.0000000000000000000000000001 ( -1E-28 ) and
+0.0000000000000000000000000001 ( +1E-28 )

The E followed by a number is the technical and scientific notation for the exponent for base 10. 2E-3 for instance
is 2 x 10^-3 or 0.002.

All floating-point notations ( and arithmetic's ) follow the IEEE 754 standard.

Module Example1
Sub Main()
Dim someDouble As Double = 1.5 ' (1)
Console.WriteLine(someDouble)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1,5

Use Decimal when high precision and accuracy is needed, for instance in financial applications. Be aware of the
performance overhead, Decimal is by far the slowest and memory consuming numeric datatype. When
performance is important, use Double, which on current platforms leads to the best performance.

Line (1) illustrates how the decimal separator is a dot ( . ).

Which decimal separator symbol will be used on the console depends on the culture-info. With the above output I
assume the decimal separator is a comma ( , ).
Floating Point Notation - Single Double Decimal

Floating Point Notation - Problems

Following example tries to calculate the units ( bills and coins ) of a certain Euro amount.

Module Example1
Sub Main()
Dim units As Single() = _
{500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01}
'
Dim amount As Single = 0.06
Console.Write(amount & " : ")
'
Dim index As Integer
Do While amount > 0
Do While amount - units(index) >= 0
Console.Write(units(index) & " ")
amount -= units(index)
Loop
index += 1
Loop
Console.WriteLine()
'
Console.ReadLine()
End Sub
End Module
Download Broncode

An exception ( runtime error ) IndexOutOfRangeException occurs at index 15. When looking at the above
example, you would expect that on index 14 amount would be 0, so index 15, which is indeed out of range,
would never be reached.
When 'index' reaches, and 'units(index)' evaluates to 0.05, subtraction 0.06 - 0.05 happens, this doesn't lead to
0.01, but to 0.009999998.

Certain floating point operations can have strange results. These strange results can be unexpected when you
don't know anything about floating point operations.

The strange result are usually the caused by the internal representation of the values. Some decimal values ( base
10 ) can never be exactly represented in these floating point datatypes. Often the values need to be approximated,
so round off error can be produced when operations on these values occur.

For instance value 1/3 can in decimal scale ( base 10 ) never be exactly represented in its normal representation :
0.333...
Every 3 you add makes it more precise, but it will never be completely accurate.
1/10 for instance can never be completely represented in a binary scale ( base 2 ) : 0.00011001100110011... ( the
0011 part infinitely repeats ).

What ever the scale you use, there will always be values that are impossible to represent exactly and completely.
Irrational numbers ( number which cannot be expressed as a fraction ) are particularly hard to represent, for
instance some squareroots, the constant pi, the constant e, ... .
All rational numbers could exactly be represented if both the divisor and dividend are stored. But irrational numbers
can not be stored this way.

No schema with finite capacity can ever represent all decimal values exactly. It is impossible to represent an infinite
range of values in a finite amount of bits.

Most environments ( also .NET ) use floating point notation to represent decimal values. This is not a perfect
system, but by implementing the IEEE 754 standard for floating point notations, .NET at least guarantees
standardised techniques are be used to approximate values, and to perform operations on approximated values.

In the following example other strange results are produced.

Module Example2
Sub Main()
Console.WriteLine(2.0 Mod 0.2 = 0)
Console.WriteLine(2.0 Mod 0.2)
'
Dim someSingle As Single = 4.99
Console.WriteLine(someSingle * 17 = 84.83)
Console.WriteLine(someSingle * 17)
'
someSingle = 1 / 107.0
Console.WriteLine(someSingle * 107 = 1)
Console.WriteLine(someSingle * 107)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
False
0,2
False
84,82999
False
0,9999999

Floating Point Notation - Representation

IEEE 754 Single Precision ( like Single in .NET ) :

1 bit for the sign (s) + 8 bits for the exponent (e) + 23 bits for the mantissa (m) = 32 bits

Some remarks about the following notations :


- binary values are between square brackets ( for instance [0101] )
- symbol ~ is used for approximation

Binary format :
seee eeee emmm mmmm mmmm mmmm mmmm mmmm

Different representations are used within floating point :

- normalised
- zero ( negative and positive zero )
- subnormal ( denormalised )
- infinity ( positive and negative infinity )
- not-a-number ( NaN )

Normalised Representation :

This representation is used for most values.

General formula :

(-1)^[s] * [1.mmmm mmmm mmmm mmmm mmm] * 2^[eeee eeee]

Sign :

[0] (-1)^0 = 1
or
[1] (-1)^1 = -1

Exponent :

The exponent is stored as an unsigned byte value. To be ably to represent small values ( with negative exponent ),
an offset ( also called bias ) of - 127 is used.

Some possible representations :

[0000 0000] = 0 -> reserved for other representations


[0000 0001] = 1 - 127 = -126 -> minimum exponent
...
[0111 1110] = 126 - 127 = -1
[0111 1111] = 127 - 127 = 0
[1000 0000] = 128 - 127 = 1
...
[1111 1110] = 254 - 127 = 127 -> maximum exponent
[1111 1111] = 255 -> reserved for other representations

Exponents 0 en 255 are reserved for other representations, later more about these reserved values.

Mantissa :

Number 0,5 could be represented as 1 * 2^-1 or as 0.5 * 2^0 or as 0.25 * 2^1 or as 0.125 * 2^2 or as ... . By dividing
the mantissa by 2, and adding 1 to the exponent, the same result is reached.
In other words, one value could have different representations, and room ( read : format representations ) for other
values is lost.
To avoid this, and to maximize the range of possible values that can be represented, the normalized representation
will maximize the significant, and minimize the exponent. This process is called normalization.

The significant is always preceded with [1.], so all 24 digits for the mantissa can be used to represent this mantissa.

Minimum value for the mantissa is :

[1.0000 0000 0000 0000 0000 000] or 1

Maximum value for the mantissa is :

[1.1111 1111 1111 1111 1111 111] or 1,999999940395355224609375 or 2^1 - 2^-24

Generally :

1 <= mantissa < 2

The minimum normalized value uses mantissa 1 and exponent -126 :

1 * 2^-126 or ~ 1,1754E-38 .

The maximum normalized value uses mantissa 1,999999940395355224609375 and exponent 127 :

1,999999940395355224609375 * 2^127 or ~ 3.4028E+38

Some possible representations of normalized values :

[0000 0000 1000 0000 0000 0000 0000 0000] or ~ 1,1754E-38


-> minimum positive value
...
[0011 1111 0000 0000 0000 0000 0000 0000] or 0,5
...
[0011 1111 0001 1001 1001 1001 1001 1010] or 0,6
...
[0111 1111 0111 1111 1111 1111 1111 1111] or ~ 3,4028E+38
-> maximum positive value -> 'Single.MaxValue'
...
[1000 0000 1000 0000 0000 0000 0000 0000] or ~ -1,1754E-38
-> minimum negative value
...
[1111 1111 0111 1111 1111 1111 1111 1111] or ~ -3,4028E+38
-> maximum negative value -> 'Single.MinValue'

0,5 will be represented with sign 1 ( or [0] ), mantissa 1 or [1.0000 0000 0000 0000 0000 000] ) and exponent -1 (
or [0111 1110] ), or 1 * 1 * 2^-1.

0,6 will be represented with sign 1 ( of [0] ), mantissa 1,1935484 or [1.0011 0011 0011 0011 0011 010] ) and
exponent -1 ( or [0111 1110] ), or 1 * 1,1935484 * 2^-1.

Representation of Zero :

How is zero represented? Neither the exponent, nor the mantissa can be zero, so the result ( multiplication of both
) can never be zero.

For zero two representations are reserved, one for positive zero and one for negative zero.

Both the significant and the exponent are 0 for the representation of zero.

[0000 0000 0000 0000 0000 0000 0000 0000] -> +0


[1000 0000 0000 0000 0000 0000 0000 0000] -> -0

Subnormal ( Denormalized ) Representation :

General formula :

(-1)^[s] * [0.mmmm mmmm mmmm mmmm mmm] * 2^-126

These representations are used to represent very small values.

Exponent :

The exponent is always [0000 0000] or 0, this 0 has no meaning ( except for being part of this representation ). The
value used for the exponent in this representation is always -126 ( equal to the minimum exponent in the
normalized representation ).

Mantissa :

The mantissa is not normalized. A prefix [0.] is always presumed.

The minimum mantissa is :

[0.0000 0000 0000 0000 0000 001] or 0,00000011920928955078125 or 2^-23

The maximum mantissa is :

[0.1111 1111 1111 1111 1111 111] or 0,999999940395355224609375 or 2^0 - 2^-24


The minimum denormalized value is :

0,00000011920928955078125 * 2^-126 or ~ 1,4012E-45

The maximum denormalized value is :

0,999999940395355224609375 * 2^-126 or ~ 1,1754E-38

[0000 0000 0000 0000 0000 0000 0000 0001] or ~ 1,4012E-45


-> minimum positive value -> 'Single.Epsilon'
...
[0000 0000 0111 1111 1111 1111 1111 1111] or ~ 1,1754E-38
-> maximum positive value
...
[1000 0000 0000 0000 0000 0000 0000 0001] or ~ -1,4012E-45
-> minimum negative value
...
[1000 0000 0111 1111 1111 1111 1111 1111] or ~ -1,1754E-38
-> maximum negative value

Representation of Infinities :

Exponent :

The exponent is always [1111 1111] or 255, this 255 has no meaning ( except for being part of this representation
).

Mantissa :

The mantissa is always [000 0000 0000 0000 0000 0000] or 0, this 0 has no meaning ( except for being part of this
representation ).

Sign :

The sign bit indicates positive or negative infinity.

[0111 1111 1000 0000 0000 0000 0000 0000] -> 'Single.PositiveInfinity'
[1111 1111 1000 0000 0000 0000 0000 0000] -> 'Single.NegativeInfinity'

Module Example3
Public Sub Main()
Console.WriteLine("seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm")
Console.WriteLine(GetBinary(1.17549435E-38F) & " : " & _
1.17549435E-38F.ToString())
Console.WriteLine(GetBinary(0.5F) & " : " & 0.5F.ToString())
Console.WriteLine(GetBinary(0.6F) & " : " & 0.6F.ToString())
Console.WriteLine(GetBinary(Single.MaxValue) & " : " & _
Single.MaxValue.ToString())
Console.WriteLine(GetBinary(-1.17549435E-38F) & " : " & _
-1.17549435E-38F.ToString())
Console.WriteLine(GetBinary(Single.MinValue) & " : " & _
Single.MinValue.ToString())
Console.WriteLine(GetBinary(0.0F) & " : " & 0.0F.ToString())
Console.WriteLine(GetBinary(-0.0F) & " : " & -0.0F.ToString())
Console.WriteLine(GetBinary(Single.Epsilon) & " : " & _
Single.Epsilon.ToString())
Console.WriteLine(GetBinary(-1.401298E-45F) & " : " & _
-1.401298E-45F.ToString())
Console.WriteLine(GetBinary(Single.PositiveInfinity) & " : " & _
Single.PositiveInfinity.ToString())
Console.WriteLine(GetBinary(Single.NegativeInfinity) & " : " & _
Single.NegativeInfinity.ToString())
'
Console.ReadLine()
End Sub
Public Function GetBinary(ByVal value As Byte) As String
For counter As Integer = 1 To 8
GetBinary = (value Mod 2).ToString() & GetBinary
value >>= 1
Next
End Function
Public Function GetBinary(ByVal value As Single) As String
If BitConverter.IsLittleEndian Then
For Each byteElement As Byte In BitConverter.GetBytes(value)
GetBinary = GetBinary(byteElement) & GetBinary
Next
Else
Throw New ApplicationException("Only Little Endian supported.")
End If
End Function
End Module
Download Broncode

Output :
seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm
00000000100000000000000000000000 : 1,175494E-38
00111111000000000000000000000000 : 0,5
00111111000110011001100110011010 : 0,6
01111111011111111111111111111111 : 3,402823E+38
10000000100000000000000000000000 : -1,175494E-38
11111111011111111111111111111111 : -3,402823E+38
00000000000000000000000000000000 : 0
10000000000000000000000000000000 : 0
00000000000000000000000000000001 : 1,401298E-45
10000000000000000000000000000001 : -1,401298E-45
01111111100000000000000000000000 : oneindig
11111111100000000000000000000000 : -oneindig

Operations on Zero, NaN and Infinity :

Operation on special values ( zero, NaN and infinity ) will according to the IEEE 754 standard have specific results.

Every operation using a NaN operand, will result in a NaN.

Other operations are illustrated by following example :


Module Example4
Sub Main()
Dim singleOperands As Single() = {Single.PositiveInfinity, _
Single.NegativeInfinity, _
123.0F, -123.0F, 0.0F, -0.0F}
Dim operatorSymbols As String() = {"*", "/", "+", "-"}
'
For Each operatorSymbol As String In operatorSymbols
Console.WriteLine("OPERATOR " & operatorSymbol.ToString())
Console.WriteLine()
For Each singleOperand1 As Single In singleOperands
For Each singleOperand2 As Single In singleOperands
PrintCalculation(singleOperand1, operatorSymbol, _
singleOperand2)
Next
Console.WriteLine()
Next
Console.WriteLine()
Next
'
Console.ReadLine()
End Sub
Sub PrintCalculation(ByVal operand1 As Single, _
ByVal operatorSymbol As String, _
ByVal operand2 As Single)
Console.Write(GetString(operand1) & " " & operatorSymbol & " " & _
GetString(operand2) & " = ")
Select Case operatorSymbol
Case "*"
Console.WriteLine(GetString(operand1 * operand2))
Case "/"
Console.WriteLine(GetString(operand1 / operand2))
Case "+"
Console.WriteLine(GetString(operand1 + operand2))
Case "-"
Console.WriteLine(GetString(operand1 - operand2))
End Select
End Sub
Function GetString(ByVal value As Single) As String
If IsPositiveZero(value) Then
GetString = "+0"
ElseIf IsNegativeZero(value) Then
GetString = "-0"
ElseIf Single.IsNegativeInfinity(value) Then
GetString = "-Infinity"
ElseIf Single.IsPositiveInfinity(value) Then
GetString = "+Infinity"
ElseIf Single.IsNaN(value) Then
GetString = "NaN"
Else
GetString = value.ToString()
End If
End Function
Public Function IsPositiveZero(ByVal value As Single) As Boolean
If BitConverter.GetBytes(value)(0) = 0 AndAlso _
BitConverter.GetBytes(value)(1) = 0 AndAlso _
BitConverter.GetBytes(value)(2) = 0 AndAlso _
BitConverter.GetBytes(value)(3) = 0 Then _
IsPositiveZero = True
End Function
Public Function IsNegativeZero(ByVal value As Single) As Boolean
If BitConverter.GetBytes(value)(0) = 0 AndAlso _
BitConverter.GetBytes(value)(1) = 0 AndAlso _
BitConverter.GetBytes(value)(2) = 0 AndAlso _
BitConverter.GetBytes(value)(3) = 128 Then _
IsNegativeZero = True
End Function
End Module
Download Broncode

Output :
OPERATOR *

+Infinity * +Infinity = +Infinity


+Infinity * -Infinity = -Infinity
+Infinity * 123 = +Infinity
+Infinity * -123 = -Infinity
+Infinity * +0 = NaN
+Infinity * -0 = NaN

-Infinity * +Infinity = -Infinity


-Infinity * -Infinity = +Infinity
-Infinity * 123 = -Infinity
-Infinity * -123 = +Infinity
-Infinity * +0 = NaN
-Infinity * -0 = NaN

123 * +Infinity = +Infinity


123 * -Infinity = -Infinity
123 * 123 = 15129
123 * -123 = -15129
123 * +0 = +0
123 * -0 = -0

-123 * +Infinity = -Infinity


-123 * -Infinity = +Infinity
-123 * 123 = -15129
-123 * -123 = 15129
-123 * +0 = -0
-123 * -0 = +0

+0 * +Infinity = NaN
+0 * -Infinity = NaN
+0 * 123 = +0
+0 * -123 = -0
+0 * +0 = +0
+0 * -0 = -0

-0 * +Infinity = NaN
-0 * -Infinity = NaN
-0 * 123 = -0
-0 * -123 = +0
-0 * +0 = -0
-0 * -0 = +0

OPERATOR /

+Infinity / +Infinity = NaN


+Infinity / -Infinity = NaN
+Infinity / 123 = +Infinity
+Infinity / -123 = -Infinity
+Infinity / +0 = +Infinity
+Infinity / -0 = -Infinity
-Infinity / +Infinity = NaN
-Infinity / -Infinity = NaN
-Infinity / 123 = -Infinity
-Infinity / -123 = +Infinity
-Infinity / +0 = -Infinity
-Infinity / -0 = +Infinity

123 / +Infinity = +0
123 / -Infinity = -0
123 / 123 = 1
123 / -123 = -1
123 / +0 = +Infinity
123 / -0 = -Infinity

-123 / +Infinity = -0
-123 / -Infinity = +0
-123 / 123 = -1
-123 / -123 = 1
-123 / +0 = -Infinity
-123 / -0 = +Infinity

+0 / +Infinity = +0
+0 / -Infinity = -0
+0 / 123 = +0
+0 / -123 = -0
+0 / +0 = NaN
+0 / -0 = NaN

-0 / +Infinity = -0
-0 / -Infinity = +0
-0 / 123 = -0
-0 / -123 = +0
-0 / +0 = NaN
-0 / -0 = NaN

OPERATOR +

+Infinity + +Infinity = +Infinity


+Infinity + -Infinity = NaN
+Infinity + 123 = +Infinity
+Infinity + -123 = +Infinity
+Infinity + +0 = +Infinity
+Infinity + -0 = +Infinity

-Infinity + +Infinity = NaN


-Infinity + -Infinity = -Infinity
-Infinity + 123 = -Infinity
-Infinity + -123 = -Infinity
-Infinity + +0 = -Infinity
-Infinity + -0 = -Infinity

123 + +Infinity = +Infinity


123 + -Infinity = -Infinity
123 + 123 = 246
123 + -123 = +0
123 + +0 = 123
123 + -0 = 123

-123 + +Infinity = +Infinity


-123 + -Infinity = -Infinity
-123 + 123 = +0
-123 + -123 = -246
-123 + +0 = -123
-123 + -0 = -123

+0 + +Infinity = +Infinity
+0 + -Infinity = -Infinity
+0 + 123 = 123
+0 + -123 = -123
+0 + +0 = +0
+0 + -0 = +0

-0 + +Infinity = +Infinity
-0 + -Infinity = -Infinity
-0 + 123 = 123
-0 + -123 = -123
-0 + +0 = +0
-0 + -0 = -0

OPERATOR -

+Infinity - +Infinity = NaN


+Infinity - -Infinity = +Infinity
+Infinity - 123 = +Infinity
+Infinity - -123 = +Infinity
+Infinity - +0 = +Infinity
+Infinity - -0 = +Infinity

-Infinity - +Infinity = -Infinity


-Infinity - -Infinity = NaN
-Infinity - 123 = -Infinity
-Infinity - -123 = -Infinity
-Infinity - +0 = -Infinity
-Infinity - -0 = -Infinity

123 - +Infinity = -Infinity


123 - -Infinity = +Infinity
123 - 123 = +0
123 - -123 = 246
123 - +0 = 123
123 - -0 = 123

-123 - +Infinity = -Infinity


-123 - -Infinity = +Infinity
-123 - 123 = -246
-123 - -123 = +0
-123 - +0 = -123
-123 - -0 = -123

+0 - +Infinity = -Infinity
+0 - -Infinity = +Infinity
+0 - 123 = -123
+0 - -123 = 123
+0 - +0 = +0
+0 - -0 = +0

-0 - +Infinity = -Infinity
-0 - -Infinity = +Infinity
-0 - 123 = -123
-0 - -123 = 123
-0 - +0 = -0
-0 - -0 = +0

Numeric Literals and Type Coercion


Numeric Literals without Type Coercion

Each literal expression ( without type coercion ) formed by an integral numeric value, will be regarded ( by the
compiler ) as anInteger or Long expression.

When the represented value falls out of the Integer range, it will be regarded as an Long expression ( at least if it
fits in the range ofLong ).

Each literal expression ( without type coercion ) formed by an numeric decimal ( with digits after the decimal
separator ), will be regarded ( by the compiler ) as an Double expression ( at least if it fits in the range
of Double ).

Module Example1
Sub Main()
Console.WriteLine("Integer :")
Console.WriteLine("Min Value : " & Integer.MinValue)
Console.WriteLine("Max Value : " & Integer.MaxValue)
Console.WriteLine("Max Literal Value : " & 2147483647)
Console.WriteLine()
'
Console.WriteLine("Long :")
Console.WriteLine("Min Value : " & Long.MinValue)
Console.WriteLine("Max Value : " & Long.MaxValue)
Console.WriteLine("Max Literal Value : " & 9223372036854775807)
Console.WriteLine()
'
Console.WriteLine("Double :")
Console.WriteLine("Negative Min ( Literal ) Value : " & _
-1.7976931348623157E+308) ' Double.MinValue
Console.WriteLine("Negative Max ( Literal ) Value : " & _
-4.94065645841247E-324)
Console.WriteLine("Zero ( Literal ) : " & 0.0)
Console.WriteLine("Positive Min ( Literal ) Value : " & _
+4.94065645841247E-324) ' Double.Epsilon
Console.WriteLine("Positive Max ( Literal ) Value : " & _
+1.7976931348623157E+308) ' Double.MaxValue
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Integer :
Min Value : -2147483648
Max Value : 2147483647
Max Literal Value : 2147483647

Long :
Min Value : -9223372036854775808
Max Value : 9223372036854775807
Max Literal Value : 9223372036854775807

Double :
Negative Min ( Literal ) Value : -1,79769313486232E+308
Negative Max ( Literal ) Value : -4,94065645841247E-324
Zero ( Literal ) : 0
Positive Min ( Literal ) Value : 4,94065645841247E-324
Positive Max ( Literal ) Value : 1,79769313486232E+308

An expression -2147483648 that tries to represent the minimum Integer value will be regarded ( by the
compiler ) as a Longexpression.
This expression is composed of the unary negation operator '-' and numeric literal '2147483648'. The parser read
the numeric part '2147483648', and tries to imply the unary negation operator '-'. But the numeric part '2147483648'
doesn't fit the 'Integer' range, an therefore will be regarded as a 'Long' expression.

Expression '-9223372036854775808' will ( for the same reason ) be refused by the compiler because
'9223372036854775808' doesn't fit in the range of 'Long'. This expression leads to an "overflow" error.

Numeric Literals with Type Coercion

Type coercion allows to form numeric literals of other datatypes then Integer, Long or Double.

By using a type character as suffix one could define the datatype of a numeric literal.

Datatype : Type character :

Byte <none>
SByte <none>
Short S
UShort US
Integer I
UInteger UI
Long L
ULong UL

Single F ( "Float" )
Double R ( "Real" )
Decimal D

Module Example2
Sub Main()
Dim value As Decimal = 9223372036854775808D ' (1)
End Sub
End Module
Download Broncode

Hexadecimal and Octal Literals

Usually integral literals are formed using the decimal scale ( base 10 ).
Using a hexadecimal ( base 16 ) or octal ( base 8 ) scale is possible, but then use prefixes &H and &O.
Module Example3
Sub Main()
Dim value1 As Short = &HF
Console.WriteLine(value1)
'
Dim value2 As Short = &H10
Console.WriteLine(value2)
'
Dim value3 As Short = &O7
Console.WriteLine(value3)
'
Dim value4 As Short = &O10
Console.WriteLine(value4)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
15
16
7
8

Char and String Datatypes

The Char datatype represents exactly one character. Its default value is " "c ( space ).

The String datatype can represent a text ( zero or more characters ). Its default value is Nothing.

Module Example1
Sub Main()
Dim someCharacter As Char
Console.WriteLine("*" & someCharacter & "*") ' (1)
'
someCharacter = "a"c ' (2)
Console.WriteLine("*" & someCharacter & "*")
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
* *
*a*
Line (2) illustrates how a Char literal is formed, surrounding double quotes and a trailing c ( indicating Char and
not String ) is used.

Temporal Datatype Date

The Date datatype is used to represent a timestamp.

Dates ranging from "January 1 of the year 0001" ( "Gregorian calendar" ) to "December 31 of the year 9999" and time
ranging from "12:00:00 AM (midnight)" to "11:59:59.9999999 PM".

"AM" stands for "Ante Meridiem" ( morning ), "PM" stands for "Post Meridiem" ( afternoon ).

The minimum difference between two Date values is 100 nanoseconds.

The minimum value to represent with Date is "12:00:00 AM (midnight), January 1 of the year 0001". The maximum
value is 100 nanoseconds before "January 1 of the year 10000".

Module Example1
Sub Main()
' Default & Minimum Value :
' January 1, 0001, 12:00:00 AM ( midnight ) :
Dim someDate As Date
Console.WriteLine(someDate)
'
' Maximum Literal Value :
' December 31, 9999, 11:59:59 PM ( 1 second before midnight ) :
someDate = #12/31/9999 11:59:59 PM#
Console.WriteLine(someDate)
'
' Minimum ( Literal ) Value :
' January 1, 0001, 12:00:00 AM ( midnight ) :
someDate = #12:00:00 AM#
Console.WriteLine(someDate)
'
' October 17, 2000, 12:00:00 AM ( midnight ) :
someDate = #10/17/2007#
Console.WriteLine(someDate)
'
' October 17, 2000, 12:00:01 AM ( 1 seconde after midnight ) :
someDate = #10/17/2007 12:00:01 AM#
Console.WriteLine(someDate)
'
' October 17, 2007, 1:00:00 AM ( 1 o'clock in the morning ) :
someDate = #10/17/2007 1:00:00 AM#
Console.WriteLine(someDate)
'
' October 17, 2007, 11:59:59 AM ( 1 second before noon ) :
someDate = #10/17/2007 11:59:59 AM#
Console.WriteLine(someDate)
'
' October 17, 2007, 12:00:00 PM ( noon ) :
someDate = #10/17/2007 12:00:00 PM#
Console.WriteLine(someDate)
'
' October 17, 2007, 12:00:01 PM ( 1 second after noon ) :
someDate = #10/17/2007 12:00:01 PM#
Console.WriteLine(someDate)
'
' October 17, 2007, 1:00:00 PM ( 1 o'clock in the afternoon ) :
someDate = #10/17/2007 1:00:00 PM#
Console.WriteLine(someDate)
'
' October 17, 2007, 11:59:59 PM ( 1 second before midnight ) :
someDate = #10/17/2007 11:59:59 PM#
Console.WriteLine(someDate)
'
' October 18, 2007, 12:00:00 AM ( midnight ) :
someDate = #10/18/2007#
Console.WriteLine(someDate)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
1/01/0001 0:00:00
31/12/9999 23:59:59
1/01/0001 0:00:00
17/10/2007 0:00:00
17/10/2007 0:00:01
17/10/2007 1:00:00
17/10/2007 11:59:59
17/10/2007 12:00:00
17/10/2007 12:00:01
17/10/2007 13:00:00
17/10/2007 23:59:59
18/10/2007 0:00:00

A Date literal is formed using surrounding # symbols.

Date and time format : #M/D/YYYY H:MM:SS AM|PM# :


- M stands for Month ( 1 - 12 ), preferable in 1 digit, 2 digits if necessary
- D stands for Day ( 1 - 31 ), preferable in 1 digit, 2 digits if necessary
- YYYY stands for Year ( 1 - 9999 ), always 4 digits
- H stands for Hour ( 1 - 12 ), preferable in 1 digit, 2 digits if necessary
- MM stands for Minutes ( 0 - 59 ), always 2 digits
- SS stands for Seconds ( 0 - 59 ), always 2 digits

Only a date : #M/D/YYYY# :


- default time is #12:00:00 AM# ( midnight )

Only a time : #H:MM:SS AM|PM# :


- default date is #1/1/0001#
Constants

What are Constants

Just like variables, constants are "dataholders". They can be used to store data that is needed at runtime.

In contrast to variable, the content of a constant can't change at runtime, it has a constant value.
At compiletime the value for a constant must be known. The declaration line of the constant must contain an
initialization clause ( where a constant expression ( for instance a literal ) is used to represent the initial value ).

An Example

Module Example1
Sub Main()
Const pi As Double = 3.1415
'
Dim radius As Single = 10
'
Dim circumference As Double = radius * 2 * pi
Dim area As Double = radius ^ 2 * pi
'
Console.WriteLine("Circle Circumference : " & circumference)
Console.WriteLine("Circle Area : " & area)
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
Circle Circumference : 62,83
Circle Area : 314,15

The above example declares a constant pi. We could have used a variable for pi, but because this value will
never change during runtime, a constant was more appropriate. We protect ourself form accidentally changing this
value.

It has to be said that a constant like 'pi' doesn't have to be declared. The FCL ( "Framework Class Library" ) already
contains a constant for this value ( 'Math.PI' ).

When Use Constants

Often constants are used to have an easy-to-remember name to refer to a difficult-to-remember value.
Module Example2
Sub Main()
Const red As Integer = &HFF0000
Const green As Integer = &HFF00
Const blue As Integer = &HFF
'
Console.WriteLine("red : " & red)
Console.WriteLine("green : " & green)
Console.WriteLine("blue : " & blue)
'
Const purple As Integer = red + blue
'
Console.WriteLine("purple : " & purple)
'
'
Console.ReadLine()
End Sub
End Module
Download Broncode

Output :
red : 16711680
green : 65280
blue : 255
purple : 16711935

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button4.Click

Dim Tot, Tot1, Tot2, Tot3, Tot4, Gtot As Double

Tot = Val(TotalTextBox.Text)
Tot1 = Val(Total1TextBox.Text)
Tot2 = Val(Total2TextBox.Text)
Tot3 = Val(Total3TextBox.Text)
Tot4 = Val(Total4TextBox.Text)

Gtot = Tot + Tot1 + Tot2 + Tot3 + Tot4


Grand_TotalTextBox.Text = Val(Gtot).ToString
End Sub

Potrebbero piacerti anche