Tài liệu Module 6: Arrays - Pdf 84

Contents
Overview 1
Overview of Arrays 2
Creating Arrays 10
Using Arrays 17
Lab 6.1: Creating and Using Arrays 29
Review 40

Module 6: Arrays
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any


The module begins with explanations of the basic concepts of arrays, including
notation, variables, and rank. It provides the syntax for declaring an array
variable, for accessing an array element, and for checking array bounds. Note
that the syntax for creating an array instance is covered in the next section.
The second section explains how to create and initialize arrays. The third
section describes how to use array properties and methods, how to pass arrays
as parameters, how to return arrays from methods, how to use command-line
arguments to Main, and how to use foreach statements on arrays.
In Exercise 1, students write a program that expects the name of a text file as an
argument to Main and then reads the contents of the named text file into an
array of characters. It then iterates through the array of characters, classifying
each character as a vowel or a consonant. Finally, the program summarizes the
contents of the array by printing a short report to the console.
In Exercise 2, students create and use arrays of rank 2 and use the
Array.GetLength(int dimension) method.
After completing this module, students will be able to:

Create, initialize, and use arrays of varying rank.

Use command-line arguments in a C# program.

Understand the relationship between an array variable and an array instance.

Use arrays as method parameters.

Return arrays from methods.

Presentation:
45 Minutes


Practice the demonstration.

Module 6: Arrays v Demonstration
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Arguments for Main

To prepare for the demonstration
• Using a text editor, type in the following code and save it to a file called
CommandLine.cs.

using System;
class Demonstration {

static void Main(string[ ] args) {
Console.WriteLine("using for:");
for (int i = 0; i < args.Length; i++) {
Console.WriteLine("{0} {1}", i, args[i]);
}
}
} 
To demonstrate using arguments for Main
1. Using a text editor, show the code for CommandLine.cs and point out the

}

6. Recompile CommandLine.cs from the command prompt:
C:> csc /t:exe CommandLine.cs

7. From the command line, rerun CommandLine.exe, supplying parameters as
shown below:
C:> CommandLine Hello World

8. Verify that the output is as follows:
Using foreach:
Hello
World Module 6: Arrays vii Module Strategy
Use the following strategy to present this module:

Overview of Arrays
When presenting this section, consider the following issues:
• Do not use array creation expressions in your examples. (These
expressions are covered in the next section.)
• Exceptions from out-of-bounds access attempts are not the focus of this
module.
• Mention that ragged arrays are no longer considered CLS compliant
types.
• In Exercise 1 of the lab, students are required to use constructor

Module 6: Arrays 1 Overview

Overview of Arrays

Creating Arrays

Using Arrays

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Arrays provide an important means for grouping data. To make the most of C#,
it is important to understand how to use and create arrays effectively.
After completing this module, you will be able to:

Create, initialize, and use arrays of varying rank.

Use command-line arguments in a C# program.

Understand the relationship between an array variable and an array instance.

Use arrays as parameters for methods.

Return arrays from methods.



*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
This section provides an overview of general array concepts, introduces the key
syntax used to declare arrays in C#, and describes basic array features such as
rank and elements. In the next section, you will learn how to define and use
arrays.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
This section provides an
overview of array concepts,
core features, and basic
syntax.
Module 6: Arrays 3 What Is an Array?

An array is a sequence of elements

All elements in an array have the same type

Structs can have elements of different types


Data rarely exists in
isolation. Most data comes
in large quantities.
Delivery Tip
Describe the differences
between an array and a
struct. Structs can contain
different types and have
members that are accessed
by name. Arrays contain the
same type and have
elements that are accessed
by integer index.
Emphasize that because
there are generally many
pieces of information to
consider in any situation,
arrays are a natural
concept. For example, an
array of houses is a street.
4 Module 6: Arrays Array Notation in C#

You declare an array variable by specifying:

The element type of the array

The rank of the array

The following are examples of allowed and disallowed notation in C#:
type[ ]name; // Allowed
type name[ ]; // Disallowed in C#
type[4] name; // Also disallowed in C#

Topic Objective
To introduce the syntax and
terminology used to declare
an array in C#.
Lead-in
Most computer languages
provide a notation that
allows you to declare a
program entity as an array.
Delivery Tip
Rank is covered in the next
slide.

This slide only shows the
syntax for an array of
rank 1. The syntax is
extended in the next slide to
show arrays of rank 2.
Module 6: Arrays 5 Array Rank

Rank is also known as the array dimension


how to declare arrays of
rank 2.
Lead-in
Different kinds of arrays
require different numbers of
indexes in order to access
specific array elements. For
example, the cells in a
Microsoft Excel spreadsheet
require a row index and a
column index.
Delivery Tip
Introduce the term rank with
respect to arrays. The slide
shows syntax for arrays of
rank 1 and 2. Give an
example of rank 3 on a
whiteboard or flip chart.

Note: The graphics that
depict array instances of
rank 1 and 2 do not show
array instance lengths
because this syntax has not
been covered yet.
6 Module 6: Arrays Accessing Array Elements


To access array elements, you use a syntax that is similar to the syntax you use
to declare array variables—both use square brackets. This visual similarity
(which is deliberate and follows a trend popularized by C and C++) can be
confusing if you are not familiar with it. Therefore, it is important for you to be
able to distinguish between an array variable declaration and an array element
access expression.
To access an element inside an array of rank 1, use one integer index. To access
an element inside an array of rank 2, use two integer indexes separated by a
comma. This notation extends in the same way as the notation for declaring
variables. To access an element inside an array of rank n, use n integer indexes
separated by commas. Notice again that the syntax used in an array element
access expression mirrors the syntax that is used to declare variables.
Array indexes (for all ranks) start from zero. To access the first element inside a
row, use the expression:
row[0]

rather than the expression:
row[1]

Topic Objective
To show the syntax for
accessing an array element
and to emphasize that array
indexes start at zero.
Lead-in
Once you have declared an
array variable, you need to
be able to access the
elements inside the array.
Delivery Tip

not at [size]. Accidentally using [size] is a common off-by-one error, especially
for programmers used to a language that indexes from one, such as
Visual Basic.

Although the technique is rarely used, it is possible to create arrays that
have user-defined integer index lower bounds. For more information, search for
“Array.CreateInstance” in the Microsoft .NET Framework SDK Help
documents.

Note
8 Module 6: Arrays Checking Array Bounds

All array access attempts are bounds checked

A bad index throws an IndexOutOfRangeException

Use the Length property and the GetLength method
row
row
grid
grid
row.GetLength(0)==6
row.GetLength(0)==6
row.Length==6
row.Length==6
grid.GetLength(0)==2
grid.GetLength(0)==2

Topic Objective
To explain the behavior of
an array index when it is out
of bounds and to show how
to find the length of each
array rank.
Lead-in
What happens when an
index is out of bounds? How
can you find the length of
each array rank?
Delivery Tip
This slide only depicts array
instances of set lengths to
allow you to cover both the
Length property and
GetLength method. It is
important to cover
GetLength because it is
required in Exercise 2 of the
lab.

Do not spend a lot of time
on the
IndexOutOfRangeException

exception. Exceptions are
not the focus of this module
and are not part of the
exercises.

int[ ] rigid = new int [ 42 ];

The array will never shrink or expand, and it will never contain anything other
than ints. Collections are more flexible; they can expand or contract as elements
are removed and added. Arrays are intended to hold elements of a single type,
but collections were designed to contain elements of many different types. You
can achieve this flexibility by using boxing, as follows:
ArrayList flexible = new ArrayList( );
flexible.Add("one"); // Add a string here
...
flexible.Add(99); // And an int here!

You cannot create an array instance with read-only elements. The following
code will not compile:
const int[ ] array = {0, 1, 2, 3};
readonly int[ ] array = {4,2};

However, you can create a read-only collection as follows:
ArrayList flexible = new ArrayList( );
...
ArrayList noWrite = ArrayList.ReadOnly(flexible);
noWrite[0] = 42; // Causes run-time exception

Topic Objective
To describe the high-level
strengths and weaknesses
of arrays and collections.
Lead-in
What are the strengths and
weaknesses of arrays and



Creating Arrays

Creating Array Instances

Initializing Array Elements

Initializing Multidimensional Array Elements

Creating a Computed Size Array

Copying Array Variables

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this section, you will learn how to create array instances, how to explicitly
initialize array instance elements, and how to copy array variables.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
Now that the basic array
concepts have been
introduced, let’s look at the
syntax you will use to create

because arrays are reference types and not value types. You use the new
keyword to create an array instance, also referred to as an array creation
expression. You must specify the size of all rank lengths when creating an array
instance. The following code will result in a compile-time error:
long[ ] row = new long[ ]; // Not allowed
int[,] grid = new int[,]; // Not allowed

The C# compiler implicitly initializes each array element to a default value
dependent on the array element type: integer array elements are implicitly
initialized to 0, floating-point array elements are implicitly initialized to 0.0,
and Boolean array elements are implicitly initialized to false. In other words,
the C# code:
long[ ] row = new long[4];

will execute the following code at run-time:
long[ ] row = new long[4];
row[0] = 0L;
row[1] = 0L;
row[2] = 0L;
row[3] = 0L;

Topic Objective
To introduce array instances
and to explain the
relationship between array
variables and array
instances.
Lead-in
An array variable is not like
any other variable that you

create a ragged array with
three elements, each of
which is an array of ints.
(Each array has a default
value of null.)

int[ ][ ] table =
new int[3][ ];

The slide mentions the
default array element
initialization to zero, which
leads nicely into the next
slide.

Students will use the syntax
for declaring arrays of rank
1 and 2 in Exercises 1 and 2
of the lab, respectively.

C++ programmers may ask
about a possible delete
keyword to match the new
keyword. Deflect questions
like this; garbage collection
is covered in a later module.


Nhờ tải bản gốc
Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status