Single Dimensional Arrays

Slides:



Advertisements
Similar presentations
An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
Advertisements

5.04 Apply Decision Making Structures
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Control structures Part 2 iteration control To enable repetition of a statement block.
5.05 Apply Looping Structures
COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#
Apply Sub Procedures/Methods and User Defined Functions
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
CS0004: Introduction to Programming Variables – Numbers.
IE 212: Computational Methods for Industrial Engineering
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
COMPUTER PROGRAMMING I Objective 7.03 Apply Built-in Math Class Functions.
6.3 List Boxes and Loops Some Properties, Methods, and Events of List Boxes List Boxes Populated with Strings List Boxes Populated with Numbers Searching.
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.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
Tutorial 6 The Repetition Structure
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#
COMPUTER PROGRAMMING I SUMMER Apply operators and Boolean expressions.
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.
Arrays Chapter 8. Overview u General discussion u Variable arrays u Control arrays u Multi-dimensional variable arrays  Two-dimensional  Three-dimensional.
COMPUTER PROGRAMMING I 5.04 Apply Decision Making Structures.
Programming with Microsoft Visual Basic 2012 Chapter 9: Arrays.
Visual Basic CDA College Paphos Campus COM123 Visual Programming 1 Lecture: Charalambous Sotiris Week 8: COM123 Visual Programming 1 Lecture: Charalambous.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 3 Variables and Calculations.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Welcome to Computer Programming II! Computer Programming II Summer 2015.
Chapter 8 Arrays and More. Chapter 8 Arrays and More.
Use TryParse to Validate User Input
Visual Basic Fundamental Concepts
Programming Right from the Start with Visual Basic .NET 1/e
5.03 Apply operators and Boolean expressions
5.04 Apply Decision Making Structures
Objective 7.04 Apply Built-in String Functions (3%)
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Objective 7.03 Apply Built-in Math Class Functions
An Introduction to Programming with C++ Sixth Edition
Chapter 7: Working with Arrays
IS 350 Arrays.
Array, Strings and Vectors
Arrays: Checkboxes and Textareas
Tutorial 10 – Class Average Application Introducing the Do…Loop While and Do…Loop Until Repetition Statements Outline Test-Driving the Class Average.
Apply Procedures to Develop Message, Input, and Dialog Boxes
Data Types, Arithmetic Operations
Computer Programming I
Use TryParse to Validate User Input
A First Book of ANSI C Fourth Edition
Apply Procedures to Develop Menus, List Box and Combo Box Objects
ARRAYS.
Arrays in C.
Understand Variables and Naming Conventions
Siti Nurbaya Ismail Senior Lecturer
Arrays, For loop While loop Do while loop
Visual Basic..
Part B – Structured Exception Handling
Do While (condition is true) … Loop
Starting Out with Programming Logic & Design
Arrays.
CIS16 Application Development and Programming using Visual Basic.net
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Arrays Part 2.
EET 2259 Unit 9 Arrays Read Bishop, Sections 6.1 to 6.3.
Introduction to Computer Programming IT-104
Lecture Set 9 Arrays, Collections, and Repetition
Presentation transcript:

Single Dimensional Arrays Computer Programming I Some slides will contain teacher notes- especially if a specific example given will not work in both VB and C#.

Objective/Essential Standard Essential Standard: 7.00 Apply Advanced Logic Indicator: 7.02 Apply One-Dimensional Arrays (7%)

Arrays What is an array? An array is a “container” that holds more than one value. Each value is called an element. Each element of the array must be the same data type.

Arrays Picture a carton of eggs. The “carton” is the container for the eggs. Each “egg” is an element in the container.

Declaring an Array An array like all variables must be declared before it can be used. Dim arrayName(intLastIndex) As DataType Dim intArray(5) as Integer 0 1 2 3 4 5 The first element is always be located at the index position of zero The index position points to the location of a value in an array. In VB this array will have six elements. In VB the number of elements in the array is one greater than the number given in the declaring statement. This is not the case in C#. So in VB the elements would be 0-5. In C# the above statement would create elements 0-4.

Declaring an Array Using our egg/egg carton analogy, each position would be numbered, starting at 0. 3 2 1 7 4 5 6 11 9 10 8

Populating an Array In the previous slide we declared an array but did not give the elements any values. Since the data type was integer all elements have a value of zero. Unless given values, the array will be initialized as follows Numeric Values  0 String Value  Nothing If the data type was string all elements would be null. Notice the difference in VB and C#. VB uses () and C# uses []. Using the wrong symbols will generate weird syntax errors.

Populating an Array However, we can modify our statement: Dim intArray() As Integer = {1, 2, 3, 4, 5} This declaration has an initializer list that will set all of the values of the array. No integer is within the ()’s. intArray with Values 1 2 3 4 5 Index Positions 1 2 3 4 If the data type was string all elements would be null. Notice the difference in VB and C#. VB uses () and C# uses []. Using the wrong symbols will generate weird syntax errors.

Populating an Array We can also add values individually like this: intArray(0) = 1 intArray(1) = 2 We can also use a loop if we are putting successive values in the array. For i as Integer = 0 to 5 intArray(i) = InputBox (“Enter a Value”, “Fill Array”) Next i Notice the difference in VB and C#. VB uses () and C# uses []. Using the wrong symbols will generate weird syntax errors.

Populating an Array Using a Loop 2 4 6 8 10 Dim intArray(4) As Integer Dim i As Integer= 2 Dim j As Integer= 0 Do While i <= 10 intArray(j) = i i+=2 ‘increases i j+=1 ‘increases index j Loop i j intArray(j) 2 4 1 6 8 3 10 12 This will give the five elements of the array an value. Starting with 2 and ending with 10 counting by 2s.

Pulling Data from An Array Now your array has data in it! How do you display it to the user? Use a loop of course! Length is a property that will give the length (number of elements) of any declared array. Note the Length will be 1 more than the index number of the last element in the array. intArray(4) has a Length of 5 Is it not required in VB to convert the data type to string to display in the message box, but it is good programming practice.

Pulling Data from An Array Consider the following example: Do While x < intArray.Length MessageBox.Show(intArray(x)) x += 1 Loop You can also use a For Loop For i As Integer = 0 To ArrayName.Length -1

Potential Problem with Arrays You will get a runtime error if you try to assign a value or pull a value from an array using an incorrect runtime error. Example Dim strName (3) As String strName (4) = “Jane” There is not a 4th index position.

Wait… There is an Easier Way There is a special type of loop just for arrays! Use For Each. This special loop’s main use is pulling data from arrays. Syntax For Each var As DataType In ArrayName ‘Statements Next var Example For Each intNum As Integer In intArray MessageBox.Show(intNum) ‘shows the value of intArray(intNum) Next i For Each i (counter) in intArray show that element and loop until all elements are displayed. If the variable being used has already been declared omit the data type in the for each statement.

Sorting An Array Sorting data in an array is quite simple: Array.Sort(NameOfArray) Array.Sort(intArray) This will sort the array from smallest to largest. A string array would be sorted A-Z.

Sorting a String Array Sample output is shown above. Dim strArray() As String = {"apple", "orange", "banana", "pineapple", "pear"} Array.Sort(strArray) For Each x In strArray lstFruit.Items.Add(x) Next x Sample output is shown above. Listboxes are covered in Standard 8- one is used here because it is the simplest way to display data pulled from an array.

Changing the Order of an Array We can flip the array (last element becomes the first) using the Reverse method. Array.Reverse(strArray) Using our string array- the new output is shown above. Notice- this is also a “trick” way to quickly sort an array in descending order. Sort it using the sort method then reverse it.

Searching an Array You can search an array by using a loop with an if statement. In many cases, it is more efficient to search an array if it is sorted first. Syntax For Each variable As DataType In ArrayName If variable = searchForVar Then Statements (Whatever should happen) End If Next variable

Parallel Arrays You can use multiple arrays where their elements are related by their position in the array. Example: Array Student Name Array StdNameArr(0) John Doe StdNameArr(1) Jane Smith StdNameArr(2) Peter Thomas Student Grade Array Array 10 StdGrdArr(0) StdGrdArr(1) 11 StdGrdArr(2)

Re-Declaring an Array If you find you need a larger array, you will need to re-declare the array as arrays are not dynamic. Once you set the size of an array, you cannot change it. Use the ReDim statement to re-declare the array. Syntax: ReDim arrayName(newSize) Re-declaring an array this way will delete all existing values in the array.

Re-Declaring an Array To re-declare the array AND hold the values, add the Preserve keyword. Syntax ReDim Preserve arrayName(newSize)

Sample Program Write a program that accepts three numbers and shows them to the user smallest to largest. Use textboxes for input and output.

Sample VB Code Private Sub btnSort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim numarray(2) As Integer Try numarray(0) = Convert.toInt16(txtNum1.Text) numarray(1) = Convert.toInt16(txtNum2.Text) numarray(2) = Convert.toInt16(txtNum3.Text) Catch ex As Exception MessageBox.Show(“Enter numeric values”) End Try Array.Sort(numarray) txtNum1.Text = numarray(0) txtNum2.Text = numarray(1) txtNum3.Text = numarray(2) End Sub Exit is a keyword that can exit the current block of code (like a try) or an entire sub. The program continues to the next block or sub (if there is one). In this case it allows the user to correct their errors without the program continuing to run.

Sample Program 2 Write a program that takes in grades from a user. The user will in a textbox tell the program how many grades to be entered. Display the grades in a listbox sorted smallest to largest. In a label provide the average of the grades.

Sample VB Code 'while counter is less than number of grades entered run loop ‘Assume i = 0 and intNumOfGrade is > 0 and has been entered to set the number of ‘Grades to be entered. Do While i < intNumOfGrade strInputGrade = InputBox("Please input a grade:", "Grade Input") 'get grade Try intArray(i) = Convert.ToInt32(strInputGrade) 'make sure it’s a number and adds it to the array Catch ex As Exception MessageBox.Show("That grade is not a number please try again.") 'error End Try intGradeTotal = intGradeTotal + intArray(i) 'add to total for average i += 1 'increment counter Loop Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click Dim intGradeNum As Integer Try intGradeNum = Convert.ToInt32(txtGrade.Text) Catch ex As Exception MessageBox.Show("Numbers only!") Exit Sub End Try Dim intArray(intGradeNum - 1) As Integer Dim i As Integer = 0 Dim j As Integer = 0 Dim intGrade As Integer = 0 Dim intGradeTotal As Integer Dim decAverage As Decimal = 0 Dim strInputGrade As String = "" Do While i < intGradeNum strInputGrade = InputBox("Please input a grade:", "Grade Input") intArray(i) = Convert.ToInt32(strInputGrade) MessageBox.Show("That grade is not a number please try again.") intGradeTotal = intGradeTotal + intArray(i) i += 1 Loop Array.Sort(intArray) For Each j In intArray lstGrades.Items.Add(j) Next j decAverage = intGradeTotal / intGradeNum lblAverage.Text = Format(decAverage, "##.00") End Sub

Sample VB Code Array.Sort(intArray) 'smallest to largest For Each grade In intArray 'pull data from array lstGrades.Items.Add(grade) Next grade decAverage = intGradeTotal / intGradeNum 'find average lblAverage.Text = decAverage.ToString("##.0") 'display with 1 decimal place

Passing An Array to a Sub You can pass an array to a sub either ByVal or ByRef. Syntax for the Sub header Private Sub addNums (ByVal NumArr() As Integer) Note: No number between the ()’s Syntax for Call statement addNums(NumArr) Note: NO ()’s

Passing An Array to a Sub You can also pass one element from an array. Syntax for the Sub header Private Sub addNums (ByVal intNum As Integer) Note: It is only pass a single data value Syntax for Call statement addNums(NumArr(i)) Passes the single value

Vocabulary Array Element Index Position Length ReDim Preserve Dynamic Array

Code Dim arrayName(intNum) As DataType ArrayName(position) = value Dim ArrayName As DataType() = {value,..., value} ArrayName.Length For Each var As DataType In ArrayName Next var Array.Sort(ArrayName) Array.Reverse(ArrayName) For Each variable As DataType In ArrayName If variable = searchForVar Then Statements (Whatever should happen) End If Next variable ReDim Preserve arrayName(newSize) Listboxname.Items.Add(what to add)

Wrap It Up In this presentation you learned about single-dimension arrays. Arrays are powerful tools that can be used to simplify programs. More sample programs are provided in the unpacked content.