Full Transcript

**Arrays** Arrays are an important data structure in Visual Basic that allow developers to store multiple values of the same data type in a single variable. Visual Basic supports two types of arrays: single-dimensional arrays and multidimensional arrays. A single-dimensional array is a collection o...

**Arrays** Arrays are an important data structure in Visual Basic that allow developers to store multiple values of the same data type in a single variable. Visual Basic supports two types of arrays: single-dimensional arrays and multidimensional arrays. A single-dimensional array is a collection of elements of the same data type arranged in a linear sequence. A multidimensional array is a collection of elements of the same data type arranged in a two or more dimensional structure. For example, a two-dimensional array can be visualized as a table or grid with rows and columns. Arrays can be declared as static or dynamic. This article will cover the basics of arrays in Visual Basic, including how to declare and initialize arrays, how to access elements in arrays, and how to use arrays in loops. **Key characteristics of arrays:** i. **Indexing**: Elements in an array are accessed using an index or key, which is typically an integer. The index indicates the position of the element in the array. ii. **Fixed** **Size**: Arrays have a fixed size, meaning the number of elements they can hold is determined at the time of declaration. Once an array is created, its size generally cannot be changed. iii. **Contiguous** **Memory**: The elements of an array are stored in adjacent memory locations. This makes it efficient to access elements using their indices because the computer can calculate the memory address of any element based on the index and the size of the elements. iv. **Homogeneous** **Elements**: Arrays typically store elements of the same data type. For example, an array of integers will only store integer values, and an array of strings will only store string values. v. **Sequential** **Access**: Elements in an array are stored sequentially in memory, and accessing them sequentially is usually more efficient than accessing them randomly. **Declaring and Initializing Arrays:** In VB, arrays can be declared using the following syntax: **Dim arrayName(size) As DataType** Where **arrayName** is the name of the array, **size** is the number of elements in the array, and **DataType** is the data type of the elements in the array. For example, to declare an integer array with 10 elements, the code would be: **Dim intArray(9) As Integer** Alternatively, we can declare an array and initialize it with values at the same time using the following syntax: For example, the following code declares and initializes a string array with three elements: **Dim strArray() As String = {\"apple\", \"banana\", \"orange\"}** **\' Declare a single-dimension array of 5 numbers.** **Dim numbers(4) As Integer={1, 2, 4, 8,10}** **\' Declare a single-dimension array and set its 4 values.** **Dim numbers = New Integer() {1, 2, 4, 8}** **\' Change the size of an existing array to 16 elements and retain the current values.** **ReDim Preserve numbers(15)** **\' Redefine the size of an existing array and reset the values.** **ReDim numbers(15)** **\' Declare a 6 x 6 multidimensional array.** **Dim matrix(5, 5) As Double** **\' Declare a 4 x 3 multidimensional array and set array element values.** **Dim matrix = New Integer(,) {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}}** **Accessing Elements in Arrays:** Elements in an array can be accessed using their index number. In VB, array indexes start at 0, which means that the first element in an array is at index 0, the second element is at index 1, and so on. To access an element in an array, we use the following syntax: **arrayName(index)** For example, to access the second element in the intArray array declared earlier, we use the following code: **Dim secondElement as Integer = intArray(1)** To declare an array in Visual Basic, you must specify its data type and the number of elements it will hold. Here is an example of declaring an integer array with five elements: **Dim intArray(4) As Integer** This code declares an integer array called **intArray** with five elements, numbered from 0 to 4. To initialize an array, you can assign values to its elements using a loop or explicitly declare the values at the time of declaration. Here is an example of initializing the **intArray** with values: **Dim intArray() As Integer = {1, 2, 3, 4, 5}** **Accessing Elements of an Array:** The elements of an array are accessed using their index values. The index of the first element in a Visual Basic array is always 0. Here is an example of accessing the second element of the **intArray**: **Dim secondValue as Integer = intArray(1)** In this example, the value of the second element in the intArray is assigned to the variable secondValue. Note that the index of the second element is 1, not 2, because the index of the first element is 0. **Common Operations on Arrays:** Visual Basic provides several built-in functions and methods for performing common operations on arrays. Here are some examples: **Length**: The Length property returns the number of elements in the array. Here is an example of using the Length property to get the number of elements in the **intArray**: **Dim ArrLength as Integer = intArray.Length** **Sort**: The Sort method arranges the elements of the array in ascending order. Here is an example of sorting the **intArray**: **Array.Sort(intArray)** **Reverse**: The Reverse method reverses the order of the elements in the array. Here is an example of reversing the **intArray**: **Array.Reverse(intArray)** **Looping through Arrays:** Arrays are often used in loops to perform operations on each element in the array. The **For loop** in VB is commonly used to iterate through arrays. For example, the following code uses a For loop to print all the elements in the strArray array: **For i As Integer = 0 To strArray.Length - 1** **Console.WriteLine(strArray(i))** **Next** This loop starts at index 0 and ends at the length of the array minus one. Within the loop, the Console.WriteLine statement prints each element in the array. **Example** **Public Sub Main()** **\' Declare an array with 7 elements.** **Dim students(6) As Integer** **\' Assign values to each element.** **students(0) = 23** **students(1) = 19** **students(2) = 21** **students(3) = 17** **students(4) = 19** **students(5) = 20** **students(6) = 22** **\' Display the value of each element.** **For ctr As Integer = 0 To 6** **Dim grade As String = If(ctr = 0, \"kindergarten\", \$\"grade {ctr}\")** **Console.WriteLine(\$\"Students in {grade}: {students(ctr)}\")** **Next** **End Sub** **End Module** **\' The example displays the following output:** **\' Students in kindergarten: 23** **\' Students in grade 1: 19** **\' Students in grade 2: 21** **\' Students in grade 3: 17** **\' Students in grade 4: 19** **\' Students in grade 5: 20** **\' Students in grade 6: 22** **Multi-Dimensional Arrays:** In VB, arrays can have more than one dimension. Multi-dimensional arrays are declared using the following syntax: **Dim arrayName(size1, size2,..., sizeN) As DataType** Where size1, size2, and so on represent the number of elements in each dimension of the array. For example, the following code declares a two-dimensional integer array with two rows and three columns: **Dim intArray(1, 2) As Integer** Elements in a multi-dimensional array can be accessed using multiple index values. For example, to access the element in the first row and second column of intArray, we use the following code: **Dim element As Integer = intArray(0, 1)** **Conclusion**: Arrays are a powerful data structure in Visual Basic that allows the programmer to store and manipulate large amounts of data in a single variable. By understanding the different types of arrays, how to declare and initialize them, how to access their elements, and some common operations that can be performed on them, you can develop more efficient and effective Visual Basic programs. Important URLs 1. 2. 3. **Procedures and functions: Visual Basic Pass by Value vs Pass by Reference** In Visual Basic, you can pass an argument to a procedure *by value* or *by reference*. This is known as the *passing mechanism*, and it determines whether the procedure can modify the programming element underlying the argument in the calling code. The procedure declaration determines the passing mechanism for each parameter by specifying the ByVal or ByRef keyword. A variable can passed to a function either by value or by reference. Primitive data types like int, long, float etc are passed by value. Reference data types like user defined classes are passed by reference. A primitive data type specifies the size and type of variable values, and it has no additional methods. Primitive data types - includes byte, short, int, long, float, double, Boolean and char Non-primitive data types - such as String, Arrays and Classes When you pass by value, a new memory is created for the value and it is treated as a new variable in the function. When you pass by reference, reference to the current memory location is passed, so if the Object in the function changes, the changes will be reflected back when you return back from the function. **Distinctions** When passing an argument to a procedure, be aware of several different distinctions that interact with each other: - Whether the underlying programming element is modifiable or nonmodifiable - Whether the argument itself is modifiable or nonmodifiable - Whether the argument is being passed by value or by reference - Whether the argument data type is a value type or a reference type **Choice of Passing Mechanism** You should choose the passing mechanism carefully for each argument. - **Protection**. In choosing between the two passing mechanisms, the most important criterion is the exposure of calling variables to change. The advantage of passing an argument ByRef is that the procedure can return a value to the calling code through that argument. The advantage of passing an argument ByVal is that it protects a variable from being changed by the procedure. - **Performance**. Although the passing mechanism can affect the performance of your code, the difference is usually insignificant. One exception to this is a value type passed ByVal. In this case, Visual Basic copies the entire data contents of the argument. Therefore, for a large value type such as a structure, it can be more efficient to pass it ByRef. **Determination of the Passing Mechanism** The procedure declaration specifies the passing mechanism for each parameter. The calling code can\'t override a ByVal mechanism. Non modifiable If a parameter is declared with ByRef, the calling code can force the mechanism to ByVal by enclosing the argument name in parentheses in the call. The **default** in Visual Basic is to pass arguments by value. **When to Pass an Argument by Value** - If the calling code element underlying the argument is a nonmodifiable element, declare the corresponding parameter [[ByVal]](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/byval). No code can change the value of a nonmodifiable element. - If the underlying element is modifiable, but you do not want the procedure to be able to change its value, declare the parameter ByVal. Only the calling code can change the value of a modifiable element passed by value. **When to Pass an Argument by Reference** - If the procedure has a genuine need to change the underlying element in the calling code, declare the corresponding parameter [[ByRef]](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/byref). - If the correct execution of the code depends on the procedure changing the underlying element in the calling code, declare the parameter ByRef. If you pass it by value, or if the calling code overrides the ByRef passing mechanism by enclosing the argument in parentheses, the procedure call might produce unexpected results. **Example** **Description** The following example illustrates when to pass arguments by value and when to pass them by reference. Procedure Calculate has both a ByVal and a ByRef parameter. Given an interest rate, rate, and a sum of money, debt, the task of the procedure is to calculate a new value for debt that is the result of applying the interest rate to the original value of debt. Because debt is a ByRef parameter, the new total is reflected in the value of the argument in the calling code that corresponds to debt. Parameter rate is a ByVal parameter because Calculate should not change its value. **Code** VB Module Module1 **Sub Main()** **\' Two interest rates are declared, one a constant and one a** **\' variable.** **Const highRate As Double = 12.5** **Dim lowRate = highRate \* 0.6** **Dim initialDebt = 4999.99** **\' Make a copy of the original value of the debt.** **Dim debtWithInterest = initialDebt** **\' Calculate the total debt with the high interest rate applied.** **\' Argument highRate is a constant, which is appropriate for a** **\' ByVal parameter. Argument debtWithInterest must be a variable** **\' because the procedure will change its value to the calculated** **\' total with interest applied.** **Calculate(highRate, debtWithInterest)** **\' Format the result to represent currency, and display it.** **Dim debtString = Format(debtWithInterest, \"C\")** **Console.WriteLine(\"What I owe with high interest: \" & debtString)** **\' Repeat the process with lowRate. Argument lowRate is not a** **\' constant, but the ByVal parameter protects it from accidental** **\' or intentional change by the procedure.** **\' Set debtWithInterest back to the original value.** **debtWithInterest = initialDebt** **Calculate(lowRate, debtWithInterest)** **debtString = Format(debtWithInterest, \"C\")** **Console.WriteLine(\"What I owe with low interest: \" & debtString)** **End Sub** **\' Parameter rate is a ByVal parameter because the procedure should** **\' not change the value of the corresponding argument in the** **\' calling code.** **\' The calculated value of the debt parameter, however, should be** **\' reflected in the value of the corresponding argument in the** **\' calling code. Therefore, it must be declared ByRef.** **Sub Calculate(ByVal rate As Double, ByRef debt As Double)** **debt = debt + (debt \* rate / 100)** **End Sub** **End Module**

Use Quizgecko on...
Browser
Browser