Sie sind auf Seite 1von 7

Asdiscussedinthepreviouspost,therearetwotypesofdatastructuresavailabletoC/C++

programmers.Oneisalreadybuiltintotheprogramminglanguageandotheroneisabitcomplexina
sensethatitcanbeimplementedusingthebuiltindatastructuresanddatatypes.InC/C++
programminglanguage,builtindatastructuresincludeArrays,structures,unionsandclasses.Someof
theexamplesofcomplexdatastructuresareStack,Queue,LinkedList,TreeandGraph.
Theaimofthisfirsttutorialsistoteachyouhowtodeclare,initialiseandusesimplearraysaswellas
multidimensionalarrays.YouwillalsobeabletousearraysasdatastructureinyourC/C++program.
Soattheendofthistutorialyouwillbeabletoanswer:

Whatisanarrayandhowyoucanuseit?

Howtodeclareandinitialisesimplearrays?

Howtodeclareandinitialisemultidimensionalarrays?

Howtoperformsimpleoperationsonarrays?

Whatisanarray?
Arrayisaverybasicdatastructureprovidedbyeveryprogramminglanguage.Letstalkaboutan
examplescenariowhereweneedtostoretenemployeesdatainourC/C++programincludingname,
ageandsalary.Oneofthesolutionsistodeclaretendifferentvariablestostoreemployeenameandten
moretostoreageandsoon.Alsoyouwillneedsomesortofmechanismtogetinformationaboutan
employee,searchemployeerecordsandsortthem.TosolvethesetypesofproblemC/C++providea
mechanismcalledArrays.

Definition
Anarrayissimplyanumberofmemorylocations,eachofwhichcanstoreanitemofdataofthesame
datatypeandwhichareallreferencedthroughthesamevariablename.IvorHorton.
Arraymaybedefinedabstractlyasfiniteordersetofhomogeneouselements.Sowecansaythatthere
arefinitenumbersofelementsinanarrayandalltheelementsareofsamedatatype.Alsoarray
elementsareorderedi.e.wecanaccessaspecificarrayelementbyanindex.

Howtodeclareanarray?
Thegeneralformofdeclaringasimple(onedimensional)arrayis

array_typevariable_name[array_size];

inyourC/C++programyoucandeclareanarraylike

intAge[10];

Herearray_typedeclaresbasetypeofarraywhichisthetypeofeachelementinarray.Inourexample
array_typeisintanditsnameisAge.Sizeofthearrayisdefinedbyarray_sizei.e.10.Wecanaccess
arrayelementsbyindex,andfirstiteminarrayisatindex0.Firstelementofarrayiscalledlower
boundanditsalways0.Highestelementinarrayiscalledupperbound.
InCprogramminglanguageupperandlowerboundscannotbechangedduringtheexecutionofthe
program,soarraylengthcanbesetonlywhentheprograminwritten.

Age0

Age1

Age2

Age3

Age4

Age5

Age6

Age7

30

32

54

32

26

29

23

43

Arrayhas10elements
Note:Onegoodpracticeistodeclarearraylengthasaconstantidentifier.Thiswillminimisethe
requiredworktochangethearraysizeduringprogramdevelopment.
Consideringthearraywedeclaredabovewecandeclareitlike

#defineNUM_EMPLOYEE10
intAge[NUM_EMPLOYEE];

1
2

Howtoinitialiseanarray?
Initialisationofarrayisverysimpleincprogramming.Therearetwowaysyoucaninitialisearrays.

Declareandinitialisearrayinonestatement.

Declareandinitialisearrayseparately.

LookatthefollowingCcodewhichdemonstratesthedeclarationandinitialisationofanarray.

1
2
3
4
5
6
7

intAge[5]={30,22,33,44,25};
intAge[5];
Age[0]=30;
Age[1]=22;
Age[2]=33;
Age[3]=44;
Age[4]=25;

Arraycanalsobeinitialisedinawaysthatarraysizeisomitted,insuchcasecompilerautomatically
allocatesmemorytoarray.

intAge[]={30,22,33,44,25};

Letswriteasimpleprogramthatusesarraystoprintoutnumberofemployeeshavingsalarymore
than3000.

ArrayinCProgramming

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

#include<windows.h>
#include<stdio.h>
#include<stdlib.h>
#defineNUM_EMPLOYEE10

intmain(intargc,char*argv[]){
intSalary[NUM_EMPLOYEE],lCount=0,gCount=0,i=0;
printf("Enteremployeesalary(Max10)\n");
for(i=0;i<NUM_EMPLOYEE;i++){
printf("\nEnteremployeesalary:%d",i+1);
scanf("%d",&Salary[i]);
}

for(i=0;i<NUM_EMPLOYEE;i++){
if(Salary[i]<3000)
lCount++;
else
gCount++;
}

printf("\nThereare{%d}employeewithsalarymorethan3000\n",gCount);
printf("Thereare{%d}employeewithsalarylessthan3000\n",lCount);
printf("PressENTERtocontinue...\n");
getchar();
return0;
}

ArrayinC++Programming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include<cstdlib>
#include<iostream>
#defineNUM_EMPLOYEE10

usingnamespacestd;

intmain(intargc,char*argv[]){
intSalary[NUM_EMPLOYEE],lCount=0,gCount=0,i=0;
cout<<"Enteremployeesalary(Max10)"<<endl;
for(i=0;i<NUM_EMPLOYEE;i++){
cout<<"Enteremployeesalary:"<<i+1<<endl;
cin>>Salary[i];
}

for(i=0;i<NUM_EMPLOYEE;i++){
if(Salary[i]<3000)
lCount++;
else

19
20
21
22
23
24
25
26
27

gCount++;
}

cout<<"Thereare"<<gCount<<"employeewithsalarymorethan3000"
<<endl
<<"Thereare"<<lCount<<"employeewithsalarylessthan3000"<<endl;

system("PAUSE");
returnEXIT_SUCCESS;
}

Howtodeclareandinitialisemultidimensional
arrays?
Oftenthereisneedtomanipulatetabulardataormatrices.Forexampleifemployeesalaryisincreased
by20%andyouarerequiredtostoreboththesalariesinyourprogram.Thenyouwillneedtostorethis
informationintoatwodimensionalarrays.C/C++givesyoutheabilitytohavearraysofany
dimension.

Multidimensionarrays
Considertheexampleabove,youhavetostore,previoussalary,presentsalaryandamountof
increment.Inthatcaseyouwillneedtostorethisinformationinthreedimensionalarrays.
FirstIwillshowyouhowtodeclareatwodimensionalarrayandinitialiseit.Thenwriteacomplete
programtousemultidimensionalarrays.

intSalary[10][2];

Thisdefinesanarraycontaining10elementsoftypeint.Eachoftheseelementsitselfisanarrayoftwo
integers.Sotokeeptrackofeachelementofthisarrayiswehavetousetwoindices.Oneistokeep
trackofrowandotheristokeeptrackofcolumn.

Elementsofmultidimensionalarrays
Hereisagraphicalviewofmultidimensionalarraythatweusetostoresalaryandincrementonsalary.
Firstcolumnstoresthesalaryelementofthearrayandsecondcolumnstoresincrementonsalary.We
couldaddanothercolumntostorethenewsalarywhichaddstheincrementtothesalary.

Column0Salary Column1Increment
Row0
Row2
Row3
Row4
Row5
Row6

Row7
Row8
Row9
Row10

Initialisingmultidimensionalarrays
Multidimensionalarrayscanalsobeinitialisedintwowaysjustlikeonedimensionalarray.Twobraces
areusedtosurroundtherowelementofarrays.
Ifyouareinitialisingmorethanonedimensionthenyouwillhavetouseasmanybracesasthe
dimensionsofthearrayare.

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

intSalary[5][2]={
{2300,460},
{3400,680},
{3200,640},
{1200,240},
{3450,690}
};

intSalary[5][2]={0};//Thiswillinitialiseallthearrayelementsto0

intSalary[5][2];
Salary[0][0]=2300;
Salary[1][0]=3400;
Salary[2][0]=3200;
Salary[3][0]=1200;
Salary[4][0]=3450;
Salary[0][1]=460;
Salary[1][1]=680;
Salary[2][1]=640;
Salary[3][1]=240;
Salary[4][1]=690;

HereisacompleteprogramwritteninbothCandC++todemonstratetheuseofmultidimensional
arrays.Youcanfindthewholesourcecodeinazipfileattheendofthetutorial.Sourcecodeis
availableinbothCandC++programminglanguages.Zipfilealsocontainsthedemonstrationofthree
dimensionalarrays.

Demonstrationoftwodimensionarrays
Thecodebelowdemonstratestwodimensionarrays.Itusesthesameexampleofemployeesalaryto
incrementitby20%andaddsittoactualsalarythenprintcurrentsalary,incrementandnewsalary.

TwodimensionalArrayinCProgramming

#include<windows.h>

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

#include<stdio.h>
#include<stdlib.h>
#defineNUM_EMPLOYEE10
intmain(intargc,char*argv[]){
//initialiseSalaryofeachemployee
intSalary[NUM_EMPLOYEE][2]={
{2300,0},
{3400,0},
{3200,0},
{1200,0},
{3450,0},
{3800,0},
{3900,0},
{2680,0},
{3340,0},
{3000,0}
};
intlCount=0,gCount=0,i=0;
for(i=0;i<NUM_EMPLOYEE;i++){
Salary[i][1]=((Salary[i][0]*20)/100);
}
printf("InitialSalary+Increment=TotalSalary\n");
for(i=0;i<NUM_EMPLOYEE;i++){
printf("%d\t\t%d\t\t%d\n",Salary[i][0],Salary[i][1],Salary[i][0]+Salary[i][1]);
}

printf("PressENTERtocontinue...\n");
getchar();
return0;
}

TwodimensionalarrayinC++Programming

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

#include<cstdlib>
#include<iostream>
#defineNUM_EMPLOYEE10
usingnamespacestd;

intmain(intargc,char*argv[]){
//initialiseSalaryofeachemployee
intSalary[NUM_EMPLOYEE][2]={
{2300,0},
{3400,0},
{3200,0},
{1200,0},
{3450,0},
{3800,0},
{3900,0},
{2680,0},
{3340,0},
{3000,0}
};
intlCount=0,gCount=0,i=0;
for(i=0;i<NUM_EMPLOYEE;i++){

22
23
24
25
26
27
28
29
30
31

Salary[i][1]=((Salary[i][0]*20)/100);
}
cout<<"InitialSalary+Increment=TotalSalary"<<endl;
for(i=0;i<NUM_EMPLOYEE;i++){
printf("%d\t\t%d\t\t%d\n",Salary[i][0],Salary[i][1],Salary[i][0]+Salary[i][1]);
}

system("PAUSE");
returnEXIT_SUCCESS;
}

Das könnte Ihnen auch gefallen