300 likes | 325 Views
Programming with Visual Basic .NET. Arrays, Sub Procedure and Functions Week 7 Tariq Ibn Aziz. Arrays. You can declare an array to work with a set of values of same data type. An array is a single variable with many compartments to store values
E N D
Programming with Visual Basic .NET Arrays, Sub Procedure and Functions Week 7 Tariq Ibn Aziz Dammam Community College
Arrays • You can declare an array to work with a set of values of same data type. • An array is a single variable with many compartments to store values • An individual variable in the array is called an array element • Declare single-dimensional array: Dim a1() AsInteger Dim arr(5) AsInteger Dammam Community College
One-Dimensional Arrays • In Visual Basic .NET, an array cannot have a fixed size. The preceding example can be rewritten as either of the following declarations: ' Reserves 12 elements -- (0) through (11). Dim Month(11) AsInteger Dim Month() AsInteger = New Integer(11) {} Dim Month() AsInteger = {1,2,3,4,5,6,7,8,9,10,11,12} Dammam Community College
One-Dimensional Arrays • If you specify dimension lengths in the parentheses following the variable name, you must use a subsequent assignment statement to assign an array object to the variable. The following sample declarations show valid and invalid syntax for a single-dimensional array variable: Dim BA(2) AsByte ' Currently contains Nothing (no object). Dim BA(2) AsByte = New Byte() ' INVALID (New after length specified). Dim BA() AsByte = New Byte() {} ' Empty Byte array object. Dim BA() AsByte = New Byte() ' INVALID (missing braces). Dim BA() AsByte = New Byte(2) ' INVALID (missing braces). Dim BA() AsByte = New Byte() {0,1,2} ' (0) through (2). Dim BA() AsByte = New Byte(2) {0,1,2} ' (0) through (2). Dammam Community College
One-Dimensional Array Example 1 • For example, to store daily expenses for each day of the year, you can create one array with 366 elements, rather than declaring 366 variables. • Each element in the array contains one value, which you access by specifying the element's index. Sub FillArray() ' Allocates (0) through (365). Dim CurExpense(365) AsDecimal Dim I AsInteger For I = 0 to 365 CurExpense(I) = 20.00 Next I EndSub Dammam Community College
One-Dimensional Array Mix Data type • You can mix data types in an array if it is declared of type Object. The following example stores employee information in the array variable EmployeeData. ' Allocates (0) through (3). Dim EmployeeData(3) AsObject EmployeeData(0) = "Ron Bendel" EmployeeData(1) = "4242 Maple Blvd" EmployeeData(2) = 48 EmployeeData(3) = "06-09-1953" Dammam Community College
One-Dimensional Array Example 3 • The following example creates a single-dimensional array of integer values, initializes the array elements, and then prints each of them out: Module Test Sub Main() Dim arr(5) AsInteger Dim i AsInteger For i = 0 To arr.GetUpperBound(0) arr(i) = i * i Next i For i = 0 To arr.GetUpperBound(0) Console.WriteLine("arr(" & i & ")=" & arr(i)) Next i EndSub EndModule Dammam Community College
Array • The program outputs the following: arr(0) = 0 arr(1) = 1 arr(2) = 4 arr(3) = 9 arr(4) = 16 Dammam Community College
Exercise (One-Dimensional Arrays) • Declare one-dimensional array that includes both doubleand floatelements? • Write a program that creates and initialize a four-elements bytearray. Display its elements • Write a program that creates and initialize a four-element doublearray. Calculate and display the average of its values. Dammam Community College
Multi-Dimensional Arrays • In Visual Basic, you can declare arrays with up to 32 dimensions. • For example, the following statement declares a two-dimensional array with 5 rows and 10 columns. In addition to one dimension array, you can create array of two or more dimensions. ' (0) through (4), (0) through (9). Dim Rectangle(4, 9) AsSingle Dammam Community College
Multi-Dimensional Arrays • You need to perform 2 steps to create an array declare and Initialize. • Declare 2 Dimensional Integer array: Dim a2(,) AsInteger • Declare 3 Dimensional Integer array: Dim a3(,,) AsInteger Dammam Community College
Multi-Dimensional Arrays (Cont.) • You can initialize a multidimensional array variable in a similar manner. The following sample declarations show a two-dimensional array variable being declared as an Short array with 2 rows and 2 columns. ' (0) through (1), (0) through (1) Dim S2X2(1, 1) AsShort ' INVALID (New after lengths) Dim S2X2(1, 1) As Short = New Short(,) ' INVALID (missing braces). Dim S2X2(,) As Short = New Short(,) Dammam Community College
Multi-Dimensional Arrays ' INVALID (missing braces) Dim S2X2(,) As Short = New Short(1, 1) ' Empty array object. Dim S2X2(,) AsShort = New Short(,) {} ' Elements have default value Dim S2X2(,) AsShort = New Short(1, 1) {} ' Four elements. Dim S2X2(,) AsShort = New Short(,){{5, 6},{7, 8}} • Note: The first argument represents the rows; the second argument represents the columns. Dammam Community College
Multi-Dimensional Arrays Example 1 Output: Array1.length=6 33 71 -16 45 99 -27 Imports System.Console Public Module TwoDimArray Sub Main() Dim array1(2,1) AsInteger array1(0,0) = 33 array1(0,1) = 71 array1(1,0) = -16 array1(1,1) = 45 array1(2,0) = 99 array1(2,1) = -27 WriteLine("Array1.length=" & array1.length) WriteLine(array1(0,0) &" "& array1(0,1)) WriteLine(array1(1,0) &" "& array1(1,1)) WriteLine(array1(2,0) &" "& array1(2,1)) EndSub End Module Dammam Community College
Multi-Dimensional Arrays Example 2 • You can efficiently process a multidimensional array by using nested For loops. For example, the following statements initialize every element in MatrixA to a value between 0 and 99, based on its location in the array. Dim I, J AsInteger Dim MaxDim0, MaxDim1 AsInteger Dim MatrixA(9, 9) AsDouble MaxDim0 = MatrixA.GetUpperBound(0) MaxDim1 = MatrixA.GetUpperBound(1) For I = 0 To MaxDim0 For J = 0 To MaxDim1 MatrixA(I, J) = (I * 10) + J Next J Next I Dammam Community College
Multi-Dimensional Arrays Example 2 • Note: You can obtain the overall size of an array of any rank from its Length property. • In the previous example, MatrixA.Length would return 100. Dammam Community College
Multi-Dimensional Arrays Exercise • Write a program to initialize 2 dim array of size 3 x 3 as follow: • Use nested loop and if condition. 0 1 1 1 0 1 1 1 0 Dammam Community College
Multi-Dimensional Arrays Exercise • Write a program to initialize 2 dim array of size 3 x 3 as follow: • Use nested loop and if condition. 1 1 0 1 0 1 0 1 1 Dammam Community College
Procedures • Subprocedures • Do not return values • Cannot be used in an expression value • Functions • A block of code that is grouped into a named unit. • Built-in functions inherit from a .NET Framework class • User defined functions • Event Procedures • Not executed until an event triggers the procedure • Known as an event procedure • Does not return a value • Page_Load event triggered when the page is loaded Dammam Community College
Sub Method Declarations Syntax Sub: [accessibility] Sub subname[(argumentlist)] ' Statements of the Sub procedure go here. End Sub • The accessibility can be Public, Protected, Friend, Protected Friend, or Private. • You can define Sub procedures in modules, classes, and structures. They are Public by default, which means you can call them from anywhere in your application. Dammam Community College
Call Sub Method • The syntax for a call to a Sub procedure is as follows: • [Call] subname[(argumentlist)] Dammam Community College
Sub Method Example • The following application simply calls TellOperator from various places. Each call passes a string in the Task argument that identifies the task being started. Module M1 Sub Main() Call TellOperator("file update") End Sub Sub TellOperator(ByVal Task AsString) ' Stamp is local to TellOperator. Dim Stamp As Date ' Get current time for time stamp. Stamp = TimeOfDay() ' Use MessageBox class of System.Windows.Forms namespace. MessageBox.Show("Start" & Task & " at " & CStr(Stamp)) EndSub EndModule Dammam Community College
Event Procedure • Event Names • Based on object name and event name • Identified with the prefix "on" and event name • Underscore (_) separate object and event name Sub objectName_eventHandler(sender as Object, e as EventArgs) action and control statements EndSub Dammam Community College
Functions • Are declared • Public functions - visible to all other functions • Private functions - only available within the context where they are declared PublicFunction GetStudentID() AsInteger 'This function returns an integer Return 200510103 EndFunction Dammam Community College
Function Method Example Syntax Sub: [accessibility] Function Funname[(argumentlist)] As type ' Statements of the Function go here. End Function • The accessibility can be Public, Protected, Friend, Protected Friend, or Private. • You can define a Function procedure inside a module, class, interface, or structure, but not inside another procedure. They are Public by default, which means you can call them from anywhere in your application. Dammam Community College
Functions Example PublicFunction GetStoreName() AsString Return "Tara Store“ EndFunction GetTheFunction() Dammam Community College
Passing an Argument to a Function • A pair of parentheses follows with zero or more arguments, also known as parameters, which are passed to the function when it is called • If no arguments are passed, you use an empty pair of parentheses • If multiple arguments are used, you use a comma to separate each argument Dammam Community College
Passing an Argument to a Function class A PublicFunction Welcome(usr As String) AsString If Usr = "Admin" Then Return "Welcome Administrator!“ Else Return usr EndIf EndFunction SharedSub Main() System.Console.WriteLine(Welcome("Tariq")) EndSub EndClass Dammam Community College
Returning a Value From a Function & Exiting a Function • Keyword Return • Identify the value returned to the function call • Exiting a Function • Exit Function keywords • A jumping control; jumping controls allow you to temporarily halt the execution of a code block, and move to another section of code outside the function Dammam Community College
Return Keyword & Exiting a Function PublicFunction GetStoreName() AsString Dim UserName AsString UserName = txtUserName.Text.ToString If UserName = "Admin" Then Return "Welcome Administrator!" ExitFunction Else ExitFunction EndIf EndFunction Dammam Community College