You are on page 1of 75

Chapter 7:

Arrays

Copyright 2012 Pearson Education, Inc.

7.1
Arrays Hold Multiple Values

Copyright 2012 Pearson Education, Inc.

Arrays Hold Multiple Values


Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared usin [] operator:
int tests[5];

Copyright 2012 Pearson Education, Inc.

Array ! Memory "ayout


#he definition:
int tests[5];

allocates the follo$in memory:

first element

second element

third element

fourth element

fifth element

Copyright 2012 Pearson Education, Inc.

Array #erminolo y
%n the definition int tests[5]; int is the data type of the array elements tests is the name of the array 5, in [5], is the si&e declarator. %t sho$s the number of elements in the array. #he si&e of an array is 'number of elements( ) 'si&e of each element(

Copyright 2012 Pearson Education, Inc.

Array #erminolo y
#he si&e of an array is:
* the total number of bytes allocated for it * 'number of elements( ) 'number of bytes for each element(

+,amples:
int tests[5] is an array of -. bytes/ assumin 0 bytes for an int long double measures[10]is an array of 1. bytes/ assumin 1 bytes for a long double
Copyright 2012 Pearson Education, Inc.

2i&e Declarators
3amed constants are commonly used as si&e declarators. const int SIZE = 5; int tests[SIZE]; #his eases pro ram maintenance $hen the si&e of the array needs to be chan ed.

Copyright 2012 Pearson Education, Inc.

7.Accessin Array +lements

Copyright 2012 Pearson Education, Inc.

Accessin Array +lements


+ach element in an array is assi ned a uni4ue subscript. 2ubscripts start at .
subscripts 1 :0

Copyright 2012 Pearson Education, Inc.

Accessin Array +lements


#he last element5s subscript is n!1 $here n is the number of elements in the array.

subscripts 1 :0

Copyright 2012 Pearson Education, Inc.

Accessin Array +lements


Array elements can be used as re ular variables:
tests[0] = !"; cout ## tests[0]; cin $$ tests[1]; tests[ ] = tests[0] % tests[1];

Arrays must be accessed via individual elements:


cout ## tests; && not legal
Copyright 2012 Pearson Education, Inc.

(Program Continues)
Copyright 2012 Pearson Education, Inc.

Here are the contents of the 'ours array/ $ith the values entered by the user in the e,ample output:

Copyright 2012 Pearson Education, Inc.

Accessin Array 6ontents


6an access element $ith a constant or literal subscript:
cout ## tests[3] ## endl;

6an use inte er e,pression as subscript:


int i = 5; cout ## tests[i] ## endl;

Copyright 2012 Pearson Education, Inc.

7sin a "oop to 2tep #hrou h an Array


+,ample * #he follo$in code defines an array/ numbers/ and assi ns 88 to each element:
const int ())(*+SIZE = 5; int numbers[())(*+SIZE]; ,or -int count = 0; count # ())(*+SIZE; count%%. numbers[count] = "";

Copyright 2012 Pearson Education, Inc.

A 6loser "oo9 At the "oop

Copyright 2012 Pearson Education, Inc.

Default %nitiali&ation
:lobal array all elements initiali&ed to 0 by default "ocal array all elements uninitialized by default

Copyright 2012 Pearson Education, Inc.

7.;
3o <ounds 6hec9in in 6==

Copyright 2012 Pearson Education, Inc.

3o <ounds 6hec9in in 6==


>hen you use a value as an array subscript/ 6== does not chec9 it to ma9e sure it is a valid subscript. %n other $ords/ you can use subscripts that are beyond the bounds of the array.

Copyright 2012 Pearson Education, Inc.

6ode ?rom @ro ram 7!A


#he follo$in code defines a three! element array/ and then $rites five values to itB

Copyright 2012 Pearson Education, Inc.

>hat the 6ode Does

Copyright 2012 Pearson Education, Inc.

3o <ounds 6hec9in in 6==


<e careful not to use invalid subscripts. Doin so can corrupt other memory locations/ crash pro ram/ or loc9 up computer/ and cause elusive bu s.

Copyright 2012 Pearson Education, Inc.

Cff!<y!Cne +rrors
An off!by!one error happens $hen you use array subscripts that are off by one. #his can happen $hen you start subscripts at 1 rather than .:
&& /'is code 'as an o,,0b10one error2 const int SIZE = 100; int numbers[SIZE]; ,or -int count = 1; count #= SIZE; count%%. numbers[count] = 0;

Copyright 2012 Pearson Education, Inc.

7.0
Array Initialization

7.0
Array %nitiali&ation

Copyright 2012 Pearson Education, Inc.

Array %nitiali&ation
Arrays can be initiali&ed $ith an initiali&ation list:
const int SIZE = 5; int tests[SIZE] = 3!",42,"1,!!,4 5;

#he values are stored in the array in the order in $hich they appear in the list. #he initiali&ation list cannot e,ceed the array si&e.
Copyright 2012 Pearson Education, Inc.

7!-D

6ode ?rom @ro ram 7!D

Copyright 2012 Pearson Education, Inc.

@artial Array %nitiali&ation


%f array is initiali&ed $ith fe$er initial values than the si&e declarator/ the remainin elements $ill be set to 06

Copyright 2012 Pearson Education, Inc.

%mplicit Array 2i&in


6an determine array si&e by the si&e of the initiali&ation list:
int 7ui88es[]=312,1!,15,115;
12 1! 15 11

Must use either array si&e declarator or initiali&ation list at array definition

Copyright 2012 Pearson Education, Inc.

7.A
@rocessin Array 6ontents

Copyright 2012 Pearson Education, Inc.

@rocessin Array 6ontents


Array elements can be treated as ordinary variables of the same type as the array >hen usin %%/ 00 operators/ don5t confuse the element $ith the subscript:
tests[i]%%; && add 1 to tests[i] tests[i%%]; && increment i, no && e,,ect on tests

Copyright 2012 Pearson Education, Inc.

Array Assi nment


#o copy one array to another/ Don5t try to assi n one array to the other:
ne9/ests = tests; && :on;t 9or<

%nstead/ assi n element!by!element:


,or -i = 0; i # ())(*+SIZE; i%%. ne9/ests[i] = tests[i];

Copyright 2012 Pearson Education, Inc.

@rintin the 6ontents of an Array


Eou can display the contents of a character array by sendin its name to cout: c'ar ,=ame[] = >?enr1>;
cout ## ,=ame ## endl; <ut/ this C3"E $or9s $ith character arraysB

Copyright 2012 Pearson Education, Inc.

@rintin the 6ontents of an Array


?or other types of arrays/ you must print element!by!element:
,or -i = 0; i # ())(*+SIZE; i%%. cout ## tests[i] ## endl;

Copyright 2012 Pearson Education, Inc.

2ummin and Avera in Array +lements


7se a simple loop to add to ether array elements:
int tnum; double a@erage, sum = 0; ,or-tnum = 0; tnum # SIZE; tnum%%. sum %= tests[tnum];

Cnce summed/ can compute avera e:


a@erage = sum & SIZE;
Copyright 2012 Pearson Education, Inc.

?indin the Hi hest Value in an Array


int count; int 'ig'est; 'ig'est = numbers[0]; ,or -count = 1; count # SIZE; count%%. 3 i, -numbers[count] $ 'ig'est. 'ig'est = numbers[count]; 5

>hen this code is finished/ the 'ig'est variable $ill contains the hi hest value in the numbers array.

Copyright 2012 Pearson Education, Inc.

?indin the "o$est Value in an Array


int count; int lo9est; lo9est = numbers[0]; ,or -count = 1; count # SIZE; count%%. 3 i, -numbers[count] # lo9est. lo9est = numbers[count]; 5

>hen this code is finished/ the lo9est variable $ill contains the lo$est value in the numbers array.

Copyright 2012 Pearson Education, Inc.

@artially!?illed Arrays
%f it is un9no$n ho$ much data an array $ill be holdin :
* Ma9e the array lar e enou h to hold the lar est e,pected number of elements. * 7se a counter variable to 9eep trac9 of the number of items stored in the array.

Copyright 2012 Pearson Education, Inc.

6omparin Arrays
#o compare t$o arrays/ you must compare element!by!element:
const int SIZE = 5; int ,irst(rra1[SIZE] = 3 5, 10, 15, 20, 25 5; int second(rra1[SIZE] = 3 5, 10, 15, 20, 25 5; bool arra1sE7ual = true; && Alag @ariable int count = 0; && BooC counter @ariable && DomCare t'e t9o arra1s2 9'ile -arra1sE7ual EE count # SIZE. 3 i, -,irst(rra1[count] F= second(rra1[count]. arra1sE7ual = ,alse; count%%; 5 i, -arra1sE7ual. cout ## >/'e arra1s are e7ual2Gn>; else cout ## >/'e arra1s are not e7ual2Gn>;
Copyright 2012 Pearson Education, Inc.

7.D
7sin @arallel Arrays

Copyright 2012 Pearson Education, Inc.

7sin @arallel Arrays


@arallel arrays: t$o or more arrays that contain related data A subscript is used to relate arrays: elements at same subscript are related Arrays may be of different types

Copyright 2012 Pearson Education, Inc.

@arallel Array +,ample


const int SIZE = 5; && (rra1 si8e int id[SIZE]; && student IH double a@erage[SIZE]; && course a@erage c'ar grade[SIZE]; && course grade 222 ,or-int i = 0; i # SIZE; i%%. 3 cout ## >Student IH6 > ## id[i] ## > a@erage6 > ## a@erage[i] ## > grade6 > ## grade[i] ## endl; 5
Copyright 2012 Pearson Education, Inc.

(Program Continues)
Copyright 2012 Pearson Education, Inc.

@ro ram 7!1- (Continued)

Copyright 2012 Pearson Education, Inc.

#he 'ours and Ca1)ate arrays are related throu h their subscripts:

Copyright 2012 Pearson Education, Inc.

7.7
Arrays as ?unction Ar uments

Copyright 2012 Pearson Education, Inc.

Arrays as ?unction Ar uments


#o pass an array to a function/ just use the array name: #o define a function that ta9es an array parameter/ use empty [] for array ar ument:
@oid s'o9Scores-int [].; && ,unction Crotot1Ce @oid s'o9Scores-int tests[]. && ,unction 'eader s'o9Scores-tests.;

Copyright 2012 Pearson Education, Inc.

Arrays as ?unction Ar uments


>hen passin an array to a function/ it is common to pass array si&e so that function 9no$s ho$ many elements to process: Array si&e must also be reflected in prototype/ header:
@oid s'o9Scores-int [], int.; && ,unction Crotot1Ce @oid s'o9Scores-int tests[], int si8e. && ,unction 'eader s'o9Scores-tests, ())(*+SIZE.;

7!01
Copyright 2012 Pearson Education, Inc.

(Program Continues)
Copyright 2012 Pearson Education, Inc.

@ro ram 7!10 (Continued)

Copyright 2012 Pearson Education, Inc.

Modifyin Arrays in ?unctions


Array names in functions are li9e reference variables * chan es made to array in a function are reflected in actual array in callin function 3eed to e,ercise caution that array is not inadvertently chan ed by a function

Copyright 2012 Pearson Education, Inc.

7.1
#$o!Dimensional Arrays

Copyright 2012 Pearson Education, Inc.

#$o!Dimensional Arrays
6an define one array for multiple sets of data "i9e a table in a spreadsheet 7se t$o si&e declarators in definition:
const int )I:S = , DIBS = 3; int eJams[)I:S][DIBS];

?irst declarator is number of ro$sF second is number of columns


Copyright 2012 Pearson Education, Inc.

#$o!Dimensional Array Gepresentation


const int )I:S = , DIBS = 3; int eJams[)I:S][DIBS];
columns
eJams[0][0] eJams[0][1] eJams[1][1] eJams[2][1] eJams[0][2] eJams[1][2] eJams[2][2]

r o $ s

eJams[1][0] e

7se t$o subscripts to access element:


eJams[2][2] = 4K;

Copyright 2012 Pearson Education, Inc.

Copyright 2012 Pearson Education, Inc.

Copyright 2012 Pearson Education, Inc.

7!A7
Copyright 2012 Pearson Education, Inc.

-D Array %nitiali&ation
#$o!dimensional arrays are initiali&ed ro$!by!ro$:
const int )I:S = 2, DIBS = 2; int eJams[)I:S][DIBS] = 3 34 , !45, 3"2, "!5 5;
4 !4 "! "2

6an omit inner 3 5/ some initial values in a ro$ * array elements $ithout initial values $ill be set to 0 or =LBB
Copyright 2012 Pearson Education, Inc.

#$o!Dimensional Array as @arameter/ Ar ument


7se array name as ar ument in function call:
getEJams-eJams, 2.;

7se empty [] for ro$/ si&e declarator for column in prototype/ header: const int DIBS = 2; && Mrotot1Ce @oid getEJams-int [][DIBS], int.; && ?eader @oid getEJams-int eJams[][DIBS], int ro9s.

Copyright 2012 Pearson Education, Inc.

+,ample * #he s'o9(rra1 ?unction from @ro ram 7!18

Copyright 2012 Pearson Education, Inc.

Ho$ s'o9(rra1 is 6alled

Copyright 2012 Pearson Education, Inc.

2ummin All the +lements in a #$o!Dimensional Array


:iven the follo$in definitions:
const int =LN+)I:S = 5; && =umber o, ro9s const int =LN+DIBS = 5; && =umber o, columns int total = 0; && (ccumulator int numbers[=LN+)I:S][=LN+DIBS] = 332, !, ", K, 5, 3K, 1, 4, ", 5, 3 , 3, !, 2, "5, 3", ", 0, 3, 15, 3K, 2, !, , 155;

Copyright 2012 Pearson Education, Inc.

2ummin All the +lements in a #$o!Dimensional Array


&& Sum t'e arra1 elements2 ,or -int ro9 = 0; ro9 # =LN+)I:S; ro9%%. 3 ,or -int col = 0; col # =LN+DIBS; col%%. total %= numbers[ro9][col]; 5 && HisCla1 t'e sum2 cout ## >/'e total is > ## total ## endl;

Copyright 2012 Pearson Education, Inc.

2ummin the Go$s of a #$o!Dimensional Array


:iven the follo$in definitions:
const int =LN+S/LHE=/S = 3; const int =LN+SDI)ES = 5; double total; && (ccumulator double a@erage; && /o 'old a@erage scores double scores[=LN+S/LHE=/S][=LN+SDI)ES] = 3344, "!, !", 4K, " 5, 34K, "1, !4, !", 4 5, 342, !3, !!, 42, 4"55;

Copyright 2012 Pearson Education, Inc.

2ummin the Go$s of a #$o!Dimensional Array && Oet eac' student;s a@erage score2
,or -int ro9 = 0; ro9 # =LN+S/LHE=/S; ro9%%. 3 && Set t'e accumulator2 total = 0; && Sum a ro92 ,or -int col = 0; col # =LN+SDI)ES; col%%. total %= scores[ro9][col]; && Oet t'e a@erage a@erage = total & =LN+SDI)ES; && HisCla1 t'e a@erage2 cout ## >Score a@erage ,or student > ## -ro9 % 1. ## > is > ## a@erage ##endl; 5
Copyright 2012 Pearson Education, Inc.

2ummin the 6olumns of a #$o!Dimensional Array


:iven the follo$in definitions:
const int =LN+S/LHE=/S = 3; const int =LN+SDI)ES = 5; double total; && (ccumulator double a@erage; && /o 'old a@erage scores double scores[=LN+S/LHE=/S][=LN+SDI)ES] = 3344, "!, !", 4K, " 5, 34K, "1, !4, !", 4 5, 342, !3, !!, 42, 4"55;

Copyright 2012 Pearson Education, Inc.

2ummin the 6olumns of a #$o!Dimensional Array


&& Oet t'e class a@erage ,or eac' score2 ,or -int col = 0; col # =LN+SDI)ES; col%%. 3 && )eset t'e accumulator2 total = 0; && Sum a column ,or -int ro9 = 0; ro9 # =LN+S/LHE=/S; ro9%%. total %= scores[ro9][col]; && Oet t'e a@erage a@erage = total & =LN+S/LHE=/S; && HisCla1 t'e class a@erage2 cout ## >Dlass a@erage ,or test > ## -col % 1. ## > is > ## a@erage ## endl; 5
Copyright 2012 Pearson Education, Inc.

7.8
Arrays $ith #hree or More Dimensions

Copyright 2012 Pearson Education, Inc.

Arrays $ith #hree or More Dimensions


6an define arrays $ith any number of dimensions:
s'ort rectSolid[2][3][5]; double timeOrid[3][ ][3][ ];

>hen used as parameter/ specify all but 1st dimension in prototype/ headin :
@oid get)ectSolid-s'ort [][3][5].;

Copyright 2012 Pearson Education, Inc.

7.11
%ntroduction to the 2#" @ector

Copyright 2012 Pearson Education, Inc.

%ntroduction to the 2#" @ector


A data type defined in the 2tandard #emplate "ibrary 'covered more in 6hapter 1D( 6an hold values of any type:
@ector#int$ scores;

Automatically adds space as more is needed * no need to determine si&e at definition 6an use [] to access elements
Copyright 2012 Pearson Education, Inc.

Declarin Vectors
Eou must Pinclude#@ector$ Declare a vector to hold int element:
@ector#int$ scores;

Declare a vector $ith initial si&e ;.:


@ector#int$ scores-30.;

Declare a vector and initiali&e all elements to .:


@ector#int$ scores-30, 0.;

Declare a vector initiali&ed to si&e and contents of another vector:


@ector#int$ ,inals-scores.;
Copyright 2012 Pearson Education, Inc.

Addin +lements to a Vector


7se Cus'+bac< member function to add element to a full array or to an array that had no defined si&e:
scores2Cus'+bac<-!5.;

7se si8e member function to determine si&e of a vector:


'o9big = scores2si8e-.;

Copyright 2012 Pearson Education, Inc.

Gemovin Vector +lements


7se CoC+bac< member function to remove last element from vector:
scores2CoC+bac<-.;

#o remove all contents of vector/ use clear member function:


scores2clear-.;

#o determine if vector is empty/ use emCt1 member function:


9'ile -Fscores2emCt1-.. 222

Copyright 2012 Pearson Education, Inc.

Cther 7seful Member ?unctions


Member ?unction
at-elt. caCacit1-. re@erse-. resi8e -elts,@al. s9aC-@ec2.

Description
Geturns the value of the element at position elt in the vector

+,ample
cout ## @ec12at-i.;

maJelts = Geturns the ma,imum number of elements a vector can store $ithout @ec12caCacit1-.; allocatin more memory Geverse the order of the elements @ec12re@erse-.; in a vector Add elements to a vector/ optionally initiali&es them +,chan e the contents of t$o vectors @ec12resi8e-5,0.; @ec12s9aC-@ec2.;

Copyright 2012 Pearson Education, Inc.

You might also like