Vous êtes sur la page 1sur 10

Chapter 3: Fundamentals of programming in VB.

NET

1. Variables
 A variable stores data while an application runs

 The process of creating a variable is called declaring a variable

 A variable has a name (identifier)

 The naming rules for variables and procedures are the same

 A variable has a data type

 Variables can be declared and initialized in the same statement

 Example to declare a variable named CurrentYear and initialize its value to 2006:

Dim CurrentYear As Integer = 2006

 Remark: Numeric initialization values cannot contain formatting characters

 The following statements are illegal:

Dim Value1 As Double = 100,000.52

Dim Value2 As Double = $100,000.52

 The value of a constant does not change while an application runs

 Trying to assign a value to a constant will cause an error

 Use the Const statement to declare a constant

 Declare a constant to store value of PI

Private Const PI_VALUE As Single = 3.14159

2. Decision Making Statements


 Applications need the capability to execute one group of statements in certain
circumstances and other statements in other circumstances
 These statements are called decision-making statements or decision structures
or alternative structures
 The If statement is used to make decisions
 A conditional statement executes one group of statements when a condition is
True and another group of statements when a condition is False
 Comparison operators are used in conditional statements
 Conditional operations always produce a Boolean result

Comparison Operators

 Equal to (=), Not equal to (<>), Less than (<), Greater than (>), Less than or equal to
(<=), Greater than or equal to (>=)

Example 1

If Grade is greater than 75, set Pass to True. Otherwise, set Pass to False

Dim Pass As Boolean

Dim Grade As Integer = 80

If Grade > 75 Then

Pass = True

Else

Pass = False

End If

Example 2

Dim NumericGrade As Integer = 84

Dim LetterGrade As String

If NumericGrade >= 90 Then

LetterGrade = "A"

ElseIf NumericGrade >= 80 Then

LetterGrade = "B"

ElseIf NumericGrade >= 70 Then

LetterGrade = "C"

ElseIf NumericGrade >= 60 Then

LetterGrade = "D"
Else

LetterGrade = "F"

End If

Example 3

Dim Quarter As Integer = 3

Dim QuarterString As String

Select Case Quarter

Case 1

QuarterString = "First"

Case 2

QuarterString = "Second"

Case 3

QuarterString = "Third"

Case 4

QuarterString = "Fourth"

Case Else

QuarterString = "Error"

End Select

3. Loops
 To execute statements repeatedly

 These structures are part of nearly every program written

 Repetition is the most powerful feature of any language – it is what computers do best
(and FAST!)

 Learning how to construct loops with appropriate loop parameters can make difficult
tasks seem easy (and coded with a short instruction sequence
 Situations where repetition is used

 Calculating payroll – a loop is used to calculate the payroll for each employee

 Reading multiple records in a file – a loop is used to process each record in a


file

 Graphical animations – a loop is used to move graphical objects about the


screen

 Accounting problems – depreciation and loan balances are calculated


repeatedly for multiple periods

Example 1

 Print the counting numbers 1 through 10 using a Do Until loop

 Print the counting numbers 1 through 10 using a Do While loop

Dim Counter As Integer = 1

Do While Counter <= 10

Debug.WriteLine(Counter)

Counter += 1

Loop

Example 2

 Store the sum of the counting numbers 1 through 10

Dim Counter As Integer = 1

Dim Accumulator As Integer = 0

Do While Counter <= 10

Debug.WriteLine(Counter)

Accumulator += Counter

Counter += 1

Loop
Example 3: What is the output of the following code?

Dim Counter As Integer = 1

Do While Counter < 10

Debug.WriteLine(Counter)

Loop

Example 4

 Determine whether a number is prime

Private Shared Function IsPrime( _


ByVal arg As Integer) As Boolean

Dim Count As Integer = 2

Do While Count < arg

If (arg Mod Count) = 0 Then

Return False

End If

Count += 1

Loop

Return True

End Function

Example 5

 Print the counting numbers 1 to 10 using for loop

Dim Counter As Integer

For Counter = 1 To 10

Debug.WriteLine(Counter)

Next Counter

Example 6
Dim CurrentYear As Integer

For CurrentYear = 2000 To 1900 Step –5

Debug.WriteLine(CurrentYear.ToString)

Next CurrentYear

Remark

 Exit causes the innermost loop that contains it to exit immediately, sending control to
the first instruction that follows the loop

 Continue causes the innermost loop that contains it to repeat immediately (effectively
sending control to the bottom of the loop so that loop repetition can take place)

 The keywords Exit and Continue must be followed by keywords indicating the type of
loop they are used in (Exit For or Exit Do)

Example 7

A loop with an Exit statement


Dim message as String = Nothing
Dim monthlyInvestment As Decimal
Dim monthlyInterestRate As Decimal
Dim months As Integer
Dim futureValue As Decimal
For i As Integer = 1 To months
futureValue = (futureValue + monthlyInvestment)* (1 + monthlyInterestRate)
If futureValue > 1000000 Then
message = "Future value is too large."
Exit For ' the For loop ends
End If
Next i
4. Arrays

An Array is a list of values – all values referenced by the same name.

        An array is like a ListBox without the box with the list of values all stored in memory.

        Arrays are also called tables.

        Arrays are based on the System.Array object – a type of collection object. Arrays can
store almost any type of data such as integer, string, decimal, etc.
        Element – this is the term used to refer to an individual part of an array.

        Each element is numbered beginning with the number zero. Example, 0, 1, 2, 3, etc.

        The number referring to an array element is placed inside parentheses and is called a
subscript or index. This is the general format for an array reference.

  ArrayName(ElementNumber)

         Example references to array elements:

 'Element 4 of the array named AmountDecimal – remember

'that arrays start with 0 so the 4th element is numbered 3


AmountDecimal(3)

'Element 7 of an array named StatesString

StatesString(6)

        An array element can also be referenced by using an index variable – usually each
element in a single-dimension array is termed a row so you might name the index
variable a name such as RowInteger.

        In this example the referenced element depends on the current value of RowInteger.

 'The referenced element depends on the value of RowInteger

StatesString(RowInteger)

Declaring an Array
Arrays are created in memory by declaring them as you would a variable.

        Generally you declare local arrays with the keyword Dim and module-level arrays with
the keyword Private.

        The number inside parentheses that specifies the number of elements should be an
integer – if a floating point number is used, VB will round the number to an integer value
automatically.

        Numeric array elements default to a value of zero; string array elements default to a
value of the empty string.

There are several different correct syntax variations for declaring arrays. The general formats
are:
  Dim ArrayName(UpperSubscript) As DataType

Dim ArrayName() As DataType = {ListOfValues}

Dim ArrayName As DataType() = {ListOfValues}

         Example declarations:

 'A String array with 26 elements numbered 0 through 25

Dim NameString(25) As String

'A decimal array of 11 elements numbered 0 through 10

Private BalanceDecimal(10) As Decimal

       This example declares a module-level array and stores values to the array immediately.
When
storing values immediately to the array, you cannot specify the number of elements within the
parentheses—VB will determine the number of elements automatically.

 'A private string array with 6 elements numbered 0 through 5

Private SchoolString() As String = {"Arts and Sciences", _

"Business", "Nursing", "Engineering", _

"Education", "Pharmacy"}

Element Number School Name


0 Arts and Sciences
1 Business
2 Nursing
3 Engineering
4 Education
5 Pharmacy

 Array Subscript Errors


A subscript (also referred to as an index) must always reference a valid, existing array element.

 If an array contains 10 elements, and a VB program attempts to reference element -1 or


element 11, the reference will be invalid and result in an error message:

  An unhandled exception of type 'System.IndexOutOfRangeException' occurred in


Ch08VBUniversity-Version1.exe
 The subscript (index) is out of the allowable range of 0 through 10 for element numbers.

Navigating array elements

Arrays are often processed in loops. The power of arrays comes with using a variable as the
subscript.

        A For..Next loop can process an entire array with a few lines of code as shown here, but
the code requires you to manipulate the array index.

        This example writes the array contents to the Output window, one school name per line:

For RowInteger = 0 To NumberOfSchoolsInteger

Debug.WriteLine(SchoolString(RowInteger))

Next RowInteger
Another type of count-controlled loop is the For Each..Next loop – the advantage of this coding
construct is that you don't have to manipulate the loop index.
        The loop code shown here is equivalent to the one shown above.
For Each SchoolNameString As String In SchoolString
Debug.WriteLine(SchoolNameString )
Next SchoolNameString
Learn these rules about For Each..Next loops:
        The index data type must match the array data type, i.e., for a string array the index
should be a string index, for an integer array the index should be an integer, etc.
        This above example declares SchoolNameString as a string variable index and then
immediately uses it to search the SchoolString array.

 An array can be used to accumulate values where you would otherwise need to declare many
accumulating variables. Sometimes a numeric accumulating array needs to be re-initialized to
zero. This example sets all elements of an integer array named TotalInteger to zero.
Remember a numeric array starts out with each element equal to zero, but if the array is used
over and over within a program, it may need to be reinitialized.

 For Each IndividualElementInteger As Integer In TotalInteger

IndividualElementInteger = 0

Next IndividualElementInteger

5. Modularity
Subs and Functions
Subs and Functions are used to turn a block of statements into a named
operation
A Sub is a block of code that does something
A Function is a block of code that does something and then returns a result
Both are useful in breaking up a complex task by separating out specific parts of the
process to be considered separately during programming
Within a class, Subs and Functions are Methods

Parameters
Subs and Functions can accept values or variables as inputs and/or outputs, so
that they can be made more general purpose

Example 1

Sub Square(ByVal Value As Integer )


Dim result As Integer
result = Value * Value
Console.WriteLine(result)
End Sub

Example 2

Function Square(ByVal Value As Integer ) As Integer


Return Value * Value
End Sub

Q. What is the difference between Example 1 and Example 2? (Above)

Input and Output Parameters


Parameters can be used differently depending how they are passed
into a Sub or Function (more correctly, how the Sub or Function is prepared
to accept them)
A ByVal parameter (the default) sends values into a Sub or Function:
these values act as inputs only
A ByRef parameter sends references into a Sub or Function: this is
equivalent to sending the whole variable in the parameter, since the
Sub/Function can modify the values in these variables. ByRef parameters
are Input/Output parameters

Vous aimerez peut-être aussi