1 / 26

Arrays

StudentsPerClass. 22. 22. 24. 0. 24. 0. 24. 0. 26. 0. 1. 2. 3. 4. 5. 6. 7. 8. Arrays. Definition – A set of values that are logically related to each other.

bina
Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. StudentsPerClass 22 22 24 0 24 0 24 0 26 0 1 2 3 4 5 6 7 8 Arrays • Definition – A set of values that are logically related to each other. • Purpose -An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The individual values are called the elements of the array. They are contiguous from index 0 through the highest index value. • Example – What if I wanted to have variables that tell me how many students are in each of my classes. I could declare a variable for each period and assign it a value of how many students are in each class, or I could create an array to do it. We graphically represent arrays like the following. • Caution – New students get the elements of the array confused with the index of the array. The element is the important data, the index is simply what spot it is stored in.

  2. Syntax for declaring one dimensional arrays • Dim arrayname = New datatype(size) { initial values } or • Dim arrayname(size) as datatype • Arrayname - Follow the same rules as naming variables, use a prefix to identify its datatype and use a descriptive name. • Datatype – Just like variables, tell the computer what type of data you expect the array to hold. The two datatypes must be the same in the declaration. • Size – An integer telling how many values you want your array to hold. The actual size of the array will always be one more than the number you put because the first index number is 0. • Initial Values – May be left blank or you may enter in values separated by commas. If blank the array will contain 0 for all number datatypes, false values for boolean datatype and blank for string datatypes. Declaring One Dimensional Arrays

  3. Declare an array example • dim bytStudentsPerClass() as byte = New byte(8) { } • Dim bytStudentsPerClass(27) as byte

  4. Assigning Values or “Populating” Arrays • The term populating arrays means how to get information in your array. Listed below shows how to do this. • Populate array when you declare the array. (Rarely done and used only when dealing with small arrays) DimstrStreet() as String = New String(2) {“Main”, “Ruble”, “Selden” } • Populate array one element at a time. (Rarely done and used only when dealing with small arrays) DimstrStreet() As String = New String(2) {} 'Declare array strStreet(0) = "Main" strStreet(1) = "Ruble" strStreet(2) = "Selden"

  5. Little differences • Dimboard() As Integer = {0, 4, 3, 2, 4, 5} You are not allow to declare a size when giving it initial values this way. • You are allowed this way though DimstrStreet() as String = New String(2) {“Main”, “Ruble”, “Selden” }

  6. Populate array with loops • Most arrays are populated by using loops. The information can come from many places and you typically don’t just type it in. ‘Fills an array with the numbers 0 – 5 Dim board(5) As Integer For i = 0 To 5 board(i) = i Next

  7. Arrays and Constants • You should declare your array size with a constant. • Example Const SIZE As Byte = 5 Dim board() As Integer = New Integer(SIZE) {} For i = 0 To board.Length - 1 board(i) = i Next

  8. Array commands • Arrayname.length – This returns how big the array is but it is always one bigger than the index values. Use this when running loops to traverse through an array. • Array.sort(arrayname) – This will sort an array in ascending order. Example follows: Dim zooAnimals(2) As String zooAnimals(0) = "lion" zooAnimals(1) = "turtle" zooAnimals(2) = "ostrich" Array.Sort(zooAnimals)

  9. Array Examples to do in class • Create a form that has the following: • A text box to add in names to an array • A listbox to display the array content • Four command buttons • Add the name typed in to the array • Display the names in the array • Reset the array (clear the values in the array) • Clear the list box • Use a constant after the program is finished. • Fill an array that holds a 1000 numbers with random numbers (between 1 and 100) generated for each element in the array. Search the array and have it tell how many array elements have a value greater than 50 and count how many array elements have a value less than 50.

  10. Code for example shown • Public Class Form1 • Const ASIZE As Byte = 4 • Dim strNames() As String = New String(ASIZE) {} • Dim i As Byte • Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load • For x = 0 To strNames.Length - 1 • strNames(x) = "" • Next • End Sub • Private Sub add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles add.Click • strNames(i) = txtinput.Text • i += 1 • txtinput.Text = "" • End Sub • Private Sub display_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles display.Click • lstoutput.Items.Clear() • For x = 0 To strNames.Length - 1 • lstoutput.Items.Add(strNames(x)) • Next • End Sub • Private Sub clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clear.Click • lstoutput.Items.Clear() • txtinput.Text = "" • End Sub • Private Sub reset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles reset.Click • For x = 0 To strNames.Length - 1 • strNames(x) = "" • Next • i = 0 • lstoutput.Items.Clear() • txtinput.Text = "" • End Sub • End Class

  11. Stop Lecture • Do first two array assignments

  12. Swapping Variables or Array Values • In programming you quite often will want to swap two variable values with each other. • In order to perform a variable swap you will need a third temporary variable of the same data type as what is being swapped. • Swapping needs to be done when you sort or shuffle values in an array.

  13. Swap Example • Say you want to swap the integer value of variable x with the integer value of variable y. The code would be: Dim temp as integer temp = x x = y y = temp

  14. Swap array values example Dim myarray() as String = new String(6) {“Bob”, “Tim”, “Sam”, “Dan”, “Ben”, “Zak”, “Jan”} Dim temp as String temp = myarray(0) myarray(0) = myarray(1) myarray(1) = temp

  15. Array Sorts • There are several ways to sort arrays, some are Bubble Sort, Quick Sort, Select Sort, Shell Sort, Insert Sort, and Heap Sort to name a few. • Why so many? • Some sorts work better depending on several factors, such as data types, length of array, how sorted array is etc… • We are not going to study all these but we will need to use one.

  16. Subroutines (no parameters) • A subroutine is simply a block of code that is given a name. • Do an example with no parameters

  17. Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strinput As String = InputBox("Type add or subtract").ToUpper If strinput = "ADD" Then Add() ElseIf strinput = "SUBTRACT" Then Subtract() End If MessageBox.Show("You are back") End Sub Private Sub Add() MessageBox.Show("You have reached add") End Sub Private Sub Subtract() MessageBox.Show("You have reached subtract") End Sub End Class

  18. Subroutines (with parameters) • Subroutines sometimes contain parameters. • The calling code may have variables or data typed in. Example add(3,5) or add(x,y) • The subroutine parameter list must match the parameter list of the calling routine. • Add(byval n as integer, byval m as integer)

  19. parameters • There are two parameter types in VB • Byval – makes a copy of the calling parameter • Byref – uses the calling parameter

  20. Bubble Sort – This is gold Private Sub sort(ByRefmyarray As Integer()) Dim temp As Integer For i = 0 To myarray.Length - 2 For j = 0 To myarray.Length - (i + 2) If myarray(j) >myarray(j + 1) Then temp = myarray(j) myarray(j) = myarray(j + 1) myarray(j + 1) = temp End If Next Next End Sub The stuff that is blue will need to be changed based on your application but the code is reusable with slight changes. The red part is the swap and it to may need to be modified based on your application.

  21. Using Structures • A structure is simply a custom data type and is used when you need to store more than one type of information on something. • The syntax for defining a structure StructureSomeName dimvariableassome data type dimvariableassome data type End Structure • After the structure is defined a variable then needs to declared as the defined structure. This is done like all other variable declarations except you use the structure name. do as many as you need

  22. Structure Example ‘Define the structure Structure aStudent dim strFname as string dim intGradeLevel as byte dim blnCurrentStudent as boolean End structure ‘Declare the variable of the defined data type Dim myStudents() As aStudent = New aStudent(5) {} ‘Using it in the program myStudents(0).strFname = "Elaine" myStudents(0).intGradeLevel = 12 myStudents(0).blnCurrentStudent = False

  23. Playing Sounds • Embedded vs Linked • Embedded is a anything (sounds, pictures, videos, etc…) that becomes part of the VB project. • Linked is a sound that is external to the VB project. If you send the program to someone you also have to send the linked file with it. • We will use embedded sounds. • To embed files open My Project and go to Resources. Add the resource.

  24. Sound • We can only use .wav files and make sure you follow the naming rules. • The code to play sound isMy.Computer.Audio.Play(My.Resources.your sound, AudioPlayMode.Background) • The code to stop sound is My.Computer.Audio.Stop() • Background can be one of three things. • Background – sound plays and everything continues. • BackgroundLoop – sound plays forever and everything continues. • WaitToComplete – Sound plays and code pauses until sound is over.

  25. Do Structure Example • Make it register 5 things • Sort it and display it by name or age. Use the bubble sort code. • Make it play and stop sound that is in the folder.

  26. Delay Code System.Threading.Thread.Sleep(Some Integer here)

More Related