Chapter 8 Arrays, Timers, and More.

Slides:



Advertisements
Similar presentations
Chapter 8 Arrays, Timers, and More.
Advertisements

Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
Programming Logic and Design Sixth Edition
1 Chapter 7 Arrays. 2 Outline and Objective In this chapter we will Learn about arrays One-dimensional arrays Two-dimensional arrays Learn about searching.
Chapter 8 Arrays and Strings
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
Chapter 8 Arrays and More.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
Chapter 8 Arrays and Strings
CSCI Chapter 8 Arrays Instructor: Bindra Shrestha University of Houston – Clear Lake.
Week Arrays, Timers, and More 9. 2 Introduction Arrays are like groups of variables that allow you to store sets of similar data A single dimension array.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
© 2012 EMC Publishing, LLC Slide 1 Chapter 8 Arrays  Can store many of the same type of data together.  Allows a collection of related values to be stored.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays Code: Arrays Controls: Control Arrays, PictureBox, Timer.
Arrays Chapter 8. Chapter 8 - Part 12 Variable and Variable Array Variable Stores only one value Variable Array Variable that has 1 symbolic name but.
‘Tirgul’ # 3 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #3.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 1.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 8 Arrays and More.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Arrays, Timers, and More 8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More About Array Processing 8.2 There Are Many Uses of Arrays and Many Programming.
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
Programming with Microsoft Visual Basic 2012 Chapter 9: Arrays.
Arrays and More CHAPTER 8. INTRODUCTION Arrays are like groups of variables that allow you to store sets of similar data A single dimension array is useful.
CHAPTER EIGHT ARRAYS © Prepared By: Razif Razali1.
1 Chapter 7 Arrays. 2 Outline and Objective In this chapter we will Learn about arrays One-dimensional arrays Two-dimensional arrays Learn about searching.
Controlling Program Flow with Decision Structures.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 9: Chapter 5: Slide 1 Unit 9 Do Until and For… Next Loops Chapter 5 Lists,
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Arrays 1.
Chapter 8 Arrays and More. Chapter 8 Arrays and More.
Programming Right from the Start with Visual Basic .NET 1/e
An Introduction to Programming with C++ Sixth Edition
Chapter 7: Working with Arrays
Microsoft Visual Basic 2005: Reloaded Second Edition
IS 350 Arrays.
Visual Basic 2010 How to Program
Lists, Loops, Validation, and More
Single Dimensional Arrays
Chapter 7 Arrays.
2. Understanding VB Variables
Arrays … The Sequel Applications and Extensions
Arrays, For loop While loop Do while loop
7 Arrays.
Chapter 8 Arrays and More.
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections
Chapter 8 Slides from GaddisText
EKT150 : Computer Programming
CIS16 Application Development and Programming using Visual Basic.net
CIS 16 Application Development Programming with Visual Basic
Starting Out with Programming Logic & Design
Arrays.
Topics Sequences Introduction to Lists List Slicing
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Building Java Programs
CIS16 Application Development and Programming using Visual Basic.net
Dr. Sampath Jayarathna Cal Poly Pomona
Programming Logic and Design Fifth Edition, Comprehensive
Topics Sequences Introduction to Lists List Slicing
Introduction to Computer Programming IT-104
Presentation transcript:

Chapter 8 Arrays, Timers, and More

8.1 Introduction

Chapter 8 Topics Arrays are like groups of variables that allow you to store sets of data A single dimension array is useful for storing and working with a single set of data A multidimensional array can be used to store and work with multiple sets of data Array programming techniques covered Summing and averaging all the elements in an array Summing all the columns in a two-dimensional array Searching an array for a specific value Using parallel arrays

8.2 Arrays An Array Is Like a Group of Variables With One Name You Store and Work With Values in an Array by Using a Subscript

Array Characteristics An array is a like group of variables with a single name All of the variables within an array are called elements and are of the same data type You access the individual variables in an array through a subscript

Subscript Characteristics A subscript, also known as an index, is a number that identifies a specific element within an array Subscript numbering begins at 0, so the subscript of the first element in an array is 0 The subscript of the last element in an array is one less than the total number of elements

Declaring an Array ArrayName is the name of the array Dim ArrayName(UpperSubscript) As DataType ArrayName is the name of the array UpperSubscript is the value of the array's highest subscript It must be a positive whole number DataType is a Visual Basic .NET data type

Example of an Array Dim hours(5) As Integer hours(0) hours(1) hours(2) hours(3) hours(4) hours(5)

Default Initialization All of the elements of an Integer array are initialized with the same value as a normal integer, zero (0) Same for other types of arrays Float, zero (0.0) String, Nothing

Explicit Array Initialization Example: No upper subscript value is given Visual Basic .NET will automatically make the array long enough to hold the values Dim numbers As Integer = {2, 4, 5, 7, 9, 12}

Named Constants As Array's Highest Subscript Value In place of a whole number, a named constant may be used as an array's highest subscript: Const upperSub As Integer = 100 Dim array(upperSub) As Integer

Working With Array Elements An Array element (e.g., numbers(2)) is used just like an ordinary variable: numbers(0) = 100 numbers(1) = 200 numbers(2) = 300 numbers(3) = 400 numbers(4) = 500 numbers(5) = 600 pay = hours(3) * rate tallies(0) += 1 MessageBox.Show(grossPay(5).ToString)

Arrays and Loops Frequently, arrays will be processed in loops Dim count As Integer For count = 0 To 9 series(count) = Val(InputBox("Enter a number.")) Next count Dim count As Integer For count = 0 To 999 names(count) = "" Next count

Array Bounds Checking Visual Basic .NET will check each subscript value of each array reference used at run time If a subscript is used that is either negative or greater than the highest allowed, a dialog box will appear giving the option of Debugging or Stopping the application (Note that no bounds checking is done at design time)

For Each … Next Statement This statement is similar to a For…Next Dim employees As String() = {"Jim", "Sally", _ "Henry", "Jean", "Renee" } Dim name As String For Each name In employees MessageBox.Show(name) Next name

8.3 More About Array Processing There Are Many Uses of Arrays and Many Programming Techniques That Involve Them Arrays May Be Used to Total Values and Search for Data Related Information May Be Stored in Multiple Parallel Arrays In Addition, Arrays May Be Resized at Run Time

Determining the Number of Elements in an Array Array's have a Length property that holds the number of elements in the array Note that the length is the number of elements on the array, not the largest subscript Dim values(25) As Integer For count = 0 to (values.Length – 1) MessageBox.Show(values(count).ToString) Next count

How to Total the Values in an Array The values are summed up in a variable that is initialized to zero beforehand: Dim total As Integer = 0 ' Initialize accumulator For count = 0 To (units.Length – 1) total += units(count) Next count

Getting the Average of the Values in a Numeric Array This algorithm first totals the values, then calculates the average: Dim total As Integer = 0 ' Initialize accumulator Dim average As Single For count = 0 To (units.Length – 1) total += units(count) Next count average = total / units.Length

Finding the Highest and Lowest Values in a Numeric Array Pick the first element as the highest, then look through the rest of the array for even higher ones, always saving the highest value Proceed analogously to find the lowest value highest = numbers(0) For count = 1 To (numbers.Length - 1) If numbers(count) > highest Then highest = numbers(count) End If Next count

Copying One Array's Contents to Another This is done by copying the elements one at a time, thusly Note that newvalues = oldvalues will not work for this use because the value of oldvalues is the storage location for that array (not all of the contents of oldvalues) For count = 0 To 100 newValues(count) = oldValues(count) Next count

Parallel Arrays Sometimes it is useful to store related data in two or more arrays Hence the ith element of one array is related to the ith element of another Then the program can access this related information by using the same subscript on both arrays Dim names(4) As String Dim addresses(4) As String

Parallel Arrays Example Dim names(4) As String Dim addresses(4) As String For count = 0 To 4 lstPeople.Items.Add( "Name: " & names(count) & _ " Address: " & addresses(count)) Next count

Parallelism Between Arrays and List Boxes and Combo Boxes ' Initialize a List Box with names lstPeople.Items.Add("Jean James") ' Subscript 0 lstPeople.Items.Add("Kevin Smith") ' Subscript 1 lstPeople.Items.Add("Joe Harrison") ' Subscript 2 ' Initialize an Array with corresponding phone numbers phoneNumbers(0) = "555-2987" phoneNumbers(1) = "555-5656" phoneNumbers(2) = "555-8897" ' Process a selection If lstPeople.SelectedIndex > -1 And _ lstPeople.SelectedIndex < phoneNumbers.Length Then MessageBox.Show(phoneNumbers(lstPeople.SelectedIndex)) Else MessageBox.Show("That is not a valid selection.") End If

Searching Arrays, The Search This code hunts for the value 100 in the array scores ' Search for a 100 in the array. found = False count = 0 Do While Not found And count < scores.Length If scores(count) = 100 Then found = True position = count End If count += 1 Loop

Searching Arrays, Acting on the Result This code indicates whether or not the value was found or not ' Was 100 found in the array? If found Then MessageBox.Show( _ "Congratulations! You made a 100 on test " & _ (position + 1).ToString, "Test Results") Else "You didn’t score a 100, but keep trying!", _ "Test Results") End If

Sorting an Array There is an Array.Sort method that sorts arrays in ascending order, examples: Dim numbers() As Integer = { 7, 12, 1, 6, 3 } Array.Sort(numbers) ' OR Dim names() As String = { "Sue", "Kim", "Alan", "Bill" } Array.Sort(names)

Resizing an Array ReDim is a new keyword ReDim [Preserve] Arrayname(UpperSubscript) ReDim is a new keyword If Preserve is specified, the existing contents of the array are preserved Arrayname names the existing array UpperSubscript specifies the new highest subscript value

Resizing Example Dim scores() As Single ' Start array as having "Nothing" ' Now obtain a size from the user numScores = Val(InputBox("Enter the number of test scores.")) If numScores > 0 Then ReDim scores(numScores - 1) Else MessageBox.Show("You must enter 1 or greater.") End If

8.4 Sub Procedures and Functions That Work With Arrays You May Pass Arrays As Arguments to Sub Procedures and Functions You May Also Return an Array From a Function These Capabilities Allow You to Write Sub Procedures and Functions That Perform General Operations With Arrays

Passing Arrays as Arguments ' In the calling program Dim numbers() As Integer = { 2, 4, 7, 9, 8, 12, 10 } DisplaySum(numbers) ' The sub procedure Sub DisplaySum(ByVal a() As Integer) ' Displays the sum of the elements Dim total As Integer = 0 ' Accumulator Dim count As Integer ' Loop counter For count = 0 To (a.Length - 1) ' << Length obtained total += a(count) Next MessageBox.Show("The total is " & total.ToString) End Sub

Passing Arrays: ByVal and ByRef ByRef when used with an array, allows unrestricted changes to the array ByVal with an array Does not restrict its values from being changed from within the sub procedure It does prevent an array argument from be assigned to another array (see next slide)

ByRef Allows This Sort of Modification ByVal Does Not Dim numbers() As Integer = { 1, 2, 3, 4, 5 } ResetValues(numbers) Sub ResetValues(ByVal a() As Integer) ' Assign the array argument to a ' new array. Does this work? ' NOT when using ByVal ' It would if ByRef was used instead Dim newArray() As Integer = {0, 0, 0, 0, 0} a = newArray End Sub

Returning an Array From a Function Function GetNames() As String() ' Get four names from the user ' and return them as an array ' of strings. Dim names(3) As String Dim input As String Dim count As Integer For count = 0 To 3 input = InputBox("Enter name " & _ (count + 1).ToString) names(count) = input Next Return names End Function

8.5 Multidimensional Arrays You May Create Arrays With More Than Two Subscripts to Hold Complex Sets of Data

A Two Dimensional Array Picture Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2

Two Dimensional Array Syntax Dim ArrayName(UpperRow, UpperColumn) As DataType UpperRow and UpperColumn give the highest subscript for the row and column indices of the array The array on the previous slide could be: Dim array(2,3) As Single

A Two Dimensional Array Showing the Subscripts Dim array(2,3) As Single Column 0 Column 1 Column 2 Column 3 Row 0 array(0,0) array(0,1) array(0,2) array(0,3) Row 1 array(1,0) array(1,1) array(1,2) array(1,3) Row 2 array(2,0) array(2,1) array(2,2) array(2,3)

Two Dimensional Arrays Are Often Processed With Nested Loops For row = 0 To 2 For col = 0 To 3 num = Val(InputBox("Enter a score.")) scores(row, col) = num Next col Next row

Implicit Sizing and Initialization of Two-Dimensional Arrays This works for multi-dimensional arrays as well as singly dimensioned ones: Dim numbers(,) As Integer = {{1, 2, 3}, _ {4, 5, 6}, _ {7, 8, 9}}

For Each Loops and Multi-dimensional Arrays A For Each Loop will process all of the elements in an array (without having to have nested loops): Dim numbers(,) As Integer = {{1, 2, 3}, _ {4, 5, 6}, _ {7, 8, 9}} For Each element In numbers total += element Next element

Summing the Columns of a Two-dimensional Array ' Sum the columns. For col = 0 To 2 ' Initialize the accumulator. total = 0 ' Sum a column. For row = 0 To 4 total += values(row, col) Next row ' Display the sum of the column. MessageBox.Show("Sum of column " & col.ToString & _ " is " & total.ToString) Next col

Three-dimensional Arrays and Beyond Visual Basic .NET allows arrays with up to 32 dimensions Beyond three dimensions, they are difficult to visualize But, all one needs to do is to be consistent in the use of the different indices

8.6 Enabled Property, Timer Control, Splash Screens You Disable Controls by Setting Their Enabled Property to False The Timer Control Allows Your Application to Execute a Procedure at Regular Time Intervals Splash Screens Are Forms That Appear As an Application Begins Executing

Enabled Property, I Most controls have a Boolean property named Enabled When a control’s Enabled property is set to false, it is considered disabled, which means: It cannot receive the focus and cannot respond to events generated by the user In addition, it will appear dimmed, or grayed out

Enabled Property, II This property defaults to true (Enabled) Under program control this property can be set to whatever the application logic dictates radBlue.Enabled = False

Timer Control, I This control, when placed on a form, generates Tick events on a regular interval If there is a corresponding Tick event procedure, it executes at these intervals Hence, your form can perform needed operations on a regular interval

Timer Control, II The timer control has two important properties: Enabled - if set to True, it generates the Tick events, otherwise not Interval - holds the interval between Ticks in milliseconds (thousandths of a second)

Splash Screens This is a form, typically with the application's logo, that is often displayed while an application is loading, it should: Have its Topmost property set to True so that it will be seen in preference to the applications other forms Disappear shortly (using a Timer) Be modeless

8.6 Anchoring and Docking Controls Controls Have Two Properties, Anchor and Dock, That Allow You to Determine the Control’s Position on the Form When the Form Is Resized at Run Time

Anchor Property A control may be Anchored to two adjacent sides of the form This situation will maintain the same distances from those edges whenever the form is resized by the user (control does not change size) A control may be anchored to opposite sides of a form This situation will again maintain those distances, but by changing the size of the control

Dock Property A control can be docked against any side of a form Whenever the form is resized, the control will change in size also to fill up the edge that it is docked to

8.7 Random Numbers Visual Basic .NET Provides the Tools to Generate Random Numbers and Initialize the Sequence of Random Numbers With a Seed Value

Random Number Generation, Step 1 Random number generation is initiated with the selection of a "seed" number If you wish to repeat the same sequence of random numbers, then use the above statement with the same argument Number If you do not want to repeat a sequence, omit the argument Randomize [Number]

Random Number Generation, Step 2 Obtain the next random number in the sequence Repeatedly use a statement like the above to generate additional random numbers randomNumber = Rnd

Random Number Range Rnd creates random numbers in the range of 0.0 to 1.0 To scale these to a range between two integers that may be needed in your program: randomNumber = Int(LowerNumber + Rnd * _ (UpperNumber - LowerNumber))