CIS162AD - C# Arrays ch08.ppt.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Arrays – Part 2 13_arrays_sorting.ppt
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Chapter 10 Introduction to Arrays
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Chapter 9: Arrays and Strings
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
An Object-Oriented Approach to Programming Logic and Design Chapter 7 Arrays.
Chapter 8 Arrays and Strings
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Processing Arrays Lesson 8 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Chapter 8 Arrays and Strings
Array Processing.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CIS162AD - C# Arrays – part 1 12_arrays_loading.ppt.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
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.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Version 1.1. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
Arrays.
Lesson 8: Introduction To Arrays
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Computer Programming BCT 1113
Microsoft Visual Basic 2005: Reloaded Second Edition
Chapter 7 Part 1 Edited by JJ Shepherd
Single Dimensional Arrays
New Structure Recall “average.cpp” program
Chapter 7 Arrays.
Chapter 5: Arrays: Lists and Tables
Arrays, Collections and Repetition Part A – Arrays and Repetition
Arrays … The Sequel Applications and Extensions
Visual Basic .NET BASICS
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
EKT150 : Computer Programming
Review of Arrays and Pointers
Starting Out with Programming Logic & Design
Data Structures (CS212D) Week # 2: Arrays.
Standard Version of Starting Out with C++, 4th Edition
Arrays Week 2.
CIS16 Application Development and Programming using Visual Basic.net
7 Arrays.
Chapter 9: Data Structures: Arrays
Programming Logic and Design Fifth Edition, Comprehensive
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Introduction to Computer Programming IT-104
Presentation transcript:

CIS162AD - C# Arrays ch08.ppt

Overview of Topics Declaring Arrays Loading Arrays Partially Filled Arrays Arrays Elements as Arguments Declaring and Loading Constant Arrays Sorting Arrays Searching Arrays Parallel Arrays Multi-dimensional Arrays CIS162AD

Arrays are Tables Array is a different word for a table. A table is made up of columns and rows. Just like an Excel spreadsheet. CIS162AD

Array Defined An array is used to process a collection of data all of which is of the same data type (Integer, Decimal, String, etc.). First we’ll look at single dimensional arrays (one column, many rows). Think of a single dimensional array as a list of variables. CIS162AD

Declaring Array int intQty1, intQty2, intQty3; int[ ] intQty = new int[3]; //3 integer variables dataType[ ] arrayName = new dataType[arraySize]; An array of 3 elements of type integer is created. The arraySize is used by C# to determine how much memory to allocate. Arrays will usually be class-level because after values are loaded in we don’t want to lose the values. CIS162AD

Array Subscript dataType[ ] arrayName = new dataType[arraySize]; Arrays are allocated consecutive memory. Each element is referenced using a subscript. Subscript are integers. The number of elements that are created is arraySize. The first element in the array is referenced with a value of zero [0]. The last element is referenced with a subscript value of [arraySize – 1]. A subscript is also referred to as an index. Short variable names for subscripts are acceptable. CIS162AD

Memory Map Address Variable Value 1010 intQty1 1020 intQty2 1030 1020 intQty2 1030 intQty3 1040 intQty[0] 1050 intQty[1] 1060 intQty[2] 1070 decPrice CIS162AD

Subscript Out Of Range If during execution, the subscript value referenced an element past the end of the array, the program would throw an exception (run-time error). The programmer must make sure that the logic in the program does not allow the subscript to exceed the array size. This is called being out of range. CIS162AD

Preventing Out of Range C# will not prevent a subscript out of range error, but it will abort the execution when it happens. It aborts because the subscript would be referencing some other section of memory than what was allocated for the array. The programmer is responsible for preventing the out range error. We can use some built in methods to manage arrays, arrayName.Length arrayName.GetUpperBound(0). The For Each (foreach) command may also be used to walk through arrays. CIS162AD

Array Properties int[ ] intQty = new int[3]; //3 integer variables arrayName.Length intQty.Length is equal to 3. intQty.Length is the number of entries that can be loaded. The last valid subscript value is one less than Length. arrayName.GetUpperBound(0). intQty.GetUpperBound(0) is equal to 2. intQty.GetUpperBound(0) is last valid subscript value. Depending the loop structure, we may use: less than Length or Equal to GetUpperBound(0) CIS162AD

Array Processing Declare Array Load Array Process Array After creating the array, data must be loaded. Use arrayName.Length or arrayName.GetUpperBound(0) to prevent out of range errors. Note: Arrays can be declared and loaded with constant values. Process Array Use individual elements in calculations or as arguments. Send entire arrays to methods for processing. Sort, Search, Display Use a lot of For loops or For Each loops. CIS162AD

Declare Array //Arrays are declared at the class level, //so they can be referenced by all methods. int[ ] cintTestScores = new int[20]; int cintNumberOfStudents; //We can load up to 20 scores, but we will //save how many tests are actually loaded in cintNumberOfStudents. CIS162AD

cintTestScores Array Memory Map Position Address Index Value 1 1010 [0] 2 1014 [1] 3 1018 [2] 4 1022 [3] 5 1026 [4] 6 1030 [5] 7 1034 [6] … 20 1086 [19] CIS162AD

Load Array //Loads Array with scores saved in a data file. cs12ex.txt 50 40 100 30 10 20 //Loads Array with scores saved in a data file. private void btnLoadArray_Click( ) { FileStream studentFile = new FileStream("cs12ex.txt", FileMode.Open); StreamReader studentStreamReader = new StreamReader(studentFile); int i = 0; //subscript initialized to zero while (studentStreamReader.Peek() != -1) { if (i < cintTestScores.Length) { cintTestScores[i] = int.Parse(studentStreamReader.ReadLine( )); i ++; //Increment subscript by one } else { MessageBox.Show (“Array Size Exceeded”); break; //Get of out of loop; Array is full. } } cintNumberOfStudents = i; //Save how many students were loaded studentFile.Close( ); //Close file } CIS162AD

Loaded Arrays Position Address Index Value 1 1010 [0] 50 2 1014 [1] 40 3 1018 [2] 100 4 1022 [3] 30 5 1026 [4] 10 6 1030 [5] 20 7 1034 [6] … 1086 [19] CIS162AD

Process Array – Individual Elements private void btnProcessArray_Click( ) { int i; int intSum = 0; for (i = 0; i <= cintTestScores.GetUpperBound(0); i++) { intSum += cintTestScores[i]; } txtSum.Text = intSum.ToString(“N0”); CIS162AD

For Each - Example private void btnProcessArray_Click( ) { int i; //subscript not needed int intSum = 0; foreach (int intTestScore in cintTestScores) { intSum += intTestScore; } txtSum.Text = intSum.ToString(“N0”); CIS162AD

Partially Filled Arrays In the for loop on the prior slide it was assumed that the arrays were filled by going up to GetUpperBound(0). Up to 20 scores could be loaded, but in the example only 6 scores were actually loaded. When the array is not full, it is considered a partially filled array. The for loops need to be modified to only process the number scores loaded. The number of scores loaded are counted in the load routine, and the count should then be saved in a variable like cintNumberOfStudents. This variable should then be used when processing the arrays. CIS162AD

Load Array – Partially Filled //Loads Array with scores saved in a data file. private void btnLoadArray_Click( ) { FileStream studentFile = new FileStream("cs12ex.txt", FileMode.Open); StreamReader studentStreamReader = new StreamReader(studentFile); int i = 0; //subscript initialized to zero while (studentStreamReader.Peek() != -1) { if (i < cintTestScores.Length) { cintTestScores[i] = int.Parse(studentStreamReader.ReadLine( )); i ++; //Increment subscript by one } else { MessageBox.Show (“Array Size Exceeded”); break; //Get of out of loop; Array is full. } } cintNumberOfStudents = i; //Save how many students were loaded studentFile.Close( ); //Close file } CIS162AD

Processing Partially Filled Arrays private void btnProcessArray_Click( ) { int i; int intSum; //for (i = 0; i <= cintTestScores.GetUpperBound(0); i++) //process entire array for (i = 0; i < mintNumberOfStudents; i++) //process partially filled array { intSum += cintTestScores[i]; } txtAverage.Text = (intSum / mintNumberOfStudents).ToString(“N0”); CIS162AD

Declare and Load Constant Arrays Arrays that will hold constants or some initial values can be loaded at declaration. When the values are provided at declaration, do not include the size. The size is determined by the number of values provided. The values are enclosed in braces and not parenthesis. decimal[ ] cdecPERCENT_RANGE = new decimal[ ] {90D, 80D, 70D, 60D, 0D}; string[ ] cstrLETTER_GRADE = new string[ ] {"A", "B", "C", "D", "F"}; C# does NOT allow const for arrays. CIS162AD

Array Management If during execution, the subscript value referenced an element past the end of the array, the program would throw a subscript out range exception (run-time error). The programmer must make sure that the logic in the program does not allow the subscript to exceed the array size. We can use some built in methods to manage arrays, arrayName.Length arrayName.GetUpperBound(0) For partially filled arrays we must count how many items are loaded and then use the count when processing the arrays. CIS162AD

Array Subscript dataType[ ] arrayName = new dataType[arraySize]; Arrays are allocated consecutive memory. Each element is referenced using a subscript. Subscript are integers. The number of elements that are created is arraySize. The first element in the array is referenced with a value of zero [0]. The last element is referenced with a subscript value of [arraySize – 1]. A subscript is also referred to as an index. Short variable names for subscripts are acceptable. CIS162AD

Sorting Arrays Data is always being sorted. It is important that we understand how sorts work. There are various sort algorithms. We’ll only be looking at the simple selection sort. Selection Sort Algorithm: Find the lowest value in the array. Move it to the top of the array. Find the next lowest value, and move it to the 2nd position. Continue until the end of the array is reached. CIS162AD

Sort Ascending private void sortAscending(…) { int i, i2; int intMinScore, intMinSubscript, intHoldValue; for (i = 0; i < cintNumberOfStudents - 1; i++) //-1 so we don’t all the way to the bottom { intMinSubscript = i; intMinScore = cintTestScores[i]; for (i2 = i + 1; i2 < cintNumberOfStudents; i2++) { if {cintTestScore[i2] < intMinScore) { intMinSubscript = i2; intMinScore = intTestScores[i2]; } intHoldValue = cintTestScores[i]; //swap values cintTestScores[i] = cintTestScores[intMinSubscript]; cintTestScore[intMinSubscript] = intHoldValue; CIS162AD

Sort Algorithm Demonstration const int intARRAY_SIZE = 20; int[ ] cintTestScores = new int[intArraySize]; int cintNumberOfStudents; CIS162AD

Declared Array - cintTestScores Address Subscript Value 1010 [0] 1014 [1] 1018 [2] 1022 [3] 1026 [4] 1030 [5] 1034 [6] … 1086 [19] CIS162AD

Load Array Subscript Value [0] 50 [1] 40 [2] 100 [3] 30 [4] 10 [5] 20 [6] … [19] Read 6 numbers from file and load them into array. Numbers of Students = i i = 6 CIS162AD

Sort Ascending 1st position Subscript Value [0] 50 [1] 40 [2] 100 [3] 30 [4] 10 [5] 20 [6] … [19] Move the value in the 1st position to holdValue = 50. Find the lowest value and move it to the 1st position. Move holdValue to the position that the lowest value was found, swap values. CIS162AD

Sort Ascending 2nd position Subscript Value [0] 10 [1] 40 [2] 100 [3] 30 [4] 50 [5] 20 [6] … [19] Move the value in the 2nd position to holdValue = 40. Find the next lowest value and move it to the 2nd position. Move holdValue to the position that the lowest value was found. CIS162AD

Sort Ascending 3rd position Subscript Value [0] 10 [1] 20 [2] 100 [3] 30 [4] 50 [5] 40 [6] … [19] Move the value in the 3rd position to holdValue = 100. Find the next lowest value and move it to the 3rd position. Move holdValue to the position that the lowest value was found. CIS162AD

Sort Ascending 4th position Subscript Value [0] 10 [1] 20 [2] 30 [3] 100 [4] 50 [5] 40 [6] … [19] Move the value in the 4th position to holdValue = 100. Find the next lowest value and move it to the 4th position. Move holdValue to the position that the lowest value was found. CIS162AD

Sort Ascending 5th position Subscript Value [0] 10 [1] 20 [2] 30 [3] 40 [4] 50 [5] 100 [6] … [19] Move the value in the 5th position to holdValue = 50. A lower value than 50 will not be found, but the comparison must still be made. CIS162AD

Sort Ascending private void sortAscending(…) { int i, i2; int intMinScore, intMinSubscript, intHoldValue; for (i = 0; i < cintNumberOfStudents - 1; i++) //-1 so we don’t all the way to the bottom { intMinSubscript = i; intMinScore = cintTestScores[i]; for (i2 = i + 1; i2 < cintNumberOfStudents; i2++) { if {cintTestScore[i2] < intMinScore) { intMinSubscript = i2; intMinScore = intTestScores[i2]; } intHoldValue = cintTestScores[i]; //swap values cintTestScores[i] = cintTestScores[intMinSubscript]; cintTestScore[intMinSubscript] = intHoldValue; CIS162AD

Sequential Search Algorithm Before searching, the data is usually sorted first. Look through the array elements from the first to the last looking for a match. After a match is found, we are going to do something with item found later, so the index of where the item was found must be saved. If the item was not found, we also need to record this using a flag or special value, so that the error can be reported. CIS162AD

Search Array – part 1 private void searchArray(…) int i; int intSearchNumber; int intNumberLocation; bool blnNumberFound; blnNumberFound = false; intSearchNumber = int.Parse(txtSearch.Text); //see next slide for the rest of the method CIS162AD

Search Array – part 2 for (i = 0; i < cintNumberOfStudents; i++) { if (intSearchNumber = = cmintTestScores[i]) { blnNumberFound = true; intNumberLocation = i; lblOutput.Text = intSearchNumber.ToString(“N0”) + “ is located in array position “ + _ intNumberLocation. ToString(“N0”); } if (blnNumberFound = = false) “ is not in the array.“; CIS162AD

Search Array – Match Found Subscript Value [0] 10 [1] 20 [2] 30 [3] 40 [4] 50 [5] 100 [6] … [19] intSearchNumber = 40. For loop walks through array checking if cintTestScores(i) = = intSearchNumber. When a match is found, the subscript value is displayed (3). CIS162AD

Search Array – Early Exit Subscript Value [0] 10 [1] 20 [2] 30 [3] 40 [4] 50 [5] 100 [6] … [19] intSearchNumber = 25. In the for loop we should also check if intSearchNumber < cintTestScores[i] . If it is, then we know that we will not find the value. We can exit search. Must be sorted. CIS162AD

Search Array – Early Exit for (i = 0; i < cintNumberOfStudents; i++) { if (intSearchNumber = = cmintTestScores[i]) { blnNumberFound = true; intNumberLocation = i; lblOutput.Text = intSearchNumber.ToString(“N0”) + “ is located in array position “ + _ intNumberLocation. ToString(“N0”); } else if (intSearchNumber < cintTestScores[i]) { lblOutput.Text = "Match not found - Early Exit “; break; // get out for loop CIS162AD

Parallel Arrays An array is used to process a collection of data all of which is of the same data type (Integer, Decimal, String, etc.). When there is related data of different data types, then the data must be loaded into separate but parallel Arrays. This means that related values are loaded into different arrays but are connected to each by the subscript value. All of the related values will have the same subscript value. CIS162AD

Parallel Arrays – Simplified Example Names and scores stored in a file string[ ] cstrName = new string[19]; int[ ] cintScore = new int[19]; for (i = 0; i < 20; i++) { cstrName[i] = studentStreamReader.ReadLine( ); cintScore[i] = int.Parse(studentStreamReader.ReadLine( )); } The related student data in different arrays must be kept together, especially when sorting. CIS162AD

Sorting Parallel Arrays Subscript Name [0] Todd [1] Mary [2] John [3] Subscript Score [0] 90 [1] 50 [2] 70 [3] If sorting by Name, John would be moved to the first position. The data in the related array (Score of 70) must also be swapped. The sort routine would require additional swap statements. CIS162AD

Two Dimensional Array Single Dimensional Arrays are thought of as one column and many rows. Single Dimensional Arrays require one subscript to reference an individual element. Two Dimensional Arrays are many columns and many rows. Two Dimensional Arrays require two subscripts to reference an individual element. CIS162AD

Two Dimensional Array - Example Sum sales data for 10 departments and 4 quarters. decimal[,] decSales = new decimal[10, 4]; for (i = 0; i < 11; i++) { for (j = 0; j < 5; j++) { decTotal += decSales[i, j]; } } Each individual element requires two subscripts. CIS162AD

Two Dimensional Array - Data Subscript i is going down the rows. Subscript j is going across the columns. 10, 15, 25, 30 20, 22, 32, 42 30, 33, 43, 15 Subscripts [0] [1] [2] [3] 10 15 25 30 20 22 32 42 33 43 [etc.] CIS162AD

Name Array – 1D Juan Marquez John Smith Sue Bradley Pat West Need an array to store the names of 5 people that are head of the household. string[ ] strName = new string[5] Juan Marquez John Smith Sue Bradley Pat West Mark Jones CIS162AD

Name Array – 2D Juan Marquez John Smith Sue Bradley Pat West Mark Need an array to store 5 names, but first and last name separately. string[ , ] strName = new string[5,2] Juan Marquez John Smith Sue Bradley Pat West Mark Jones CIS162AD

Name Array – 3D Juan Marquez John Smith Sue Bradley Pat West Mark Need an array to store the first and last names of up to 5 household members of 4 households. string[ ,, ] strName = new string[4,5,2] West is in strName[0,3,1]. household, row, col Juan Marquez John Smith Sue Bradley Pat West Mark Jones CIS162AD

Name Array – 4D Need an array to store the first and last names of up to 5 household members of 4 house holds for two different years. string[ ,,, ] strName = new string[2,4,5,2] See next slide. The first dimension is the cube (year). West is in strName[0,0,3,1] and [1,0,3,1]. CIS162AD

Multi-Dimensional Arrays Arrays are actually stored consecutively in memory, not in a form represented in the drawings in the prior slides. We draw pictures so that we can visually see the data we are trying to manipulate. The computer can handle as many dimensions as you would like to add. 3 or 4 dimensions should be our maximum. Keep in mind that eventually you or someone will need to maintain the program. If the array is to complex, it will take a while to get reacquainted with the logic. CIS162AD

Summary Declaring Arrays Loading Arrays Processing Arrays Single Dimensional Multi Dimensional The best way to understand these slides is to work through the examples using your own values. Desk check the logic to see how values are sorted. CIS162AD

Summary Declaring Arrays Loading Arrays Partially Filled Arrays Arrays Elements as Arguments Declaring and Loading Constant Arrays CIS162AD