C# Programming: From Problem Analysis to Program Design1 7 Arrays and Collections C# Programming: From Problem Analysis to Program Design 2 nd Edition.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Chapter 10.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
C# Programming: From Problem Analysis to Program Design1 Arrays C# Programming: From Problem Analysis to Program Design 3 rd Edition 7.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
C# Programming: From Problem Analysis to Program Design1 Advanced Collections C# Programming: From Problem Analysis to Program Design 3 rd Edition 8.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 7 & 8- Arrays and Strings
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays and Strings
C# Programming: From Problem Analysis to Program Design1 7 Arrays and Collections.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
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.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 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.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays Chapter 7.
INF230 Basics in C# Programming
Chapter 6: Using Arrays.
C# Programming: From Problem Analysis to Program Design
Computer Programming BCT 1113
INF230 Basics in C# Programming
C# Programming: From Problem Analysis to Program Design
7 Arrays.
7 Arrays.
Presentation transcript:

C# Programming: From Problem Analysis to Program Design1 7 Arrays and Collections C# Programming: From Problem Analysis to Program Design 2 nd Edition

C# Programming: From Problem Analysis to Program Design2 Chapter Objectives Learn array basics Declare arrays and perform compile-time initialization of array elements Access elements of an array Become familiar with methods of the Array class

C# Programming: From Problem Analysis to Program Design3 Chapter Objectives ( continued ) Write methods that use arrays as parameters Write classes that include arrays as members and instantiate user-defined array objects Create two-dimensional arrays including rectangular and jagged types Use multidimensional arrays

C# Programming: From Problem Analysis to Program Design4 Chapter Objectives ( continued ) Use the ArrayList class to create dynamic lists Learn about the predefined methods of the string class Be introduced to the other collection classes Work through a programming example that illustrates the chapter’s concepts

C# Programming: From Problem Analysis to Program Design5 Array Basics Data structure that may contain any number of variables Variables must be of same type Single identifier given to entire structure Individual variables are called elements Elements accessed through an index –Index also called subscript –Elements are sometimes referred to as indexed or subscripted variables

C# Programming: From Problem Analysis to Program Design6 Array Basics ( continued ) Arrays are objects of System.Array class Array class includes methods and properties –Methods for creating, manipulating, searching, and sorting arrays Create an array in the same way you instantiate an object of a user-defined class –Use the new operator –Specify number of individual elements

C# Programming: From Problem Analysis to Program Design7 Array Declaration Format for creating an array type [ ] identifier = new type [integral value]; Type can be any predefined types like int or string, or a class that you create in C# Integral value is the number of elements –Length or size of the array –Can be a constant literal, a variable, or an expression that produces an integral value

C# Programming: From Problem Analysis to Program Design8 Array Declaration ( continued ) Figure 7-1 Creation of an array

C# Programming: From Problem Analysis to Program Design9 Array Declaration ( continued ) Array identifier, name, references first element –Contains address where score[0] is located First index for all arrays is 0 Last element of all arrays is always referenced by an index with a value of the length of the array minus one Can declare an array without instantiating it The general form of the declaration is: type [ ] identifier;

C# Programming: From Problem Analysis to Program Design10 Array Declaration ( continued ) Figure 7-2 Declaration of an array

C# Programming: From Problem Analysis to Program Design11 Array Declaration ( continued ) If you declare array with no values to reference, 2 nd step required – dimension the array General form of the second step is: identifier = new type [integral value ]; Examples const int size = 15; string [ ] lastName = new string [25]; double [ ] cost = new double [1000]; double [ ] temperature = new double [size]; int [ ] score; score = new int [size + 15]; Two steps

C# Programming: From Problem Analysis to Program Design12 Array Initializers Compile-time initialization General form of initialization follows: type[ ] identifier = new type[ ] {value1, value2, …valueN}; Values are separated by commas Values must be assignment compatible to the element type –Implicit conversion from int to double Declare and initialize elements in one step

C# Programming: From Problem Analysis to Program Design13 Array Initializers ( continued ) Array length determined by number of initialization values placed inside curly braces Examples int [] anArray = {100, 200, 400, 600}; char [ ] grade = new char[ ] { ‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; double [ ] depth = new double [2] {2.5, 3}; No length specifier is required

C# Programming: From Problem Analysis to Program Design14 Array Initializers ( continued ) Figure 7-3 Methods of creating and initializing arrays at compile time

C# Programming: From Problem Analysis to Program Design15 Array Access Specify which element to access by suffixing the identifier with an index enclosed in square brackets score[0] = 100; Length – special properties of Array class Last valid index is always the length of the array minus one

C# Programming: From Problem Analysis to Program Design16 Array Access ( continued ) Try to access the array using an index value larger than the array length minus one, a nonintegral index value, or a negative index value – Run-time error Figure 7-4 Index out of range exception

C# Programming: From Problem Analysis to Program Design17 Example 7-6: Create and Use an Array /* AverageDiff.cs Author: Doyle */ using System; using System.Windows.Forms; namespace AverageDiff { class AverageDiff { static void Main( ) { int total = 0; double avg, distance;

C# Programming: From Problem Analysis to Program Design18 Example 7-6: Create and Use an Array ( continued ) //AverageDiff.cs continued string inValue; int [ ] score = new int[10]; //Line 1 // Values are entered for (int i = 0; i < score.Length; i++) //Line 2 { Console.Write("Enter Score{0}: ", i + 1); //Line 3 inValue = Console.ReadLine( ); score[i] = Convert.ToInt32(inValue); //Line 4 }

C# Programming: From Problem Analysis to Program Design19 //AverageDiff.cs continued // Values are summed for (int i = 0; i < score.Length; i++) { total += score[i]; //Line 5 } avg = total / score.Length; //Line 6 Console.WriteLine( ); Console.WriteLine("Average: {0}", avg); Console.WriteLine( ); Example 7-6 Create and Use an Array ( continued )

C# Programming: From Problem Analysis to Program Design20 //AverageDiff.cs continued // Output is array element and how far from the mean Console.WriteLine("Score\tDist. from Avg."); for (int i = 0; i < score.Length; i++) { distance = Math.Abs((avg - score[i])); Console.WriteLine("{0}\t\t{1}", score[i], distance); } Example 7-6 Create and Use an Array ( continued )

C# Programming: From Problem Analysis to Program Design21 Example 7-6 Create and Use an Array ( continued ) Figure 7-5 Output from AverageDiff example

C# Programming: From Problem Analysis to Program Design22 Sentinel-Controlled Access What if you do not know the number of elements you need to store? –Could ask user to count the number of entries and use that for the size when you allocate the array –Another approach: create the array large enough to hold any number of entries Tell users to enter a predetermined sentinel value after they enter the last value Sentinel value –Extreme or dummy value

C# Programming: From Problem Analysis to Program Design23 Using foreach with Arrays Used to iterate through an array Read-only access General format foreach (type identifier in expression) statement ; –Identifier is the iteration variable –Expression is the array –Type should match the array type

C# Programming: From Problem Analysis to Program Design24 Using foreach with Arrays ( continued ) string [ ] color = {"red", "green", "blue"}; foreach (string val in color) Console.WriteLine (val); Iteration variable, val represents a different array element with each loop iteration No need to increment a counter (for an index) Displays red, blue, and green on separate lines

C# Programming: From Problem Analysis to Program Design25 Array Class Base array class All languages that target Common Language Runtime More power is available with minimal programming

C# Programming: From Problem Analysis to Program Design26

C# Programming: From Problem Analysis to Program Design27

C# Programming: From Problem Analysis to Program Design28 Arrays as Method Parameters Can send arrays as arguments to methods Heading for method that includes array as a parameter modifiers returnType identifier (type [ ] arrayIdentifier...) –Open and closed square brackets are required –Length or size of the array is not included Example void DisplayArrayContents (double [ ] anArray )

C# Programming: From Problem Analysis to Program Design29 Pass by Reference Arrays are reference variables –No copy is made of the contents Array identifier memory location does not contain a value, but rather an address for the first element Actual call to the method sends the address –Call does not include the array size –Call does not include the square brackets Example DisplayArrayContents (waterDepth);

C# Programming: From Problem Analysis to Program Design30 Example 7-12: Using Arrays as Method Arguments /* StaticMethods.cs Author: Doyle */ using System; using System.Windows.Forms; namespace StaticMethods { class StaticMethods { public const string caption = "Array Methods Illustrated"; static void Main( ) { double [ ] waterDepth = {45, 19, 2, 16.8, 190, 0.8, 510, 6, 18 };

C# Programming: From Problem Analysis to Program Design31 Example 7-12: Using Arrays as Method Arguments ( continued ) // StaticMethods.cs continued double [ ] w = new Double [20]; DisplayOutput(waterDepth, "waterDepth Array\n\n" ); // Copies values from waterDepth to w Array.Copy(waterDepth, 2, w, 0, 5); //Sorts Array w in ascending order Array.Sort (w); DisplayOutput(w, "Array w Sorted\n\n" ); // Reverses the elements in Array w Array.Reverse(w); DisplayOutput(w, "Array w Reversed\n\n"); }

C# Programming: From Problem Analysis to Program Design32 Example 7-12: Using Arrays as Method Arguments ( continued ) // StaticMethods.cs continued // Displays an array in a MessageBox public static void DisplayOutput(double [ ] anArray, string msg) { foreach(double wVal in anArray) if (wVal > 0) msg += wVal + "\n"; MessageBox.Show(msg, caption); }

C# Programming: From Problem Analysis to Program Design33 Example 7-12: Using Arrays as Method Arguments ( continued ) Figure 7-6 Output from Examples 7-10 and 7-12

C# Programming: From Problem Analysis to Program Design34 Input Values into an Array // Instead of doing compile time initialization, input values public static void InputValues(int [ ] temp) { string inValue; for(int i = 0; i < temp.Length; i++) { Console.Write("Enter Temperature {0}: ", i + 1); inValue = Console.ReadLine( ); temp[i] = int.Parse(inValue); }

C# Programming: From Problem Analysis to Program Design35 Input Values into an Array ( continued ) To call InputValues(int [ ] temp) method int [ ] temperature = new int[5]; InputValues(temperature); Next slide, Figure 7-7, shows the result of inputting 78, 82, 90, 87, and 85

C# Programming: From Problem Analysis to Program Design36 Input Values into an Array ( continued ) Figure 7-7 Array contents after the InputValues( ) method is called

C# Programming: From Problem Analysis to Program Design37 Array Assignment Assignment operator (=) does not work as you would think –Assigned operand contains the same address as the operand on the right of the equal symbol

C# Programming: From Problem Analysis to Program Design38 Array Assignment ( continued ) Figure 7-8 Assignment of an array to reference another array

C# Programming: From Problem Analysis to Program Design39 Parameter Array Keyword params used –Appears in formal parameter list (heading to the method) –Must be last parameter listed in the method heading Indicates number of arguments to the method that may vary Parallel array –Two or more arrays that have a relationship

C# Programming: From Problem Analysis to Program Design40 Arrays in Classes Arrays can be used as fields or instance variables in classes Base type is declared with other fields – but, space is allocated when an object of that class is instantiated Example field declaration private int[ ] pointsScored; Space allocated in constructor pointsScored = new int[someIntegerValue];

C# Programming: From Problem Analysis to Program Design41 Array of User-Defined Objects Create just like you create arrays of predefined types Example Console.Write("How many players? "); inValue = Console.ReadLine( ); playerCnt = Convert.ToInt32(inValue); Player[ ] teamMember = new Player[playerCnt];

C# Programming: From Problem Analysis to Program Design42 Arrays as Return Types Methods can have arrays as their return type Example method heading public static int [ ] GetScores(ref int gameCnt) Example call to the method int [ ] points = new int [1000]; points = GetScores(ref gameCnt); –Method would include a return statement with an array

C# Programming: From Problem Analysis to Program Design43 PlayerApp Use of Arrays Figure 7-10 PlayerApp memory representation

C# Programming: From Problem Analysis to Program Design44 Two-Dimensional Arrays Two-dimensional and other multidimensional arrays follow same guidelines as one-dimensional Two kinds of two-dimensional arrays –Rectangular Visualized as a table divided into rows and columns –Jagged or ragged Referenced much like you reference a matrix Data stored in row major format (C# – row major language)

C# Programming: From Problem Analysis to Program Design45 Two-Dimensional Representation Figure 7-11 Two-dimensional structure

C# Programming: From Problem Analysis to Program Design46 Two-Dimensional Arrays ( continued ) Declaration format type [, ] identifier = new type [integral value, integral value]; –Two integral values are required for a two- dimensional array Number of rows listed first Data values placed in array must be of the same base type Example (create a 7x3 matrix) –int [, ] calories = new int[7, 3];

C# Programming: From Problem Analysis to Program Design47 Two-Dimensional Arrays ( continued ) calories references address of calories[0,0] Figure 7-12 Two-dimensional calories array

C# Programming: From Problem Analysis to Program Design48 Two-Dimensional Arrays ( continued ) Length property gets total number of elements in all dimensions Console.WriteLine(calories.Length); // Returns 21 GetLength( ) – returns the number of rows or columns –GetLength(0) returns number of rows –GetLength(1) returns number of columns Console.WriteLine(calories.GetLength(1)); //Display 3 (columns) Console.WriteLine(calories.GetLength(0)); //Display 7 (rows) Console.WriteLine(calories.Rank); // returns 2 (dimensions)

C# Programming: From Problem Analysis to Program Design49 Jagged Arrays Rectangular arrays always have a rectangular shape, like a table; jagged arrays do not Also called ‘arrays of arrays’ Example int[ ] [ ] anArray = new int[4] [ ]; anArray [0] = new int[ ] {100, 200}; anArray [1] = new int[ ] {11, 22, 37}; anArray [2] = new int[ ] {16, 72, 83, 99, 106}; anArray [3] = new int[ ] {1, 2, 3, 4};

C# Programming: From Problem Analysis to Program Design50 Multidimensional Arrays Limited only by your imagination as far as the number of dimensions Format for creating three-dimensional array type [,, ] identifier = new type [integral value, integral value, integral value]; Example (rectangular) int [,, ] calories = new int [4,7,3]; (4 week; 7 days; 3 meals) Allocates storage for 84 elements

C# Programming: From Problem Analysis to Program Design51 Multidimensional Arrays ( continued ) Upper bounds on the indexes are 3, 6, 2 Figure 7-13 Three-dimensional array

C# Programming: From Problem Analysis to Program Design52 ArrayList Class Limitations of traditional array –Cannot change the size or length of an array after it is created ArrayList class facilitates creating listlike structure, BUT it can dynamically increase or decrease in length –Similar to vector class found in other languages Includes large number of predefined methods

C# Programming: From Problem Analysis to Program Design53 ArrayList Class ( continued )

C# Programming: From Problem Analysis to Program Design54 ArrayList Class ( continued )

C# Programming: From Problem Analysis to Program Design55 String Class Stores a collection of Unicode characters Immutable series of characters Reference type –Normally equality operators, == and !=, compare the object’s references, but operators function differently with string than with other reference objects Equality operators are defined to compare the contents or values Includes large number of predefined methods

C# Programming: From Problem Analysis to Program Design56

C# Programming: From Problem Analysis to Program Design57

C# Programming: From Problem Analysis to Program Design58

C# Programming: From Problem Analysis to Program Design59

C# Programming: From Problem Analysis to Program Design60

C# Programming: From Problem Analysis to Program Design61 Other Collection Classes Number of other collection classes –BitArray class Stores a collection of bit values represented as Booleans – HashTable class Stores a collection of key/value pairs that are organized based on the hash code of the key –Queue class Represents a FIFO (first in, first out) collection –Stack class Represents a simple LIFO (last in, first out) collection

C# Programming: From Problem Analysis to Program Design62 Manatee Application Example Figure 7-16 Problem specification for Manatee example

C# Programming: From Problem Analysis to Program Design63 Manatee Application Example ( continued ) Figure 7-17 Prototype

C# Programming: From Problem Analysis to Program Design64 Manatee Application Example ( continued )

C# Programming: From Problem Analysis to Program Design65 Manatee Application Example ( continued ) Figure 7-18 Class diagrams

C# Programming: From Problem Analysis to Program Design66 Manatee Application Example ( continued )

C# Programming: From Problem Analysis to Program Design67 Pseudocode – Manatee Application Figure 7-19 ManateeSighting class methods behavior

C# Programming: From Problem Analysis to Program Design68 Chapter Summary Array declaration –Compile-time initialization –Accessing elements Array and ArrayList class methods Arrays as parameters to methods Classes that include array members –Instantiate user-defined array objects Multidimensional arrays String class