You are on page 1of 9

2

Arrays
Structuresofrelateddataitems
Structures of related data items
Staticentity(samesizethroughoutprogram)
Consecutivegroupofmemorylocations
Samenameandtype(int,char,etc.)
Same name and type (int char etc )

261102
Computer Programming
Lecture8:Arrays

Declaring Arrays
type arrayName[ arraySize ];

Whendeclaringarrays,specify
Name
Typeofarray
yp
y anydatatype
y
yp
Numberofelements

Declaring Arrays
Global/Localscopeconceptsisappliedjust
like normalvariables
Storageclasses(auto,
Storage classes (a to register
register,
static, extern ) canalsobeusedas
sameasnormalvariables

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

Declaringmultiplearraysofsametype
Declaring multiple arrays of same type
Usecommaseparatedlist,likeregularvariables
int b[100], x[27];

static int c[10];


extern int a[];

Access ElementofArray
Element of Array

Initializing arrays
arrays
Forloop
F l

arrayName[ index ];

Seteachelement

Initializer list

Torefertoanelement
To refer to an element

Specifyeachelementwhenarraydeclared
Specify each element when array declared
int n[5] = { 1, 2, 3, 4, 5 };
Ifnotenoughinitializers,rightmostelements0
If t
h i iti li
i ht
t l
t 0
Iftoomanysyntaxerror

Specifyarraynameandindex(positionnumber)
Firstelementatposition0

Nelementarrayc
N element array c

Ifarraysizeomitted,initializers determinesize

c[0],c[1] c[n - 1]

int n[]
[] = { 1,
, 2,
, 3,
, 4,
, 5 }
};

Nthh elementaspositionN1

5initializers,therefore5elementarray

Access ElementofArray
Element of Array

Arrays

Arrayelementslikeothervariables
Assignment,printingforanintegerarrayc
c[0]
[0] = 3;
3
cout << c[0];

Canperformoperationsinsidesubscript
c[5 2] sameasc[3]
same as c[3]

Name of array
(Note that all elements of
thi array have
this
h
th same name, c)
the
)

c[0]

-45

c[1]

c[2]

c[3]

72

c[4]

1543

c[5]

-89

c[6]
[6]

c[7]

62

c[8]

-3

c[9]

c[10]

6453

c[11]

78

output sizeofelement=4
sizeofarray=48
sum=8078

Position number of the


element
l
within
i hi array c

Arrays

10

Arrays
arraya=5.50000
arrayb=5550000000
arrayc=567
arrayd=000000000
d 000000000
Maybeillegalinsome
complier here arra si e
complierwherearraysize
mustbespecifiedwith
constantvariable(const)
Youmayusevector
insteadofarray

11

Character Arrays
Arrays (cstylestring)
( t l ti )
Arraysofcharacters=Strings
Allstringsendwithnull
All t i
d ith ll ('\0')
Examples
p
char string1[] = "hello";
Null characterimplicitlyadded
string1 has6elements

char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 };

Subscriptingisthesame
string1[
g
0 ] is'h'
string1[ 2 ] is'l'

12

Character Arrays
Arrays (cstylestring)
( t l ti )

13

String Arrays (arrayofc++ stringobjects )


StringArrays

14

Passing Arrays to Functions


PassingArraystoFunctions
Specifynamewithoutbrackets
Specify name without brackets
TopassarraymyArray tomyFunction
int myArray[24];
myFunction( myArray, 24 );

output

Arraysize usuallypassed,butnotrequired

InW
KAK
NOOB

Usefultoiterateoverallelements
f l
ll l

15

Passing Arrays to Functions


PassingArraystoFunctions
Arrayspassedbyreference
Arrays passed by reference
Functionscanmodifyoriginalarraydata
Valueofnameofarrayisaddressoffirst
element
Functionknowswherethearrayisstored
Canchangeoriginalmemorylocations
C
h
i i l
l
i

Individualarrayy elementspassedbyvalue
p
y
Likeregularvariables
square( myArray[3] );

16

Passing Arrays to Functions


PassingArraystoFunctions
Functionstakingarrays
Functions taking arrays
Functionprototype
void modifyArray( int b[], int arraySize );
void modifyArray( int [], int );
Namesoptionalinprototype
i
li
Bothtakeanintegerarrayandasingleinteger

Noneedforarraysizebetweenbrackets
N
df
i b t
b k t
Ignoredbycompiler

Ifdeclarearrayparameterasconst
Cannotbemodified(compilererror)
Cannot be modified (compiler error)
void doNotModify( const int [] );

17

Passed by reference
Passedbyreference
NormalVariable
Prototype

18

Passing Arrays to Functions


PassingArraystoFunctions
Array

int func(int &);

int func(int[]);

int func(int &x){

int func(int A[]){

func(x)

func(A)

Prototype
Thisinputparameterisanarrayofdouble

FunctionCall

Definition
Calling

Passbyreference

D fi iti
Definition

Passbyvalue

If
Ifconst
t keywordisusedtoparameter(s)ofthefunctionwhenitdeclared
k
di
dt
t ( ) f th f ti
h it d l d
int func(const int[]);

Range of data = 20 15
Rangeofdata=20.15

thenthefunctioncantmodifythatparameteralthoughitpassedbyreference

19

Passing Arrays to Functions


PassingArraystoFunctions

20

Passing Arrays to Functions


PassingArraystoFunctions

new data = 6 1 2 8 1 85
newdata=6.12.81.85

22

Passing Array Elements toFunctions


PassingArrayElements
to Functions

Example 8A:
Example8
A: AddingTwoArrays
Adding Two Arrays

Donotallowfunctiontomodifysrc1 andsrc2

Allowfunctiontomodifydest

result = 0 7 10 3 9 7
result=0.710.39.7

23

MultipleSubscripted
Multiple
SubscriptedArrays
Arrays
Multiplesubscripts(Multidimensionalarrays)
Multiple subscripts (Multidimensional arrays)

a[ i ][ j ]
T bl
Tableswithrowsandcolumns
ith
d l
Specifyrow,thencolumn
Arrayofarrays

24

MultipleSubscripted
Multiple
SubscriptedArrays
Arrays
Toinitialize
To initialize
Defaultof0
Initializers groupedbyrowinbraces
int b[ 2 ][ 2 ] = { { 1,
1 2 },
} { 3,
3 4 } };
Row 0

Row 1

a[0] isanarrayof4elements
a[0][0] isthefirstelementofthatarray
Column 0

Column 1
a[ 0 ][ 1 ]

Column 2
a[ 0 ][ 2 ]

Column 3

Row 0

a[ 0 ][ 0 ]

a[ 0 ][ 3 ]

Row 1

a[ 1 ][ 0 ]

a[ 1 ][ 1 ]

a[ 1 ][ 2 ]

a[ 1 ][ 3 ]

R
Row
2

a[ 2 ][ 0 ]

a[ 2 ][ 1 ]

a[ 2 ][ 2 ]

a[ 2 ][ 3 ]

Column subscript
Array name
Row subscript

a[0]

i t b[ 2 ][ 2 ] = { { 1 },
int
} { 3,
3 4 } }
};

25

MultipleSubscripted
Multiple
SubscriptedArrays
Arrays

26

MultipleSubscripted
Multiple
SubscriptedArrays
Arrays

Referencedlikenormal
Referenced like normal
cout << b[ 0 ][ 1 ];

Outputs0
Cannotreferenceusingcommas
Cannot reference using commas
cout << b[ 0, 1 ];

Syntaxerror
Syntax error

Functionprototypes
Mustspecifysizesofsubscripts
First
Firstsubscriptnotnecessary,aswithsinglescripted
subscript not necessary as with singlescripted
arrays

void printArray( int [][ 3 ] );


27

MultipleSubscripted
Multiple
SubscriptedArrays
Arrays
Initializer Lists

Results

int A[2][4] = {{1,2,3,4}};

1234
0000

int A[2][4] = {1,2,3,4,5,6};

1234
5600

int A[2][4] = {1};

1000
0000

int A[2][4] = {{1},{2}};

1000
2000

int A[2][4] = {{},{2,3}};

0000
2300

int A[2][4] = {};

0000
0000

[ ][ ] = {1,2,3,4,5,6,7,8,9};
{ , , , , , , , , };
int A[2][4]

too manyy
initializers

28

Example 8B:
Example8
B: Determinant(2x2)
Determinant (2x2)
a b ad bc
c d
IInputFirstRow:12
t Fi t R 1 2
InputSecondRow:34
Determinant = 2
Determinant=2

29

Example 8C:
Example8
C:ScoreTable
Score Table

30

Example 8C:
Example8
C:ScoreTable
Score Table

31

Vectors

32

Vectors

Vectors
Vectors=sequencecontainersrepresentingarrays
= sequence containers representing arrays
thatcanchangeinsizedynamically
#include<vector>
Declaringavector:
std::vector< type > vectorName(vectorSize);
std::vector< type > vectorName;
Referringtoanelement:
Referring to an element:
vectorName[ index ]
vectorName.at( index )

Addinganelementtoavector:
Adding an element to a vector :
vectorName.push
p
_back( value);
(addnewelementtotheendofvector)

vectorName.insert( position,value);
(usevectorName.begin() toobtainpositionofthe1st element)

Removingelement(s)ofavector:
p p_
vectorName.pop_back();
(removesthelastelementinthe vector)

vectorName.erase( position);
vectorName.erase( firstPosition,lastPosition );
vectorName.clear();
(removesallelementsfromthe vector)

33

Vectors

34

Vectors

Changingvalueofanelementofavector:
Changing value of an element of a vector :
vectorName[ index] = newValue;
vectorName.at( index) = newValue;

0 0 0 1 10 100
69 0 60 1 10 100

Vectorcanbereturnfromafunction:
vector<type> func(paramenter_list);

Passavectortoafunction:
ByValue

ByReference

yp func(vector<type>);
(
yp );
Prototype
ototype type

type
yp func(vector<type>
(
yp
&);
);

type func(vector<type> v);

type func(vector<type> &v);

func(v)

func(v)

Definition
Calling

35

Vectors

36

Vectors

Passedbyvalue

9 4 49

69 69 69 69 69 69 69

Returnvector
Passed by reference
Passedbyreference

You might also like