Uni T-I:Arrays: Ani NT R Oduct I Ont Oc++Cl Ass: Abst R Act I On
Uni T-I:Arrays: Ani NT R Oduct I Ont Oc++Cl Ass: Abst R Act I On
T-I
:ARRAYS
SYLLABUS:
AbstractDat aTy pesandt heC++Cl ass,AnIntroductiontoC++Cl ass-DataAbstr
acti
on
and
Encapsulationi nC++-Declari
ngClassObj ectsandInv oki
ngMemberFunct i
ons-Speci
al
Class
Operations-Mi scel
laneousTopics-ADTsandC++Cl asses,TheArrayasanAbst r
actData
Type,
ThePol ynomi alAbstractDataty
pe-Polynomi alRepresentati
on-PolynomialAddi
ti
on.
Spares
Mat r
ices,I
ntroduction-SparseMatri
xRepr esentat
ion-TransposingaMat ri
x-Matri
x
Multi
plicati
on, Representat
ionofArrays.
Abst
ractDat
aTy
pesandt
heC++Cl
ass
AnI
ntr
oduct
iont
oC++Cl
ass:
Abst
ract
ion
Abstracti
onrefer
st oshowingonl ytheessentialfeat
uresoftheappli
cati
onandhidi
ngthe
detai
ls.InC++,classescanpr ovi
demet hodst otheoutsideworldtoaccess&usethedat
a
vari
ables,keepi
ngt hevar
iableshiddenfrom directaccess,orcl
assescanevendecl
are
every
t hi
ngaccessibletoeveryone,ormay bejustt ot
heclassesinher
it
ingit
.Thi
scanbe
doneusi ngaccessspecifi
ers.
Encapsul
ati
on
I
tcanal sobesaiddatabinding.Encapsulat
ionisallaboutbi
ndingthedatavari
ablesand
funct
ionstogetherincl
ass.
C++Cl assDefini
ti
ons:
Classisusedtocr eat
eauserdef ineddatat
ypewher eobject
sar ei
t'
svari
ables.
objectsare
i
nstancesofclass.Aclassdefini
ti
onst ar
tswiththekeywordclassfol
lowedbyt heclass
name; andtheclassbody,enclosedbyapai rofcurl
ybraces.Aclassdefi
nit
ionmustbe
fol
lowedeitherbyasemi col
onoral i
stofdeclar
ati
ons.Forexample,wedefinedtheBox
datatypeusingthekeywordclassasf ol
l
ows−
cl
assBox{
publi
c:
doubl
elength;//Lengthofabox
doubl
ebreadth;//Breadt
hofabox
doubl
eheight;//Heightofabox
};
Thekey wordpublicdeterminestheaccessat
tri
butesofthemember soft
heclassthat
fol
lowsit.Apubl i
cmembercanbeaccessedf rom out
sidethecl
assanywher
ewi thi
nthe
scopeoft heclassobject.Youcanalsospeci
fythemember sofaclassaspr
ivateor
protect
edwhi chwewi lldiscussi
nasub-sect
ion.
Def
ineC++cl
assesandObj
ect
s
Aclasspr
ovi
desthebluepri
ntsf
orobject
s,sobasical
lyanobjectiscr
eatedfr
om acl
ass.
Wedeclar
eobject
sofacl asswi
thexactl
ythesamesor tofdeclar
ati
onthatwedecl
are
var
iabl
esofbasi
ctypes.Foll
owi
ngstatementsdeclar
etwoobj ect
sofclassBox−
BoxBox1; /
/Decl
areBox1oft
ypeBox
BoxBox2; /
/Decl
areBox2oft
ypeBox
Bot
hoft
heobj
ect
sBox1andBox2wi
l
lhav
ethei
rowncopyofdat
amember
s.
Accessi
ngt
heDat
aMember
s
Thepubli
cdatamembersofobject
sofaclasscanbeaccessedusingthedirectmember
accessoper
ator(
.)
.Letust
rythefol
lowi
ngexamplet
omaket het
hingsclear−
#i
ncl
ude<i
ost
ream>
usi
ngnamespacest
d;
cl
assBox{
publi
c:
doubl
elength;//Lengthofabox
doubl
ebreadth;//Breadt
hofabox
doubl
eheight;//Heightofabox
};
i
ntmain(
){
BoxBox1; //Decl
areBox1ofty
peBox
BoxBox2; //Decl
areBox2ofty
peBox
doubl
evol
ume=0.
0; / /St
oret
hev ol
umeofaboxher
e
//box1specif
icati
on
Box1.
height=5.0;
Box1.
length=6.0;
Box1.
breadth=7.0;
//box2specif
icati
on
Box2.
height=10.0;
Box2.
length=12.0;
Box2.
breadth=13.0;
//vol
umeofbox1
vol
ume=Box1.hei
ght*Box1.
length*Box1.
breadt
h;
cout<<"
Vol
umeofBox 1:"<<volume<<endl
;
//vol
umeofbox2
vol
ume=Box2.hei
ght*Box2.
length*Box2.
breadt
h;
cout<<"
Vol
umeofBox 2:"<<volume<<endl
;
ret
urn0;
}
Whent
heabov
ecodei
scompi
l
edandexecut
ed,
itpr
oducest
hef
oll
owi
ngr
esul
t−
Vol
umeofBox1:
210
Vol
umeofBox2:
1560
I
tisimpor
tantt
onotethatpr
ivat
eandprot
ect
edmemberscannotbeaccesseddir
ect
ly
usi
ngdir
ectmemberaccessoperat
or(
.)
.Wewi l
ll
ear
nhowpri
vateandprot
ected
memberscanbeaccessed.
Twoway st
odecl
areobj
ect
s:
Exampl
e:
classStudent
{
public:
i
ntr oll
no;
stri
ngname;
}A,B;
HereAandBaretheobjectsofclassStudent,decl
aredwiththeclassdef
init
ion.Wecan
al
sodecl
areobj
ectsseparatel
y,l
i
kewedecl ar
ev ar
iableofpri
miti
vedatat
y pes.Int
his
caset
hedataty
peistheclassname, andv ari
ablei
st heobject
.
i
ntmain()
{
StudentA;
StudentB;
}
Bot
hAandBwi
l
lhav
ethei
rowncopi
esofdat
amember
s.
AccessCont
rol
inCl
asses
Nowbef orestudy i
nghowt odefineclassanditsobj ects,l
et sfir
stquicklylear
nwhatare
accessspecifiers.
Accessspeci f
iersinC++classdef i
nestheaccesscont rolrules.C++has3newkey words
i
ntroduced,namel y,
1. publ i
c
2. pr ivate
3. pr otected
Theseaccessspeci f
ier
sareusedt osetboundariesf orav ai
labil
ityofmember sofcl
assbe
i
tdatamember sormemberf unctions
Accessspeci f
iersintheprogram,arefoll
owedbyacol on.Youcanuseei t
herone,twoor
al
l3speci f
iersinthesamecl asstosetdiffer
entboundar i
esf ordiff
erentclassmember s.
Theychanget heboundar yforallt
hedeclarat
ionst hatfoll
owt hem.
Publi
c
Publi
c,meansal lt
heclassmember sdecl
aredunderpubl i
cwi l
lbeavailabl
et oever
yone.
Thedatamember sandmemberf uncti
onsdeclar
edpubl iccanbeaccessedbyot her
cl
assest oo.Hencet herearechancesthattheymi ghtchanget hem.Sot hekeymember s
mustnotbedecl aredpubli
c.
cl
assPublicAccess
{
publi
c:/ /publi
caccessspeci
fi
er
intx; //DataMemberDeclarat
ion
voiddispl
ay();//MemberFunctiondecar
ati
on
}
Pri
v ate
Pri
vat ekeyword,
meanst hatnoonecanaccesst heclassmembersdeclar
edpri
vat
e
outsidethatcl
ass.Ifsomeonet riestoaccesst
hepr i
vatemember
,theywil
lgetacompi
l
e
ti
meer r
or.Bydefaul
tclassv ar
iablesandmemberf uncti
onsar
epri
vate.
cl
assPr i
vateAccess
{
privat
e:/ /pri
vateaccessspeci
fier
intx; //DataMemberDecl arat
ion
voiddispl
ay (
);//MemberFunct iondecar
ati
on
}
Pr
otected
Pr
otected,isthelastaccessspecifi
er,andi
tissi
mil
artopri
vat
e,i
tmakesclassmember
i
naccessibl
eout sidetheclass.Butt
heycanbeaccessedbyanysubcl
assofthatcl
ass.(
If
cl
assAi sinheri
tedbycl assB,thenclassBissubcl
assofcl
assA.Wewil
llearnt
hisl
ater
.)
cl
assPr otectedAccess
{
protected:/ /protect
edaccessspeci
fier
intx; /
/Dat aMemberDeclarati
on
voiddisplay(
) ;//MemberFunctiondecarat
ion
}
MemberFunct
ionsi
nCl
asses
Memberf uncti
onsar ethefuncti
ons,whichhav ethei
rdeclar
ationinsidetheclass
defini
ti
onandwor ksont hedatamember softheclass.Thedef i
nit
ionofmember
functi
onscanbei nsideoroutsi
det hedefini
ti
onofclass.
I
ft hememberf uncti
onisdefinedinsidetheclassdefi
nit
ionitcanbedef ineddirect
ly,buti
f
i
tsdef i
nedoutsi
det heclass,t
henwehav etouset hescoperesolution::
operatoralong
withclassnameal ngwithfuncti
onname.
Exampl
e:
cl
assCube
{
publi
c:
intsi
de;
intget
Volume(
); /
/Decl
ari
ngf
unct
ionget
Vol
umewi
thnoar
gumentandr
etur
nty
pei
nt.
};
I
fwedef i
nethefuncti
oninsi
decl
asst
henwedon'
tnotneedt
odecl
arei
tfi
rst
,wecan
di
rect
lydefi
nethefuncti
on.
cl
assCube
{
public:
intside;
intgetVolume()
{
ret
urnside*si
de*si
de; /
/ret
urnsv
olumeofcube
}
};
Buti
fweplantodefi
net
hememberfunct
ionout
sidet
heclassdefini
ti
ont
henwemust
decl
aret
hefunct
ioni
nsi
decl
assdef
ini
ti
onandthendefi
neitout
side.
cl
assCube
{
publi
c:
intsi
de;
intget
Volume(
);
}
i
ntCube:
:getVol
ume() /
/def
inedout
sidecl
assdef
ini
ti
on
{
ret
urnsi
de*
side*
side;
}
Themai
nef unct
ionforbot
hthefunct
iondef
ini
ti
onwil
lbesame.I
nsidemain(
)wewi
l
l
cr
eat
eobjectofclass,
andwil
lcall
thememberfunct
ionusi
ngdot.oper
ator.
i
ntmai n()
{
CubeC1;
C1.side=4;//set
ti
ngsidev
alue
cout<<"VolumeofcubeC1="<<C1.
get
Vol
ume(
);
}
Si
mil
arl
ywecandefi
nethegetterandset
terf
unct
ionst
oaccesspr
ivat
edat
amember
s,
i
nsi
deorout
sidet
heclassdef
init
ion.
Speci
alCl
assOper
ati
ons:Const
ruct
orandDest
ruct
or
Classescanhav ecomplicatedi nter
nal str
uctures,soobj ectini
ti
al i
zati
onandcl ean-upofa
classismuchmor ecompl icatedt henf oranyot herdat astr
uctures.Constructor sand
destructorsarespecialmemberf unctionsofcl assest hatareusedt oconstructand
destroyclassobjects.Theconst r
ucti
oncanbef orexampl e: i
nit
iali
zationf
orobj ect
sor
memor yall
ocati
on.Thedest r
uct i
onmayi nvolv
ede- al
locati
onofmemor yorot herclean-up
forobjects.
Const r
uctorsanddest r
uctor ’
sar edeclaredwi t
hinacl assdecl arati
on( asl
ikeanyot her
memberf uncti
on).Aconst ructororadest r
uctorcanbedef inedi n-
li
neorext ernal t
othe
classdeclarati
on.Wemaydecl aresomedef aultargument swhenwemakeaconst ructor.
Therear esomer estri
cti
onst hatappl ytoconst ructorsanddest ructors:
Constructor
sanddest ructorscannothav ear eturntype(notev envoid).
Pointersandr ef
erencescannotbeusedonconst r
uctorsanddestr
uctor’
s(Itisnot
possi
blet ogett her
eaddr ess)
Const r
uctorsanddest ructor’
scannotbedeclaredstati
c,constorvol
ati
le.
Const r
uctorscannotbedecl aredwiththekeywor
dv i
rtual
.
Note:thesameaccessr ulesappl ytoconstruct
orsanddestruct
orsaswithanyot her
memberf uncti
on.
Constructorsarecalledaut omaticall
ybyt hecompil
erwhendef i
ningcl
assobjects.The
destr
uctor’sarecalledwhenacl assobj ectgoesoutofscope.
Solet’
st akeal ookatanexampl e:
#i
ncl
ude<i
ost
ream>
usi
ngnamespacest
d;
cl
assCAdd
{
publ
i
c:
intone;
CAdd(
intt
wo)
{
cout<<"Aconst
ruct
ori
scal
l
ed"<<endl
;
one=two;
}
CAdd(
)
{
cout<<"
Adef
aul
tconst
ruct
ori
scal
l
ed"<<endl
;
}
~CAdd()
{
cout<<"
Dest
ruct
ing"<<one<<endl
;
}
i
ntadd()
{
ret
urn(
one+one)
;
}
}
;
i
ntmain(
)
{
CAddmy
obj
1(4)
;
CAddmy
obj
2;
cout<<myobj1.
one<<endl
;
cout<<"
Enteranumber:";
ci
n>>my obj
2.one;
cout<<myobj
2.add(
)<<endl
;
r
etur
n(0)
;
}
Note:withCAddmy obj
2;wedidnotuseanyparenthesesbecausewewanttocallt
he
def
aultconstr
uct
or.Putt
ingt
heparenthesesbehi
ndmy obj
2wil
lresul
tinaner
ror
.
Thestatement:
CAdd(i
ntt wo)
{
cout<<"Aconst
ruct
ori
scal
l
ed"<<endl
;
one=two;
}
declar
est heconstructorofthecl
assCAdd.Thenameoft heconstruct
oristhesameas
thenameoft heclass.Ifst
atementCAddmy obj
ect
(4)i
scal l
edthi
sconstructori
scall
ed
(becauseoft henumberbet weenthepar
enthesesi
nmy object(
).(
Thecompi l
erwill
callt
he
constructorwhosepar ametersmatcht
heargumentsusedi nthefunct
ioncall
.)
Thest atement:
CAdd( )
{
cout<<"
Adef
aul
tconst
ruct
ori
scal
l
ed"<<endl
;
}
decl
aresadefaul
tconstr
uctor
.Ift
hest
atementCAddmy obj2;i
scalledt
hedefault
const
ructori
scal
led(not
e:nonumberbetweentheparentheses.(Remember,
t hecompil
er
wil
lcall
theconst
ruct
orwhoseparameter
smat chtheargument susedinthef
unctioncal
l.
)
Thestatement:
~CAdd()
{
cout<<"
Dest
ruct
ing"<<one<<endl
;
}
declaresadest ruct
ortodeallocatetheobjects.Notet hetil
de( ~)
.
Attheendoft heprogram objectsaredeall
ocat edint herever seorderi
nwhichthe
constructorsarecall
ed.
Note:Constructorscannotbecal l
edexplici
tl
yasi ftheywer er egularmemberfuncti
ons.
Theyar eonlyexecutedwhenanewobj ectoft hatclassiscr eated.Destr
uct
orsare
automat i
call
ycal l
edwhenanobj ectisdestr
oy ed.Forexampl ewhenanobj ecti
s
dynami call
yassignedandi ti
sr el
easedusingt hedel eteoper ator
.(Dest
ruct
orsarereal
l
y
handywheny ouusedy namicmemor y)
.
TheAr
rayasanAbst
ractDat
aTy
pe
Thearrayi
sabasicabst r
actdatatypethatholdsanor deredcol
l
ectionofit
emsaccessiblebyaninteger
i
ndex.Theseit
emscanbeany thi
ngf r
om primiti
vetypessuchasi nt
egerstomor ecomplexty
peslike
i
nstancesofcl
asses.Sinceit
'sanADT, i
tdoesn'
tspecifyanimplementati
on,butisal
mostalways
i
mpl ement
edbyanar ray(dat
astructure)ordynamicar r
ay.
Thewor d"arr
ay "wil
lrefertotheabstractdatat ype.
Arrayshaveonepr opert
y :t
heystoreandr etri
evei temsusi nganintegeri
ndex.Anit
em is
storedi
nagi v
eni ndex,andcanber etrievedatal at ert
imebyspeci fyi
ngthesameindex.
Thewayt heseindiceswor kisspecif
ict otheimpl ement at
ion,butyoucanusuall
yjust
thi
nkofthem ast heslotnumberi nthear raythatthev alueoccupies.
/*Stat
icAll
ocat
ion(
wil
lbeal
l
ocat
edi
nthest
ack)
*/
i
ntarr[
5];
arr
[3]=5;
/*Dy namicAl
l
ocati
on(
wil
lbeal
l
ocat
edi
ntheheap)
*/
i
nt* arr=newint
[5]
;
arr
[3]=5;
/*.
..*
/
/*Remebertodeal
l
ocatememor
yal
l
ocat
edi
ntheheapwheny
ou'
redone.
*/
del
ete[]ar
r;
i
nt[
]newList=newint
[5]
;
newLi
st[
2]=4;
ThePoly
nomialAbst
ractDat
aty
pe
cl
assPolynomial{
//
object
s:p( =a0xe0+...+anxen;
x) asetofor
der
edpai
rsof<ei,
ai>wher
eaii
nCoef
fi
ci
ent
s
andeiinExponents,
eiar
eintegers>=0
Public:
Polynomi al
();
//returnthepolynomi alp(x)
=0
i
ntoper ator!
();
//i
f* t
hisistheZer opolynomial,r
etur
n1
elsereturn0
Coef f
ici
entCoef (
Exponente) ;
//r
eturnitscoefficientofein*thi
s
ExponentLeadExp( )
;
//r
eturnthel ar
gestexponenti n*thi
s
Polynomi alAdd(Polynomi alpoly
);
//returnthepolynomi al*thi
sandpoly
Pol
ynomialMul
t(Pol
ynomialpol
y);
//r
eturnt
hepolynomial*t
his*
pol
y
}
;//
endPolynomi
al
TheRepr
esent
ati
onsofPol
ynomi
als
Cl
asspol ynomial;
Cl
asster m{
Fr
iendpol ynomial
;
pr
ivat
e:
intexp
floatcoef;
}
pol
ynomi
al:
:pol
ynomi
al(
intd)
priv
ate:
stati
cter
mt ermArr
ay[MaxTer
ms];
//MaxTer
msisaconst
ant
.
//termArr
ay[MaxTerms]shar
edbyal
lpol
ynomi
alobj
ect
s.
st
ati
cintfree;
i
ntst
art,f
inish;
A.st
artA.
fi
nish B.
star
t B.f
ini
sh f
ree
coef 2 1 1 10 3 1
exp 1000 0 4 3 2 0
0 1 2 3 4 5 6
Advant
ages:
Savespacewhenpoly
nomial
isspar
se
Di
sadvant
ages:
Wastetwi
cespacewhenallt
ermsar
enonzer
o
Funct
iontoaddt
wopol
ynomials
Pol y
nomial
C=A+B, assumedRepr
esent
ati
on3.
Thet
erm ofPol
ynomi
alCst
art
ingatt
heposi
ti
onf
ree
/*addinr emai ni
ngtermsofA( x) */
for(
;a<=Finish;a++)
NewTer m( termArray[
a].
coef
,termAr
ray
[a]
.exp)
;
/*addinr emai ni
ngtermsofB( x) */
for(
;b<=B.Finish;b++)
NewTer m(ter mArray[
b].
coef,
termArr
ay[
b].
exp);
C.Fi
nish=f ree-1;
ReturnC;
}//
endofadd( )
voidPolynomial
::
NewTerm( f
loatc,
inte)
//Addanewt er
mt oC(x).
{
if(fr
ee>=MaxTer ms){
cerr<<“Toomanyt erms”
<<endl;
exit(
1);
}
termArray[
fr
ee].
coef=c;
termArray[
fr
ee].
exp=e;
free++;
}//end
Spar
esMat
ri
ces
Whati sSpar seMat ri
x?
Incomput erpr ogr ammi ng,amat ri
xcanbedef inedwitha2- dimensionalar ray.Anyar ray
with'm' col umnsand' n'rowsr epresent samXnmat ri
x.Ther emaybeasi tuat i
oni nwhi ch
amat rixcont ai
nsmor enumberofZEROv aluesthanNON- ZEROv alues.Suchmat ri
xis
knownasspar semat r
ix.
Sparsemat ri
xisamat r
ixwhichcont ainsv eryfewnon- zeroel ements.
Whenaspar semat r i
xisrepresent edwi th2- dimensionalar r
ay,wewast el otofspacet o
representt hatmat rix.Forexampl e,consi deramat r
ixofsize100X100cont ai
ningonl y10
non-zeroel ement s.I nthismat ri
x, onl
y10spacesar ef i
ll
edwi t
hnon-zerov aluesand
remainingspacesofmat ri
xaref il
ledwi thzer o.Thatmeans, total
l
yweal locat e100X100
X2=20000by tesofspacet ost orethisint egermat ri
x.Andt oaccesst hese10non- zero
element swehav etomakescanni ngfor10000t i
mes.Spar seMat ri
xRepr esentat i
ons
Aspar semat ri
xcanber epresent edbyusi ngTWOr epresent ati
ons,thosear easf ollows..
.
1. Ar rayRepr esent ati
on
2. Li nkedRepr esent ati
on
ArrayRepr esentat i
on
Inthisrepr esent ation,weconsi deronlynon- zerovaluesalongwi t
htheirrowandcol umn
th
i
ndexv alues.I nthisr epresentation, t
he0 r owst orestotalrows, t
otalcolumnsandt otal
non-zerov aluesi nt hemat ri
x.
Forexampl
e,consideramatri
xofsi
ze5X6contai
ning6numberofnon-
zer
oval
ues.Thi
s
matri
xcanberepresentedasshownint
hei
mage..
.
009000
000080
040002
005000
000200
i
ntmai
n()
{
i
nta[
10]
[10]
,tr
ans[
10]
[10]
,r,
c,i
,j
;
cout<<"
Ent
err
owsandcol
umnsofmat
ri
x:"
;
ci
n>>r>>c;
//Stori
ngelementofmat ri
xenter
edbyuseri
narraya[
][
].
cout<<endl <<" Enterel
ementsofmat
ri
x:"<<endl;
for(
i=0; i
<r; ++i)
for(
j=0; j
<c; ++j )
{
cout<<"Ent erelementsa"<<i+1<<j+1<<":";
cin>>a[i
][
j];
}
//Display
ingthemat r
ixa[
][
]
cout<<endl <<"Ent
eredMatri
x:"<<endl
;
for
(i=0; i<r;++i
)
f
or (
j=0; j
<c; ++j
)
{
cout<<""<<a[i]
[j
];
if
(j==c-1)
cout<<endl<<endl;
}
/
/Findingtr
ansposeofmat
ri
xa[
][
]andst
ori
ngi
tinar
rayt
rans[
][
].
f
or(i=0;i<r;++i
)
f
or(j=0;j<c;++j)
{
t
rans[
j]
[i
]=a[
i]
[j
];
}
//Display
ingthetranspose,
i.
e,Di
spl
ayingarr
aytr
ans[
][
].
cout<<endl <<"TransposeofMatri
x:"<<endl
;
for
(i=0; i<c;++i)
f
or (
j=0; j
<r ;
++j)
{
cout<<""<<t rans[
i]
[j
];
if
(j==r-1)
cout<<endl <<endl;
}
r
etur
n0;
}
Out
put
Ent
err
owsandcol
umnofmat
ri
x:2
3
Ent
erel
ement
sofmatr
ix:
Ent
erel
ement
sa11:
1
Ent
erel
ement
sa12:
2
Ent
erel
ement
sa13:
9
Ent
erel
ement
sa21:
0
Ent
erel
ement
sa22:
4
Ent
erel
ement
sa23:
7
Ent
eredMat
ri
x:
129
047
Tr
ansposeofMat
ri
x:
10
24
97
Mat
ri
xMul
ti
pli
cat
ion
#i
ncl
ude<i
ost
ream>
usi
ngnamespacest
d;
i
ntmain()
{
i
nta[
10][
10]
,b[
10]
[10]
,mul
t[
10]
[10]
,r1,
c1,
r2,
c2,
i,j
,k;
cout<<"Ent
err
owsandcol
umnsf
orfi
rstmat
ri
x:"
;
ci
n>>r 1>>c1;
cout<<"Ent
err
owsandcol
umnsf
orsecondmatr
ix:
";
ci
n>>r 2>>c2;
//Ifcolumnoff ir
stmatr
ixi
nnotequaltorowofsecondmat
rix,
//askt heusertoentert
hesizeofmatri
xagai
n.
while(c1!=r2)
{
cout<<" Err
or!col
umnoffirstmat
ri
xnotequalt
orowofsecond.
";
cout<<"Ent
err
owsandcol
umnsf
orf
ir
stmat
ri
x:"
;
ci
n>>r 1>>c1;
cout<<"Ent
err
owsandcol
umnsf
orsecondmat
ri
x:"
;
ci
n>>r 2>>c2;
}
//Stori
ngelement soffi
rstmatr
ix.
cout<<endl <<" Enterel
ementsofmatr
ix1:
"<<endl
;
for
(i=0; i
<r 1;++i)
f
or (
j=0; j
<c1; ++j)
{
cout<<" Enterelementa"<<i+1<<j+1<<": "
;
cin>>a[i][
j]
;
}
//Stori
ngelement sofsecondmatri
x.
cout<<endl <<" Enterel
ementsofmatri
x2:"<<endl
;
for
(i=0; i
<r 2;++i)
f
or (
j=0; j
<c2; ++j)
{
cout<<" Enterelementb"<<i+1<<j +1<<": "
;
cin>>b[i][
j]
;
}
/
/Initi
ali
zi
ngel ementsofmat
ri
xmul
tto0.
f
or(i=0;i<r1; ++i
)
f
or(j=0;j<c2; ++j
)
{
mult[
i]
[j
]=0;
}
/
/Mul t
ipl
yingmatri
xaandbandst
ori
ngi
nar
raymul
t.
f
or(i=0;i<r1;++i
)
f
or(j
=0; j<c2;++j
)
f
or(k=0;k<c1;++k)
{
mul
t[
i]
[j
]+=a[
i]
[k]*b[
k][
j]
;
}
//Displ
ayingthemul t
ipl
icat
ionoftwomatr
ix.
cout<<endl <<"OutputMatrix:
"<<endl
;
for(
i=0;i<r 1;++i
)
for(
j=0;j<c2; ++j
)
{
cout<<""<<mul t[i
][
j]
;
i
f(j==c2-1)
cout<<endl;
}
r
etur
n0;
}
Out
put
Enterr
owsandcol
umnf orfi
rstmatr
ix:
3
2
Enterr
owsandcol
umnf orsecondmatri
x:3
2
Err
or!col
umnoffi
rstmatr
ixnotequalt
orowofsecond.
Ent
err
owsandcol
umnf
orfi
rstmat
ri
x:2
3
Ent
err
owsandcol
umnf
orsecondmatr
ix:
3
2
Ent
erel
ement
sofmatr
ix1:
Ent
erel
ement
sa11:
3
Ent
erel
ement
sa12:
-2
Ent
erel
ement
sa13:
5
Ent
erel
ement
sa21:
3
Ent
erel
ement
sa22:
0
Ent
erel
ement
sa23:
4
Ent
erel
ement
sofmatr
ix2:
Ent
erel
ement
sb11:
2
Ent
erel
ement
sb12:
3
Ent
erel
ement
sb21:
-9
Ent
erel
ement
sb22:
0
Ent
erel
ement
sb31:
0
Ent
erel
ement
sb32:
4
Out
putMat
ri
x:
2429
625
Repr
esentat
ionofarr
ay
Rowmaj
orandCol
umnMajorAddresscal
cul
ati
ons
Inthistutori
al,wear egoi ngt ol
ear
nabouthowt ostoreel
ement sinatwo-di
mensi
onal
array.Forthosewhol ovet olear
nthroughvi
deos,j
umpov ertothebottom oft
hepage,
there’
sav i
deot utori
alfory ou.
Bef or
est art
ingstoringelement sofamul t
i-
dimensi
onalarr
ay,l
et’ssayI’
veanone
dimensional arr
ayhav i
ngel ementsl
ikethi
s:
A1, A2,A3…. An
Theseel ement sar estoredi nmyli
nearmemor yspaceasfoll
ows:
A1A2A3A4. .
.An
Onethingy ouneedt orememberi s,nomatterwhatty
peofar
rayi
tis(
1Dormulti-
di
mensi onal),
theywill
bealway sstoredl
inearl
yint
hememoryspaceasabov
e.
Let
’sjumpt othecaseofmul t
i-di
mensionalarr
aysnow.I
magi
neI’
vea3×3mat r
ixli
ket
his:
A11A12A13
A21A22A23
A31A32A33
Therearet womai nway sofstori
ngthem, t
heyare:
RowMaj orOr
dering
ColumnMaj orOrderi
ng
RowMaj orOr
derRepresentat
ionofArr
ay
RowMaj orOr
derisamet hodofrepr
esentingmul t
idi
mensionarrayi
nsequenti
almemory.
Inthi
smet hodelementsofanar r
ayarearrangedsequenti
all
yrowbyrow.Thuselement
s
offir
strowoccupiesfi
rstsetofmemor ylocati
onsreser
vedforthearr
ay,el
ementsof
secondr owoccupiest
henextsetofmemor yandsoon.
ConsideraTwoDi mensionalArr
ayconsistofNr owsandM columns.Itcanbestor
ed
sequenti
allyi
nmemor yrowbyr owasshownbel ow:
Row0 A[
0,0] A[0,
1] .
..
..
..
..
..
..
..
.. A[
0,M-
1]
Row1 A[
1,0] A[1,
1] .
..
..
..
..
..
..
..
.. A[
1,M-
1]
.
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
..
.
RowN-
1 A[
N-1,0] A[N-1,
1] .
..
..
..
..
..
..
..
.. A[
N-1,
M-1]
Example:
Consi
derfoll
owingexampl
einwhi
chat
wodi mensional
arr
ayconsi
stoft
wor
owsandf
our
col
umnsi sstor
edsequent
ial
l
yinr
owmajororderas:
2000 A[
0][
0]
2002 A[
0][
1]
Row0
2004 A[
0][
2]
2006 A[
0][
3]
2008 A[
1][
0]
2010 A[
1][
1]
2012 A[
1][
2] Row1
2014 A[
1][
3]
TheLocationofelementA[ i,
j]canbeobt ai
nedbyevaluat
ingexpr
essi
on:
LOC( A[i
,j]
)=Base_ Address+W [ M( i
)+( j
)]
Here,
Base_Addressi
st headdressoff ir
stelementinthearr
ay.
Wist hewordsize.Itmeansnumberofby t
esoccupiedbyeachelement
.
Nisnumberofr owsi narray.
Misnumberofcol umnsinar ray.
Supposewewantt ocalculatetheaddressofelementA[1,2].
I
tcanbecal cul
atedasf oll
ow:
Here,
Base_Address=2000, W=2, M=4,N=2, i
=1,j=2
LOC( A[i,
j]
) = Base_ Address+W [M( i
)+( j
)]
LOC(
A[1,
2]) = 2000+2*[
4*(
1)+2]
= 2000+2*[4+2]
= 2000+2*6
= 2000+12
= 2012
ColumnMaj orOrderRepresentati
onofAr r
ay
ColumnMaj orOrderi
samet hodofr epresentingmult
idimensionarrayinsequenti
al
memor y.
Inthi
smet hodelementsofanar r
ayarear rangedsequenti
all
ycolumnbycol umn.Thus
elementsoffi
rstcol
umnoccupi esfir
stsetofmemor ylocat
ionsreservedfort
hearray,
elementsofsecondcolumnoccupi esthenextsetofmemor yandsoon.
ConsideraTwoDi mensionalArrayconsi stofNr owsandM columns.I tcanbestored
sequenti
all
yinmemor ycolumnbycol umnasshownbel ow:
Col
umn0 A[
0,0] A[
1,0] A[
N-1,
0]
Col
umn1 A[
0,1] A[
1,1] A[
N-1,
1]
Col
umnN-
1 A[
0,M-1] A[
1,M-
1] A[
N-1,
M-1]
Example:
Consi
derfoll
owingexampl
einwhichatwodi
mensionalar
rayconsi
stoft
wor
owsandf
our
col
umnsi sstor
edsequent
ial
l
yinColumnMaj
orOrderas:
2000 A[
0][
0] Col
umn0
2002 A[
1][
0]
2004 A[
0][
1]
Col
umn1
2006 A[
1][
1]
2008 A[
0][
2]
Col
umn2
2010 A[
1][
2]
2012 A[
0][
3]
2014 A[
1][
3] Col
umn3
TheLocationofelementA[ i,
j]canbeobt ai
nedbyev aluat
ingexpr
essi
on:
LOC(A[ i
,j]
)=Base_ Address+W [ N(j)+( i
)]
Here,
Base_Addressi
st headdressoff ir
stelementi nthearr
ay.
Wist hewordsize.Itmeansnumberofby tesoccupiedbyeachelement
.
Nisnumberofr owsi narray.
Misnumberofcol umnsinar ray.
Supposewewantt ocalculatetheaddressofel ementA[1,2].
I
tcanbecal cul
atedasf oll
ow:
Here,
Base_Address=2000, W=2, M=4,N=2, i
=1, j
=2
LOC( A[i,
j]
) = Base_ Address+W [ N( j
)+(i)
]
LOC(
A[1,
2]) = 2000+2*[
2*(
2)+1]
= 2000+2*[4+1]
= 2000+2*5
= 2000+10
= 2010