Sie sind auf Seite 1von 32

1

Topic 7 - Arrays
Outline
7.1
7.2
7.3
7.4

7.5
7.6
7.7
7.8

7.9
7.10

Introduction
Arrays
Declaring and Allocating Arrays
Examples Using Arrays
7.4.1
Allocating an Array and Initializing Its Elements
7.4.2
Totaling the Elements of an Array
7.4.5
Using Arrays to Analyze Survey Results
7.4.3
Using Histograms to Display Array Data Graphically
7.4.4
Using the Elements of an Array as Counters
7.4.5
Using Arrays to Analyze Survey Results
Passing Arrays to Methods
Passing Arrays by Value and by Reference
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
7.8.1
Searching an Array with Linear Search
7.8.2
Searching a Sorted Array with Binary Search
Multiple-Subscripted Arrays
for/each Repetition Structure

2002 Prentice Hall. All rights reserved.

7.1 Introduction
Data structures

Consist of data items of the same type


Static: remain the same size once created

2002 Prentice Hall. All rights reserved.

7.2 Arrays
A group of contiguous memory locations
Same name
Same type

Refer to particular element in the array by position


number
Can refer to any element by giving the name of the
array followed by the position number (subscript)
of the element in square brackets ([])
First element is the zeroth element

First element of array c is c[ 0 ]

2002 Prentice Hall. All rights reserved.

7.2 Arrays
Name of array (Note that
all elements of this array
have the same name, c)

Position number (index


or subscript) of the
element within array c

Fig. 7.1

A 12-element array.

2002 Prentice Hall. All rights reserved.

c[ 0 ]

-45

c[ 1 ]

c[ 2 ]

c[ 3 ]

72

c[ 4 ]

1543

c[ 5 ]

-89

c[ 6 ]

c[ 7 ]

62

c[ 8]

-3

c[ 9 ]

c[ 10 ]

6453

c[ 11 ]

-78

7.2 Arrays
Operators

Associativity

Type

++ -- + - ! (type)

right to left

unary (unary prefix)

left to right

multiplicative

left to right

additive

< <= > >=

left to right

relational

== !=

left to right

equality

&

left to right

boolean logical AND

left to right

boolean logical exclusive OR

left to right

boolean logical inclusive OR

&&

left to right

logical AND

||

left to right

logical OR

?:

right to left

conditional

= += -= *= /= %=

right to left

assignment

() [] . ++ --

Fig. 7.2

left to right

highest (unary postfix)

Precedence and associativity of the operators discussed so far.

2002 Prentice Hall. All rights reserved.

7.3 Declaring and Allocating Arrays

Programmer specifies the type of the elements of


the array
new operator to allocate dynamically the number
of elements in the array
Array declarations and initializations need not be
in the same statement
In arrays of value types, each element contains
one value of the declared type
In arrays of reference types, every element of the
array is a reference to an object of the data type of
the array
2002 Prentice Hall. All rights reserved.

7.3.1Allocating an Array and Initializing Its


Elements
Arrays can be allocated using the word new to
specify how many elements the array should hold
Arrays can be initialized with initializer lists

Allocate space for the array number of elements in


initializer list determines the size of array
Elements in array are initialized with the values in the
initializer list

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

Outline

// Fig 7.3: InitArray.cs


// Different ways of initializing arrays.
using System;
using System.Windows.Forms;
class InitArray
{
// main entry point for application
static void Main( string[] args )
{
string output = "";
int[] x;
x = new int[ 10 ];

InitArray.cs
Allocate x to be
of size 10
Declare an integer
array x

// declare reference to an array


// dynamically allocate array and set Declare a constant
ARRAY_SIZE
// default values
Declare
an integer

// initializer list specifies number of elements


// and value of each element
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

array y and initialize it


with values

Initialize the elements in z

const int ARRAY_SIZE = 10; // named constant


a for loop
int[] z;
// reference to using
int array
Declare
// allocate array of ARRAY_SIZE (i.e., 10) elements
z = new int[ ARRAY_SIZE ];
// set the values in the array
for ( int i = 0; i < z.Length; i++ )
z[ i ] = 2 + 2 * i;

an integer array z

Initialize z to be of size
ARRAY_SIZE

output += "Subscript\tArray x\tArray y\tArray z\n";

2002 Prentice Hall.


All rights reserved.

34
35
36
37
38
39
40
41
42
43
44
45

// output values for each array


for ( int i = 0; i < ARRAY_SIZE; i++ )
output += i + "\t" + x[ i ] + "\t" + y[ i ] +
"\t" + z[ i ] + "\n";
MessageBox.Show( output,
"Initializing an array of int values",
MessageBoxButtons.OK, MessageBoxIcon.Information );
} // end Main

Outline
InitArray.cs
Add values in the arrays to
output

} // end class InitArray

Program Output

2002 Prentice Hall.


All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 7.4: SumArray.cs


// Computing the sum of the elements in an array.
using System;
using System.Windows.Forms;

Declare integer array a


and initialize it

class SumArray
{
// main entry point for application
Total the
static void Main( string[] args )
array a
{
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;

SumArray.cs

contents of

for ( int i = 0; i < a.Length; i++ )


total += a[ i ];
MessageBox.Show( "Total of array elements: " + total,
"Sum the elements of an array",
MessageBoxButtons.OK, MessageBoxIcon.Information );
} // end Main
} // end class SumArray

Program Output

2002 Prentice Hall.


All rights reserved.

10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Outline

// Fig. 7.5: Histogram.cs


// Using data to create a histogram.
using System;
using System.Windows.Forms;

Declare an integer array


n and initialize it

class Histogram
{
// main entry point for application
static void Main( string[] args )
{
int[] n = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
string output = "";

Histogram.cs

Create a bar for each


element in n

output += "Element\tvalue\tHistogram\n";
// build output
for ( int i = 0; i < n.Length; i++ )
{
output += "\n" + i + "\t" + n[ i ] + "\t";

Print a bar consisting of


asterisks, corresponding to
the value of the element in n

for ( int j = 1; j <= n[ i ]; j++ ) // print a bar


output += "*";
}
MessageBox.Show( output, "Histogram Printing Program",
MessageBoxButtons.OK, MessageBoxIcon.Information );
} // end Main
} // end class Histogram

2002 Prentice Hall.


All rights reserved.

11

Outline
Histogram.cs
Program Output

2002 Prentice Hall.


All rights reserved.

12

13

7.5 Passing Arrays to Methods

Pass arrays as arguments to methods by specifying


the name of the array (no brackets)
Arrays are passed by reference
Individual array elements are passed by value

2002 Prentice Hall. All rights reserved.

7.6 Passing Arrays by Value and by


Reference
Variables that store object, actually store references to
those objects
A reference is a location in computers memory where the
object itself is stored
Passing value types to methods
A copy of the variable is made
Any changes to variable in method do not effect the original
variable

Passing reference types to methods

A copy of the reference to the object is made


Any changes to the reference in the method do not effect the
original variable
Any changes to the contents of the object in the method, do effect
the object outside the method
2002 Prentice Hall. All rights reserved.

14

7.6 Passing Arrays by Value and by


Reference
Keyword ref may be used to pass arguments to
method by reference
Value type variables are not copied modifying the variable
in the method will modify the variable outside the method
References to objects are not copied modifying the
reference in the method will modify the reference outside the
method

Programmers have to be careful when using ref

May lead to references being set to null


May lead to methods modifying variable values and
references in ways that are not desired

2002 Prentice Hall. All rights reserved.

15

16

7.7 Sorting Arrays


Sorting data is important in many applications
Bubble Sort array of size n
Make n passes through the array
For each pass, compare every pair of successful elements
If the first is larger then the second, swap the elements

Easy to program
Runs slowly

.NET Framework includes high-speed sorting


capabilities

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

Outline

// Fig. 7.10: BubbleSorter.cs


// Sorting an array's values into ascending order.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

BubbleSorter.cs

public class BubbleSorter : System.Windows.Forms.Form


{
private System.Windows.Forms.Button sortButton;
private System.Windows.Forms.Label outputLabel;
// Visual Studio .NET generated code

Declare and initialize array a

[STAThread]
static void Main()
{
Application.Run( new BubbleSorter() );
}

Output the contents of array a


Call method Bubble sort on array a

private void sortButton_Click( object sender,


System.EventArgs e )
{
int[] a = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
outputLabel.Text += "Data items in original order\n";
for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += "
" + a[ i ];
// sort elements in array a
BubbleSort( a );

17

2002 Prentice Hall.


All rights reserved.

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

Outline

outputLabel.Text += "\n\nData items in ascending order\n";


for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += "
" + a[ i ];
} // end method sortButton_Click

Swaps two elements


BubbleSorter.cs
of an array
If an given element is bigger
Output
sorted array a
then the following
element,

// sort the elements of an array with bubble sort


swap the elements
public void BubbleSort( int[] b )
{
for ( int pass = 1; pass < b.Length; pass++ ) // passes
for ( int i = 0; i < b.Length - 1; i++ )
if ( b[ i ] > b[ i + 1 ] )
Swap( b, i );
}

18

// one pass

// one comparison
// one swap

Perform
contents of for loop
Perform b.Length-1
passes
for each element of array b

// swap two elements of an array


public void Swap( int[] c, int first )
{
int hold;
// temporary holding area for swap
hold = c[ first ];
c[ first ] = c[ first + 1 ];
c[ first + 1 ] = hold;
}
}

Program Output

2002 Prentice Hall.


All rights reserved.

7.8 Searching Arrays: Linear Search and


Binary Search

Arrays may be very large


Sometimes necessary to determine if a particular
element is in the array
Linear Search
Binary Search

2002 Prentice Hall. All rights reserved.

19

20

7.8.1 Searching an Array with Linear Search

Return index of search key in array


Begin search at the beginning of array, continue
sequentially
On average, half the array needs to be searched to
find desired element
Works well for small or unsorted arrays

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

// Fig. 7.11: LinearSearcher.cs


// Demonstrating linear searching of an array.
using System;
using System.Drawing;
using System.Collections;
Retrieve the number user
using System.ComponentModel;
using System.Windows.Forms;
input as the search key
using System.Data;
public class LinearSearcher : System.Windows.Forms.Form
{
private System.Windows.Forms.Button searchButton;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Label outputLabel;

Outline

21

LinearSearcher.c
s

Perform linear search


for the search key

int[] a = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,
28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50 };
// Visual Studio .NET generated code
[STAThread]
static void Main()
{
Application.Run( new LinearSearcher() );
}
private void searchButton_Click( object sender,
System.EventArgs e )
{
int searchKey = Int32.Parse( inputTextBox.Text );
int elementIndex = LinearSearch( a, searchKey );

2002 Prentice Hall.


All rights reserved.

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

Outline

if ( elementIndex != -1 )
outputLabel.Text =
"Found value in element " + elementIndex;

LinearSearcher.c
s

else
outputLabel.Text = "Value not found";
} // end method searchButton_Click

If the index of the search key is


1, then element was not found

// search array for the specified key value


public int LinearSearch( int[] array, int key )
{
If search failed,
for ( int n = 0; n < array.Length; n++ )
{
if ( array[ n ] == key )
Start at beginning of array
return n;
Check every element to see if it
}
return -1;

22

return -1

matches the search key.


If it does, return the current index

} // end method LinearSearch


} // end class LinearSearcher

Program Output

2002 Prentice Hall.


All rights reserved.

7.8.2 Searching a Sorted Array with Binary


Search
Array must be sorted
Eliminate half the search elements at each step
Algorithm
Locate middle element
Compare to search key
If they are equal the element has been found, return subscript
of middle element
If the search key is less then the middle element, search the
first half of the array
If the search key is greater then the middle element, search the
second half of the array

Repeat above until search key is equal to the middle


element, or the subarray to be searched is on element (in
which case the search key is not in the array)
2002 Prentice Hall. All rights reserved.

23

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

Outline

// Fig. 7.12: BinarySearchTest.cs


// Demonstrating a binary search of an array.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

Declare and initialize


integer array a

BinarySearchTest
.cs

public class BinarySearchTest : System.Windows.Forms.Form


{
private System.Windows.Forms.Label promptLabel;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Label resultLabel;
private System.Windows.Forms.Label displayLabel;
private System.Windows.Forms.Label outputLabel;
private System.Windows.Forms.Button findButton;
private System.ComponentModel.Container components = null;
int[] a = { 0, 2, 4, 6, 8, 10, 12, 14, 16,
18, 20, 22, 24, 26, 28 };
// Visual Studio .NET generated code
// main entry point for application
[STAThread]
static void Main()
{
Application.Run( new BinarySearchTest() );
}

24

2002 Prentice Hall.


All rights reserved.

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

// searches for an element by calling


// BinarySearch and displaying results
private void findButton_Click( object sender,
System.EventArgs e )
{
int searchKey = Int32.Parse( inputTextBox.Text );

Outline

BinarySearchTest
.cs

If the low index is less then


the high index then try to
find element (otherwise,
Retrieveelement
the search
keyinthe
input
is not
theuser
array

// initialize display string for the new search


outputLabel.Text = "Portions of array searched\n";
// perform the binary search
int element = BinarySearch( a, searchKey );

if ( element != -1 )
Compute midpoint of
displayLabel.Text = "Found value in element " +
element;
current search space
else
Call method BinarySearch on
displayLabel.Text = "Value not found";
} // end findButton_Click

25

array a with the user input as


the search key

// searchs array for specified key


If 1 was returned,
public int BinarySearch( int[] array, int key )
{
search key was not
int low = 0;
// low subscript
int high = array.Length - 1; // high subscript
int middle;
// middle subscript

then
found

while ( low <= high )


{
middle = ( low + high ) / 2;

2002 Prentice Hall.


All rights reserved.

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

Outline

// the following line displays the portion


// of the array currently being manipulated during
// each iteration of the binary search loop
BuildOutput( a, low, middle, high );

26

BinarySearchTest
.cs
if ( key == array[ middle ] )
// match
return middle;
Output all elements of the
else if ( key < array[ middle ] )
high = middle - 1;
// search low end of array array within two indices and
else
mark the middle element.
low = middle + 1;
Print spaces
If the middle element matches
the for the other
elements
// end BinarySearch
search key, return the index
of the
middle element

return -1;

// search key not found

} // end method BinarySearch


public void BuildOutput(
int[] array, int low, int mid, int high )
{
for ( int i = 0; i < array.Length; i++ )
{
if ( i < low || i > high )
outputLabel.Text += "
";
// mark middle element in output
else if ( i == mid )
outputLabel.Text +=
array[ i ].ToString( "00" ) + "* ";

If the key value is smaller


then the middle element, set
the high index to be one less
then the current middle index
Otherwise, set the low index to be
one more then the middle index

2002 Prentice Hall.


All rights reserved.

99
100
101
102
103
104
105
106
107
108

else
outputLabel.Text +=
array[ i ].ToString( "00" ) + "
}
outputLabel.Text += "\n";

Outline

27

";

BinarySearchTest
.cs

} // end BuildOutput
} // end class BinarySearchTest

Program Output

2002 Prentice Hall.


All rights reserved.

Outline

28

BinarySearchTest
.cs
Program Output

2002 Prentice Hall.


All rights reserved.

29

7.9 Multiple-Subscripted Arrays


Require two or more subscripts to identify a
particular element
Arrays that req2uire two subscripts to identify an
element are called double-subscripted arrays
Rectangular arrays
Often represent tables in which each row is the same size
and each column is the same size
By convention, first subscript identifies the elements row
and the second subscript the elements column

Jagged Arrays

Arrays of arrays
Arrays that compose jagged arrays can be of different
lengths
2002 Prentice Hall. All rights reserved.

30

7.9 Multiple-Subscripted Arrays


Column 0

Column 1

Column 2

Column 3

Row 0

a[0, 0]

a[0, 1]

a[0, 2]

a[0, 3]

Row 1

a[1, 0]

a[1, 1]

a[1, 2]

a[1, 3]

Row 2

a[2, 0]

a [2, 1] a[2, 2]

a[2, 3]

Column index (or subscript)


Row index (or subscript)
Array name

Fig. 7.13 Double-subscripted array with three rows and four columns.

2002 Prentice Hall. All rights reserved.

31

7.10 foreach Repetition Structure

The foreach repetition structure is used to iterate


through values in data structures such as arrays
No counter
A variable is used to represent the value of each
element

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Outline

// Fig. 7.16: ForEach.cs


// Demonstrating for/each structure.
Use
using System;

the foreach loop to examine


each element in the array

class ForEach
{
// main entry point for the application
static void Main( string[] args )
{
int[,] gradeArray = { { 77, 68, 86, 73 },
{ 98, 87, 89, 81 }, { 70, 90, 86, 81 } };

ForEach.cs

If the current array element is smaller


then lowGrade, set lowGrade to contain
the value of the current element

int lowGrade = 100;


foreach ( int grade in gradeArray )
{
if ( grade < lowGrade )
lowGrade = grade;
}
Console.WriteLine( "The minimum grade is: " + lowGrade );
}
}

The minimum grade is: 68

2002 Prentice Hall.


All rights reserved.

32

Das könnte Ihnen auch gefallen