You are on page 1of 10

12/7/2009

CCE1110 ComputerProgramming http://cce1110.ictnode.com

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Arrays y DefiningArrays ArrayExamples PassingArraystoFunctions SortingArrays CaseStudy:ComputingMean,Medianand CaseStudy:ComputingMean Medianand ModeUsingArrays SearchingArrays MultipleSubscriptedArrays
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 2

UniversityofMalta Oct2009

12/7/2009

Array
Groupofconsecutivememorylocations Samenameandtype

Torefertoanelement,specify
Arrayname(cannotbeginwithadigit) Positionnumber

Format:
arrayname[ positionnumber ]

Firstelementatposition0
n elementarraynamedc: c[ 0 ], c[ 1 ]...c[ n 1 ]

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

12/7/2009

Whendefiningarrays,specify
Name Typeofarray Numberofelements
arrayType arrayName[ numberOfElements ];

Examples:
int c[ 10 ]; float myArray[ 3284 ];

Definingmultiplearraysofsametype
Formatsimilartoregularvariables Example:
int b[ 100 ], x[ 27 ];

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

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

Ifnotenoughinitializers,rightmostelementsbecome0
int n[ 5 ] = { 0 }

Allelements0

Iftoomanyinitializers,asyntaxerroroccurs Carrayshavenoboundschecking y g

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

5initializers,therefore5elementarray

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

12/7/2009

Characterarrays
Stringfirst isreallyastaticarrayofcharacters ll f h Characterarrayscanbeinitializedusingstringliterals
char string1[] = "first";

Nullcharacter'\0' terminatesstrings string1 actuallyhas6elements Itisequivalentto


char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };

Canaccessindividualcharacters
string1[ 3 ] is character s

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Arraynameisaddressofarray,so&notneededforscanf
scanf( "% " string2 ) f( "%s", t i 2 );

Readscharactersuntilwhitespaceencountered Becarefulnottowritepastendofarray,asitispossibletodoso

Canusespecifier tolimitnumberofcharactersaccepted byscanf()


charstring2[20]; scanf(%19s,string2);

Thisforbidsscanf towritecharactersbeyondtheendof thearray

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

12/7/2009

Passingarrays
Topassanarrayargumenttoafunction,specifythenameofthearray f f h f h

withoutanybrackets
int myArray[ 24 ]; myFunction( myArray, 24 );

Arraysizeusuallypassedtofunction Arrayspassedcallbyreference Nameofarrayisaddressoffirstelement Functionknowswherethearrayisstored Modifiesoriginalmemorylocations

Passingarrayelements
Passedbycallbyvalue Passsubscriptedname(i.e.,myArray[ 3 ]) tofunction

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Functionprototype p yp
void modifyArray( int b[], int arraySize );

Parameternamesoptionalinprototype int b[] couldbewrittenint [] int arraySize couldbesimplyint

Anarraynameisreallytheaddressofthefirst elementofanarray
myarray,&myarray[0],&myarray Pointtothesamememorylocation

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

10

12/7/2009

1 2 3 4 5 6 7 8 9 10 11 12 13

/* Fig. 6.12: fig06_12.c The name of an array is the same as &array[ 0 ] */ #include <stdio h> <stdio.h> /* function main begins program execution */ int main( void ) { char array[ 5 ]; /* define an array of size 5 */ printf( " array = %p\n&array[0] = %p\n array, &array[ 0 ], &array ); &array = %p\n",

return 0; /* indicates successful termination */

14 15 } /* end main */ array = 0012FF78 &array[0] = 0012FF78 &array = 0012FF78

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

11

Labexercise8
Deitle &Deitle
Page208Fig6.5
Initializeelementsofarraystotheevennumbers2,4,6,20

Page210Fig6.6
Computethesumoftheelementsofanarray

Page210Fig6.7
Studentpollprogram

Page212Fig6 8 Page212Fig6.8
Histogramprintingprogram

Page213Fig6.9
Rolla6sideddie6000times

Startingpage216Fig6.10,6.11,6.13,6.14,6.15,6.16,6.22
various
UniversityofMalta Oct2009 Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 12

12/7/2009

Sortingdata
Importantcomputingapplication Virtuallyeveryorganizationmustsortsomedata

Bubblesort(sinkingsort)
Severalpassesthroughthearray Successivepairsofelementsarecompared Ifincreasingorder(oridentical),nochange Ifdecreasingorder,elementsexchanged Repeat

Example:

original:34267 pass1:32467 pass2:23467 Smallelements"bubble"tothetop

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

13

Mean average g Median numberinmiddleofsortedlist


1,2,3,4,5 3isthemedian

Mode numberthatoccursmostoften
1,1,1,2,3,3,4,5 1isthemode

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

14

12/7/2009

y y Searchanarrayforakeyvalue Linearsearch
Simple Compareeachelementofarraywithkeyvalue Usefulforsmallandunsortedarrays

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

15

Binarysearch
Forsortedarraysonly Comparesmiddle elementwithkey
Ifequal,matchfound Ifkey < middle,looksinfirsthalfofarray Ifkey > middle,looksinlasthalf Repeat p

Veryfast;atmostnsteps,where2n >numberof

elements
30elementarraytakesatmost5steps
25 >30soatmost5steps
UniversityofMalta Oct2009 Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 16

12/7/2009

Multiplesubscriptedarrays Initialization
Tableswithrowsandcolumns(m byn array) Likematrices:specifyrow,thencolumn
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

Initializersgroupedbyrowinbraces Ifnotenough unspecifiedelementssettozero Ifnotenough,unspecifiedelementssettozero


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

Referencingelements
Specifyrow,thencolumn
printf( "%d", b[ 0 ][ 1 ] );

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

17

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

18

12/7/2009

y Arrays DefiningArrays ArrayExamples PassingArraystoFunctions SortingArrays CaseStudy:ComputingMean,Medianand CaseStudy:ComputingMean Medianand ModeUsingArrays SearchingArrays MultipleSubscriptedArrays
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 19

UniversityofMalta Oct2009

Discussion

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

20

10

You might also like