23
Chapter 8 Arrays Programming in C# .NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Embed Size (px)

Citation preview

Page 1: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Chapter 8 Arrays

Programming in C# .NET

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Page 2: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 2

Objectives

• Establish an array and refer to individual elements in the array with subscripts

• Use a foreach loop to traverse the elements of an array

• Create a structure for multiple fields of related data

• Accumulate totals using arrays

Page 3: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 3

Objectives cont.

• Distinguish between direct access and indirect access of a table

• Write a table lookup for matching an array element

• Combine the advantage of list box controls with arrays

• Store and look up data in multidimensional arrays

Page 4: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 4

Single-Dimension Arrays

• An array is a list or series of values, similar to a list box without the box

• Create an array to keep a series of variables for later processing

• Each individual variable in an array is referenced by the same name

• Arrays also called tables or subscripted variables• Each individual variable is an element of the array• Subscript (or index) inside parentheses is the

position of the element within the array

Page 5: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 5

Subscripts• Subscripts may be constants, variables, or numeric

expressions• Subscripts must be integers• Specify the number of elements in the array in the

array’s declaration statement• Array subscripts are zero based• You declare a data type for the array and all array

elements must be the same data type• A subscript must reference a valid element of the array• Exception will be thrown if a subscript is out of range

Page 6: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 6

Declaration Statement for Arrays

• General FormDatatype[] ArrayName = new

DataType[NumberofElements];

Datatype[] ArrayName = new DataType[] {InitialValueList};

Datatype[] ArrayName = {InitialValueList};

• Examplesstring[] strName = new string[25];

decimal[] decBalance = new decimal[10];

string[] strProduct = new string[99];

int[] intValue = new int[] {1,5,12,18,20};

string[] strName = {“Sean”, “Sam”, “Sally”, “Sara”};

Page 7: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 7

foreach Statement

• foreach is a looping construct that does not require manipulation of the array subscripts

• General Formforeach (DataType ElementName in ArrayName){

//Statement(s) in loop}

• C# automatically references each array element, assigns its value to ElementName, and makes one pass through the loop

• The foreach loop will execute if the array has at least one element

Page 8: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 8

foreach Examples

foreach (string strOneName in strName)

{

Console.WriteLine(strOneName); //Write one element of the array

}

int intSum;

foreach (int intOneTotal in intTotal)

{

intSum += intOneTotal; //Add each element of the array to intSum

}

Page 9: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 9

Structures

• Combine multiple fields of related data to create a new structure

• Defining a structure is similar to defining a new data type

• Struct declaration cannot go inside a method• By default, a structure is public• If an array is included inside a structure,

you cannot specify the number of elements

Page 10: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 10

Structures cont.

• General Form[public | private] struct NameOfStruct{

public Datatype FirstField;public Datatype SecondField;. . .

}

• Examplepublic struct Product{

public string strDescription;public string strID;public int intQuantity;public decimal decPrice;

}

Page 11: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 11

Structures cont.

• Once a structure is created, declare variables of the structure

• Each field of data in variable declared as a structure is called an element of the structure

• C# does not allow declaration of the number of elements in an array in the struct declaration

• Using a value as an index to an array is called a direct reference

• View contents of array elements in break time using the Autos window by clicking on the plus sign at left of the array name

Page 12: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 12

Table Lookup

• Determine which array element to update or access using a table lookup

• Use a while loop for a table lookup• Validate input before performing table lookup• Compare input to each element in array to find a

match• It is not necessary to arrange fields being searched

in any particular sequence

Page 13: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 13

Using List Boxes with Arrays

• It is a good idea to use a list box for input of information to lookup in array

• Use the SelectedIndex property to determine the array subscript– SelectedIndex holds the position or index of the

selected item from the list

Page 14: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 14

Multidimensional Arrays

• Two-dimensional arrays have rows and columns

• Array declaration specifies number of rows and columns in the array

• Row is horizontal and column is vertical• Must always use two subscripts to refer to

individual elements of table– Row is first subscript– Column is second subscript

Page 15: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 15

Multidimensional Arrays cont.

• General FormDataType[,] ArrayName = new Datatype[NumberOfElements,NumberOfElements];DataType[,] ArrayName = new DataType[ , ] = {ListOfValues};

• Cannot specify the number of elements within parentheses and specify the initial values

• Must use a comma to specify two dimensions to the array

• Examples:string[,] strName = new string[3,4];string[,] strName = new string[ , ] = {{“James”, “Mary”, “Sammie”, “Sean”},

{“Tom”, “Lee”, “Leon”, “Larry”}, {“Maria”, “Margaret”, “Jill”, “John”}};

Page 16: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 16

Initialize Two-Dimensional Arrays

• Numeric array elements are initialized to 0 and strings are initialized to empty strings

• Use nested for loops to initialize array elements

int intRow, intColumn;for (intRow = 0; intRow < 3; intRow++){

for (intColumn = 0; intColumn < 4; intColumn++){

strName[intRow, intColumn] = “”;}

}

Page 17: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 17

Printing a Two-Dimensional Table

• Use a foreach loop to print contents of a two-dimensional table– Prints one array element per line

• Use a for loop and specify x and x coordinates to print multiple elements per line

Page 18: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 18

Summing a Two-Dimensional Table

• There are several ways to sum a table– Sum the columns– Sum the rows– Sum the figures in both directions and double-

check the totals

• To sum an array in both directions, create two one-dimensional arrays to store the total fields

Page 19: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 19

Lookup Operation for Two-Dimensional Tables

• Use direct reference and table lookup as in single-dimensional arrays

• Limitations– Row and column subscripts must be available to use

direct reference

– Table lookup is the most common lookup technique

• Lookup processes may require additional one-dimensional arrays or lists– Use list boxes or text boxes

Page 20: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 20

Your Hands-On Programming Example

Create a project for R ‘n R – Reading ‘n Refreshment that determines the price per pound for bulk coffee sales. The coffees are divided into categories: regular, decaf, and special blend. The prices are set by the quarter pound, half pound, and full pound. Use a Find Price button to search for the appropriate price based on the selections.

Page 21: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 21

Summary

• A series of variables with the same name and data type is called an array. The individual values are referred to as elements, and each element is accessed by its subscript, which is a position number.

• Array subscripts or indexes are zero based; they must be integers in the range of the array elements. C# rounds noninteger values.

• You can assign initial values in the declaration or specify the number of elements.

Page 22: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 22

Summary cont.

• A special form of the for loop called foreach is used to work with arrays. The foreach eliminates the need to manipulate the subscripts of the array.

• You can declare a structure to combine related fields then declare variables and arrays of the structure. The struct statement should appear at the class level.

• Array elements are used like any other variables; they can be used to accumulate a series of totals or to store values for a lookup procedure.

Page 23: Chapter 8 Arrays Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.8- 23

Summary cont.

• The information in arrays may be accessed directly by subscript, or a table lookup is used to determine the correct table position.

• You can use the SelectedIndex property of a list box as a subscript of an array.

• Arrays may be multidimensional. A two-dimensional table contains rows and columns. Accessing a multidimensional array frequently requires the use of nested loops.