Vous êtes sur la page 1sur 54

LECTURE 12

Array

Arrays are data structures consisting of related data items


of the same type
An array is used to process a collection of data
of the same type
Examples:
A list of names
A list of temperatures
Arrays

are static entities (same size throughout program)


Consecutive group of memory locations
Same name and type (int, char, etc.)

Arrays can be of type

Pointer based arrays (C-style) used in this chapter


Arrays as objects (C++)
2

The Array Variables

The variables making up the array are referred to as

Indexed variables
Subscripted variables
Elements of the array

The number of indexed variables in an array is the


declared size, or size, of the array

The largest index is one less than the size


The first index value is zero

Declaring an Array

When declaring arrays, programmer specify

Format

Name
Type of array
Any data type
Number of elements (array size)
type arrayName[ arraySize ];

Example
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats

Declaring multiple arrays of same type

Use comma separated list, like regular variables


int b[ 100 ], x[ 27 ];
4

Array Variable Types

An array can have indexed variables of any type

All indexed variables in an array are of the


same type
This is the base type of the array

An indexed variable can be used anywhere an ordinary


variable of the base type is used

Using [ ] With Arrays

In an array declaration, [ ]'s enclose the size


of the array such as this array of 5 integers:
int score [5];

When referring to one of the indexed variables,


the [ ]'s enclose a number identifying one of
the indexed variables

score[3] is one of the indexed variables


The value in the [ ]'s can be any expression that
evaluates to one of the integers 0 to (size -1)

Array

To refer to a particular location or an element in array

Specify array name and position number (index)


Format

arrayname[ position number ]


First element in every array is zeroth element

Consider N-element array c

The elements are c[ 0 ], c[ 1 ] c[ n - 1 ]


Nth element as position N-1

Subscript

The position number within square brackets


Must be an integer o an integer expression (any integral type)
7

Array
Name
that
this
same

A 12-element
Array named c

of array (Note
all elements of
array have the
name, c)

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

Position number of the


element within array c

Array

Array elements like other variables

Assignment, printing for an integer array c


c[ 0 ] = 3;
cout << c[ 0 ];
Performing division on array element
x = c[ 6 ] / 2; /*divide seventh element of
array by 2 and assign the result to the variable x */
printing sum of first three array elements of array c
cout << c[ 0 ] + c[ 1 ] + c[ 2 ];

Can perform operations inside subscript


c[ 5 2 ]

same as

c[3]

Loops And Arrays

For loop

for-loops are commonly used to step through arrays


Set each element

Example

First index is 0

Last index is (size 1)

for (i = 0; i < 5; i++)


{
cout << score[i] << " off by "
<< (max - score[i]) << endl;
}

could display the difference between each score and the


maximum score stored in an array
10

Initializing Arrays

To initialize an array when it is declared

The values for the indexed variables are enclosed


in braces and separated by commas

Example
int children[3] = { 2,

12,

1 };

Is equivalent to:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;
11

12

Initializing Arrays

If too few values are listed in an initialization


statement

Example:

int a[10] = {5, 5};


initializes a[0] and a[1] to 5 and
a[2] through a[9] to 0
If values listed in initialization statement are more
than array elements, it causes a syntax error

The listed values are used to initialize the first of


the indexed variables
The remaining indexed variables are initialized to
a zero of the base type

13

Initializing Arrays

To set every element to same value


int n[ 5 ] = { 0 };

If array size omitted, values listed in


initialization statement determine size
int n[] = { 1, 2, 3, 4, 5 };

5 initializers, therefore 5 element array

14

Example program

Initializing the elements of an array to


zeroes

Following program uses for repetition


structure to initialize the elements of a tenelement integer array n to zero and prints the
array in a tabular form

15

C++ code
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

// Fig. 4.3: fig04_03.cpp


// Initializing an array.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>

Declare a 10-element array of


integers.
Initialize array to 0 using a
// n is an array of 10 integers for loop. Note that the array
has elements n[0] to n[9].

using std::setw;
int main()
{
int n[ 10 ];

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ )
n[ i ] = 0; // set element at location i to 0

cout << "Element" << setw( 13 ) << "Value" << endl;

setw specifies the field width in


which the next value is to be output

// output contents of array n in tabular format


for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
return 0; // indicates successful termination
} // end main

16

Output

17

Example program

Initializing the elements of an array with


declaration

Following program initializes an integer array


with 10 values and prints the array in tabular
format

18

C++ code
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

// Fig. 4.4: fig04_04.cpp


// Initializing an array with a declaration.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;

Note the use of the initializer


list.

int main()
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
cout << "Element" << setw( 13 ) << "Value" << endl;

// output contents of array n in tabular format


for ( int i = 0; i < 10; i++ )
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
return 0; // indicates successful termination
} // end main
19

Output

20

Array size (constant variables)

Array size Can be specified with constant variable (const)


const int size = 20;
Also called named constants or read-only variables
Use constants to declare the size of an array
Using a constant allows your code to be easily altered for use on a smaller or
larger set of data

Example

//Constants must be initialized when declared and can not be


modified there after
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];

for ( i = 0; i < NUMBER_OF_STUDENTS; i++)


cout << score[i] << " off by
<< (max score[i]) << endl;

Only the value of the constant can be changed to make


this code work for any number of students
21

Example program

Generating values to be placed into an


element of array

Following example initializes a 10-element


array s to the integers 2,4,6,..20 and prints
the array in tabular format.
These numbers are generated by multiplying
each successive value of the loop counter by 2
and adding 2

22

C++ code
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

// Fig. 4.5: fig04_05.cpp


// Initialize array s to the even integers from 2 to 20.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>

Note use of const keyword.


Only const variables can
int main()
{
specify array sizes.
// constant variable can be used to specify array size
The program becomes more
const int arraySize = 10;
scalable when we set the array
int s[ arraySize ]; // array s has 10 elements
size using a const variable.
for ( int i = 0; i < arraySize; i++ ) // set the valuesWe can change arraySize,
s[ i ] = 2 + 2 * i;
and all the loops will still
cout << "Element" << setw( 13 ) << "Value" << endl;
work (otherwise, wed have to
update every loop in the
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
program).
cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl;
using std::setw;

return 0; // indicates successful termination


} // end main

23

Output

24

Reading assignment

Book

C++ How to program by Deitel and Deitel


4th edition

Assignment

Fig 4.6 (correctly initializing and using a constant


variable)
Fig 4.7( A constant object must be initialized)
Study the programs in above figures and understand

using a properly initialized constant variable


What will happen if constant variable is not correctly
initialized
25

Example program

Computing the sum of the elements of an


array

Following program sums the values contained


in a the 12-element integer array a

26

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

// Fig. 4.8: fig04_08.cpp


// Compute the sum of the elements of the array.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
const int arraySize = 10;
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
// sum contents of array a
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];
cout << "Total of array element values is " << total << endl;
return 0; // indicates successful termination
} // end main
27

Output

28

Passing Arrays to functions

To pass an array to a function

Specify the name of Array without brackets


For Example

int myArray[ 24 ];
myFunction( myArray, 24 );
Pass array myArray to function myFunction
Array size is usually passed
Useful to iterate over all elements

C++ automatically passes arrays to functions


using simulated call-by-reference
29

Passing Arrays to functions

Arrays are passed by call-by-reference

Functions can modify original array data


Value of name of array is address of first element of
array

Function knows where the array is stored


Can modify the actual array elements in their original
memory locations

Individual array elements passed by call-by-value

Like regular simple variables


Such simple pieces of data are called scalar or scalar
quantities
square( myArray[3] );
30

Passing Arrays to functions

Indexed variables can be arguments to functions

Example

If a program contains these declarations:


int i, n, a[10];
void my_function(int n);
Variables a[0] through a[9] are of type int, making
these calls legal
my_function( a[ 0 ] )
my_function( a[ 3 ] );
my_function( a[ i ] );
31

Passing Arrays to functions

Functions taking arrays

For a function receiving array through function call, the


functions parameter list must specify that an array will
be received

Function prototype
void modifyArray( int b[], int arraySize );
void modifyArray( int [], int );
this prototype can also be written as

void modifyArray(int anyArrayName[], int

anyVariableName);

Names optional in prototype


Both take an integer array and a single integer
32

Passing Arrays to functions


An array parameter is indicated using
empty
brackets in the parameter list
For example
void fill_up(int a[ ], int size);

No need for array size between brackets

Ignored by compiler

33

Example of Function Calls With Arrays


If function fill_up is declared in this way:
void fill_up(int a[ ], int size);

and array score is declared this way:


int score[5],
number_of_scores;

fill_up is called in this way:


fill_up( score, number_of_scores );
34

Example program

Passing arrays and individual array


elements to functions

Following program demonstrates the difference


between passing an entire array and passing
an array element.

35

C++ code
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

// Fig. 4.14: fig04_14.cpp


// Passing arrays and individual array elements to functions.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;

Syntax for accepting an array


in parameter list.

void modifyArray( int [], int ); // appears strange


void modifyElement( int );
int main()
{
const int arraySize = 5;
// size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a
cout << "Effects of passing entire array by reference:"
<< "\n\nThe values of the original array are:\n";
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 3 ) << a[ i ];
36

C++ code
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

cout << endl;


// pass array a to modifyArray by reference
modifyArray( a, arraySize );

Pass array name (a) and size


to function. Arrays are passedby-reference.

cout << "The values of the modified array are:\n";


// output modified array
for ( int j = 0; j < arraySize; j++ )
cout << setw( 3 ) << a[ j ];
// output value of a[ 3 ]
cout << "\n\n\n"
<< "Effects of passing array element by
value:"
Pass
a single
<< "\n\nThe value of a[3] is " << a[ 3 ] << '\n';
// pass array element a[ 3 ] by value
modifyElement( a[ 3 ] );

array element by
value; the original cannot be
modified.

// output value of a[ 3 ]
cout << "The value of a[3] is " << a[ 3 ] << endl;
return 0; // indicates successful termination
} // end main

37

C++ code
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

// in function modifyArray, "b" points to


// the original array "a" in memory
void modifyArray( int b[], int sizeOfArray )
{
// multiply each array element by 2
for ( int k = 0; k < sizeOfArray; k++ )
b[ k ] *= 2;

Although named b, the array


points to the original array a.
It can modify as data.

Individual array elements are


passed by value, and the
// in function modifyElement, "e" is a local copy of
originals cannot be changed.
// array element a[ 3 ] passed from main
} // end function modifyArray

void modifyElement( int e )


{
// multiply parameter by 2
cout << "Value in modifyElement is "
<< ( e *= 2 ) << endl;
} // end function modifyElement

38

Output

39

Output description

Program first prints 5 elements of integer array a

a and its size are passed to function modifyArray, where each of


as elements is multiplied by 2

a is reprinted in main

Program prints the value of a[3] and passes it to function


modifyElement

Function modifyElement multiplies its argument by 2 and prints


the new value

Note that when a[3] is reprinted in main, it has not been


modified, because individual array elements are passed by call-byvalue
40

Const Modifier

Array parameters allow a function to change the


values stored in the array argument
If a function should not change the values of the
array argument, use the modifier const
An array parameter modified with const is a
constant array parameter
If declare array parameter as const

Cannot be modified (compiler error)

Examples

void show_the_world (const int a[ ], int size);


void doNotModify( const int [] );
41

Using const with Arrays

If const is used to modify an array parameter

const is used in both the function declaration and


definition to modify the array parameter

The compiler will issue an error if you write code


that changes the values stored in the array parameter

42

Function Calls and const

If a function with a constant array parameter


calls another function using the const array
parameter as an argument

The called function must use a constant


array parameter as a placeholder for the array

The compiler will issue an error if a function is


called that does not have a const array parameter to
accept the array argument

43

Const Parameters Example

double compute_average(int a[ ], int size);

void show_difference(const int a[ ], int size)


{
double average = compute_average(a, size);

}
compute_average has no constant array parameter

This code generates an error message because


compute_average could change the array parameter

44

Reading assignment

c++ how to program by

Figure 4.15

Deitel and Deitel 3rd or 4th eddition

demonstrates the cont type qualifier

Study the program and find the errors in


the program also find a way to rectify the
errors
45

Returning An Array

Recall that functions can return a value of


type int, double, char, , or a class type

Functions cannot return arrays

We learn later how to return a pointer to


an array

46

Sorting Arrays

Sorting data

Important computing application


Virtually every organization must sort some data

Massive amounts must be sorted

Bubble sort (sinking sort)

Several passes through the array


Successive pairs of elements are compared

If increasing order (or identical), no change


If decreasing order, elements exchanged

Repeat these steps for every element


47

Sorting Arrays

Example:

Go left to right, and exchange elements as necessary

One pass for each element

Original: 3 4 2 7 6
Pass 1:
3 2 4 6 7 (elements exchanged)
Pass 2:
2 3 4 6 7
Pass 3:
2 3 4 6 7 (no changes needed)
Pass 4:
2 3 4 6 7
Pass 5:
2 3 4 6 7
Small elements "bubble" to the top (like 2 in this
example)

48

Sorting Arrays

Swapping variables
int x = 3, y = 4;
y = x;
x = y;

What happened?

Both x and y are 3!


Need a temporary variable

Solution
int x = 3,
temp = x;
x = y;
y = temp;

y = 4, temp = 0;
// temp gets 3
// x gets 4
// y gets 3
49

Example program

Sorting an array with bubble sort

Following program sorts the values of a


10-element array into ascending order
using the bubble sort (sinking sort)
technique as discussed earlier

50

C++ code
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

// Fig. 4.16: fig04_16.cpp


// This program sorts an array's values into ascending order.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
int main()
{
const int arraySize = 10; // size of array a
int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold; // temporary location used to swap array elements
cout << "Data items in original order\n";
// output original array
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << a[ i ];
// bubble sort
// loop to control number of passes
for ( int pass = 0; pass < arraySize - 1; pass++ )

Do a pass for each element in


the array.
51

C++ code
27
28
29
30
31
32
33
34
35
36
37
38
39 40
41
42
43
44
45
46
47
48
49
50 }

// loop to control number of comparisons per pass


for ( int j = 0; j < arraySize - 1; j++ )
// compare side-by-side elements and swap them if
// first element is greater than second element
if ( a[ j ] > a[ j + 1 ] ) {
hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = hold;
} // end if
cout << "\nData items in ascending order\n";

If the element on the left


(index j) is larger than the
element on the right (index j
+ 1), then we swap them.
Remember the need of a temp
variable.

// output sorted array


for ( int k = 0; k < arraySize; k++ )
cout << setw( 4 ) << a[ k ];
cout << endl;
return 0; // indicates successful termination
// end main

52

Output

53

Sorting Arrays

The chief virtue of bubble sort is

It is easy to program

The drawback is

It runs slowly, this becomes apparent when


sorting large arrays

54

Vous aimerez peut-être aussi