0% found this document useful (0 votes)
8 views

Array

original

Uploaded by

Baljinder Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Array

original

Uploaded by

Baljinder Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

...

I
, r
.' ,
, ..' . .
..
r • I •

\
• ► •

'• J I • I

. .

· Ami..... ·• ·· ·
~_l.\!9µ,u~TION _
~
· ·· ·· · · · · • · •
• . ~ (

In previous chapters, we have learned how a variable stores a value in it. Such varia~l~ can be of
anY data types like int, floa~, char, long int, double· etc. We c~ st~re just ;a single y~ue in a v~able •
but not more than_ o~e. So, _10 case we need to store five different_yalu~s ~~n ti~~ d~ffer~~t v~ables •
will be needed. Sunilarl~, m case we need to store fifty or more values -~~ri s~~~tion ~111 be wor_st
1,eCause it will ~ very ~tfficult to declare all fifty variables and. store fifty ~~ues_ one by one. It will
also be wastage of time for all these declaration and storing process. So, to overcome this probl~m,
the concept of array has been introduced in ~- Let us· discuss the concept of array. •
.,,.,-..............~,,.Y_·•~-1/''@ •. .. ., ~ \I ••• •.•·. • • ••
~--·:
.. • •

~
.. • • • ' ....... 1. 4
: ' < . . ~ \ : ~ t . ~ •• //wl•(•'... •., •• I
_.\ ..

.tfn array is.a ~ollCCti~n ~~ eleme~ts of homOgtJlous (s~ar) data½e w\lich take consecutive
J ' •

(continuous) memory locati(?ns m RAM to store values.under a commonvana~le ~~j A h~mogenous


data el~ment imp~es elements of si~lar data ty~Arrays off~r a conve~entJineans of crea~ng lists
of related varia~~~
, - •. - - -
• •. -. ..•.._, . . •• . .: , . . ·: • \ • r ' . • },. • -J't • • I I ., I• ..._ '

-_.,-~CITBET:~'EEN]AN}::ARRAY\ ·AND 'AN ORDINAR Y


_
~ *<
,hlft·
':--~t::~~~~ (·Y~i>~*-~(4:.\>'
• ,·
1;·~:1¾:{~r~tf?~?t~itf;-)j{;~:~
~iJfil~(·):.i~Y .:<:,/ l ~~:( ,, ~: >: , ', -~ ~-:·· ! 1 •
l",·}¾,.,?AW;,,,.i•.. . , ..~•,t,,i;,,t,;;.·•· •':·' - ,w~ .. ~ ~ •··f ., . ._.,..,-,,, ;"
\4U~l~;:*1/,~/!~;~•j~1r,,~'[~ ~-~'}efs:_~-~t~;r;\.....,;:d ~· •.. / ...:: .. ~·-,! -~·.,i· ..:'.
~4" ~ ·


~;
~ ••

~
1
I • •

~,
~
' · •• ,......... ,._.. _____ >-.,-.◄ ·~--
,~.,.t

l ••

-.
, '-'.

, ~:.-~~~~~J,~~:Jtt;f;~~,i~ ~~~4'f'¥\,;~~-\~\"~~1.h, ;~:J·.. ~~-~-M ·~ ~tv,·~-'t ,. :•, '


. . ' ...... -.,. r f-- • ~ I 1 J •. . ... •'

~Simjiiy;-aSlngle variable can be used to store one data item whereas-~ arraY is a collection
,
1
of ~y such ho~ogeqous_data items. • .• •. . . .• .l .: •• \
, -tf An array is called a subscrip~ed variable, it is always declared an~ accessed ~sing subscript
/J"whereas ordinary variable do not have any subscript. Ordinary variable· is declared as, for
. example, int num ; whereas an array is declared as, for example, int num [10] ; •
I '

::, '•,

• • "f~ .~-r·=~o,iUSJ.N&ARRAYS .'· . \ ' .' \.


~•.-.t.u.-.,,,~-" its.-:•.;,_,,,~.. ', ,,••. ·'·• ,< :: .. •
_ _, . _ , . _ , ,_ _ _ _ _ _ _ . . . _ _ ,.. '
.-

• --·- - - -
1

are
• .. ~

-Jl~'may elenl"ents stored and can be ilCcessed With a single variable mt.me with different
mdices .• • · I ,. I ,
I • .A

All arrays elements are stored on contiguous memory locations causing fast execution of ... ,.
l

programs accessing them. . :: -~ ~ _ _, .:. :. J l _ \

.__S are mo~t app~pnate for storing a fixed am~unt of data which can be accessed ~ any'
. \ .....~..J'

IQ; velY good al~ve to store data elements in the problems like ~ n nud,m,
• an item in a giveri1ist of n numbers, calculating the sum of n numbers etc.
J. Arrays pennit efficient (constant dme,ocO(alll)) random access to any element in th
lY of reference. Locality of referen
6. Iterating through an array off
ers g ~ 1art of array will also e~
one nA rt of array is accessed the be accessed soon, ~ :~ -.
n nex p
• cache memo ry in one go, so that when required "th~~
ru •
it is better to bring whole array ,n
already available there. . ' '-~ ·•t
~~
trUctures; for examp1e, st0nng
1. Arrays arc among them.ost 111pact data s 10
• t r with 1 i 0 intc&crs.
co
array takes only 100 timCS the spa . uired to store an in ege .'
ce;: f extra pointers is reqmred o~ Y ew eitra ~' ~,
ovemead for the whole ~Y · No , as is the case Wi~°"~
data structureS. like linked bst etc u
. th t they are commonly us . '
lar and easy to use a ed to im pleme nt Oth
8. Arrays are so popu
tructurcS like strings, staeks and ueues etc. er~
s q . . tak thousands of eleme '°'
vJ. It is easy to declare an.array even if it es .
nts.
...jio. The method for accesmng arra:'. elements is also very sunple
~
- "'"I ~ ys are wa
»~~ ~ G F S
~ L .::.: O f ARRAYS--.
1- -"' AI t hen we
ne ed to pe
J rm frequent op
uo
. .
erations of insertion and d
uuen w . . f
of elements. For exam~le, mcas~ d 1 ting an item form an array, we e1'ther have tClet;~II.
~ :i:ment forward. which is a wa
•all the elements followmg ~e de ste of time or we~~t
lace a sentinel (any special ma k) . dicating that the element on that position has c~
P r in
thi
deleted, but s causes a wastage of space.
. ~
2. Ccompiler does not permit aut ti bo un d ch eck ing fea tur e.
i ,

othma ctual array size given e.g It means, we can store


arr ay ele . we can access 17th el ~
access mo
of an array,re even 1f. ments tha
.d.n eed~carray of siz.e ·11
we have ec1 1o. It w1 not result 1n · any . clllcrt
time error, though logically it wi ar . syntax
ot ~
3. Ordinarily, arrays are static, ll be incorrect. . .
having fixe& size. Bu~ if we us
altered as reauired but it is diffic e dynamic arrays, size can~
ult to learn dynamic arrays.
✓- If the number of elements sto
red is l~ss than the size of the arr
• memory space remains unuse ay, then the rest of th e~
d and is wasted.
y. While declaring arrays, array size mu
st be specified and c~ ot be lef
is invalid declaration because
array size has not been mention t blank e.g. int nutn{1;
\?, Looping or iterative statements are mandato ed .
ry to be used along with arrays,
all the array elements.' in case acc~m
~or•AIQµY
Array is of two types i.e. one dim
ensional and multi-dimensiona
will discuss one dimensional an l (more than one dimension).Wt
d two-dimensional array which
array~ in this chapter. is a special case of multi-dim~nsio
oa
. Let us discuss one dimensio ,
nal ~a y first.
6¥ i'&~~~IMENSJONAL AA
AAY \
l'§ne dimension~ array is also
referred to as Single dimensio
subscripted array or linear nal arrays or 1-D array or lif
array. One dimensional array
common variable name only is used to store set Qf values um\
row-wise· i.e. a value in each 1'
dimensional array. ro ~L et us know how to dec
lalC"
I 21 0 t~- '_,_--., .....•, "• ...,. , . -~ • .
1
••·•- •·w• -.~~
.. ,....,··-"•· _,..___ ,_,.....-•"• q•-
" ~......
•~-.- ,:~f" " .,""'
I~•• -K

\ JBD Pt op ai. .--~ ..a....


•·~ ~• ""r.Z' '°" :-,;
i..;.;....... . . . . . ;..,i......
.......i w-;.~ ,.,'-'t\ ......... ..~ -
-
• ,_.,,
--"""" '.... a.o ~
....C
\
--~a..:~ .
;4,f~.,,,,

pon of one dimensional array .


~W' is as follows: • '
syn, ·
x11e storage_c - lass data ~ ,
.JJ'~ _•., I"' array_n~e [exp];

¢iet1l• • cl~ (extern, static ~uto) ·r f, • • , • •• -


siorage_ ' e ers to the storage class of arra(we will learn storage
), es in next chapters) • . •
class . . . • • •
clllta-type can be any valid data type of C such as int, float,• struct etc. . •. ·.·
J· arraY_name ~epresents the any valid name Gust like a valid variable) of the array.
{ fbe single ~arr of square brackets [ 1represents single indei or subScript which is used in
/ e ,1:n1ens1onal array .• : . • ·,
~~u

eJP square br~ckets represents total number of elements required. exp is ariy expression with
in

f- symbolic constants or constant values resuling in any positive value'.• • • •


bJDPle, int num[5] ; • • • •• . . , . ,
•At,ove statement defmes num as an array pf int data type which can store S integ~r e~ments_ i.e.
. . s. So, total 10 bytes ~e allocated_to num, as each element being int takes bytes. These 5 2

JS 1einen~ will be indexed from Oto 4 i.e. first element Of the array gCts index number Oand last
_:t le. 5 _element of the a,rray gets index number 4. This ~a~ '.'mun" could be represented in
rneinory like this : . , •- • . , _: ~ _-~
I 1 2 3 • · . ~ ·, · ·. •-
. .- .• num. I . I ·. . , I ~ ,. .'. ;.•.· I- ,. -~
l . . I . ·.
✓ • Fig. 7.1. Memory repr~sentation of array _ . . ~
• "

..el~men~ will be
.&I

.'where each blank box represents 2 bytes of memory where values of •


~y
• ,
,. r
::J

stored. ' <' • ' ' ) ' . • ' . ' ·, ' i . ' ). "' ,. .. . .. . ' f l' ... • , • I f \. • •• 1! ' ' • •, . - • I :I :

Contiguous
memory · .,___
locations

. . .
. .. .., ..

• . ·,; .:~ • . , . , . •ro- ~


Values of
Integer data. 50 -------------. ' .

num[.2f • Shows elements stored at •. _. '.-1 t . : . :


~, ' 1. • •c ~ .... "- ~~,

~" -
type Contiguous memory _
100 num[3-J ·. locations (or addresses) ·.- ,,, -~ • '-. ,
,. numf4} · •. ~ ··:: • ·f ··- ••. •••. : •• : · •·': ~ . . _,·-. ·:" •\._ ._·
'. 90 .
:. _ . Fig. 7.2. Description of ~rra~ • . • . .• - .~ ··: ... •!. . • • .\
< I ..,, "\
~ '

index a1\Va}'s starts from 0. Now, let us discuss h~w values are accessed from arrays.
" • •

suppose array num contains 5 values as 15, 25, 50, 100 and 90. . . . • • • • • • !

ue has an. appropriate .I~atioD in memory and index number.. .


in. array. As sho~.. in
.. :. ' .~ . .. . .. . •.. ..
\

,.
' ,. ' .

0 ·1 ·2 ·3 4•
i;ium ( - s · I
1 2s I so • I 00 I , 1 90 • I1
·l, • . sooo soo2 .. , so04. 5006 • • sooa
jrlg. 7.3. Location and index number In ~rray •
,. t

.
Thi8 18 .
fUrther explai~ed bel6w.
,,I ,,. · ble . . Mem.ory Location (A
• Tarta .. . ,,. . •ue.
:.::r~~n=um=r;;o1;.;;~~12-.·~~~-...:..L..:.,- .-~~7~s~-~~+~~~-:-~5000~----
l1
I
11
,,
II

. . .. 5006
11um(3] 100 . --
I '

5008

Also note that, in this example each element of array is allocated two bytes of me~ory bee
. array has been declared to be of int data type, ru:id an int takes 2 bytes 0 ~ memory. If it was of
· da t • , b allocated 4 bytes of memory •
ta type the~ eac~ element of the array wou~d have ee~ . - . •
. . ' .

~NO'T''E
. Memory I~tio~ (or lllem~ry ~d<kesSes) written above, _are writt~~ using decimal nu
system just for convenience, otherwise, C compiler ~1ves., these memory addresses
hexadecimal number syStelll. • . • • ' . •• ' • ' ..:, \ ·•·:..- • : •
Some other declarations of single dimensional arrays are as follows:
float arr[50]; • . :.
-~·, ·Here arr is·an array·vanable. of'float data fypefwhich.·crufstore-·50 elements of floating.
. ; .; ' • ' '
data type.
< • • .,. I ·, • ' '\. •
. . . , ,

.. . .- ··;.- .'·~: char·nam~[5];·~-,:: >~r;'._:". ·:· ...• I.-~.-; ·-:_: . ···" :· •• ' ' .• - • • 1 •• •
' •• • Hefe Daffie is'·all array variable nallle:of:chai' data type which ·can store 5 Characters.
vlnitialiqtion of one dimensional array . .. , •. ·' \ -•. ~ ,• . - . • ' ,. • ) A- •

_., ,. _,@i~tion is ll~ed to ass~gn value to ai:iy\'.ariable. One dimensioJlal array is initialized at
time of declaration. Jalso.. The syntax· is as follows:' ·. ' •'' • •
t_ I ' ·.-., ' ' •

[ ,-. , \ ~ • ' ' : ' ,. \ ·\ .. I 1• • •• • l •l If ' ' f • • • ( : • \ I •

storage_class .~ta_type arrayname. [exp]={list ·or values} ;


,Where, .- •
711 "-

·• • • , ":. •• • •
I

•·: • •• •~ ' • • •
I

• ·

;~ .- 1~-: ::::t~~~:!t~~:i~-~r6..:·. l.: . ••


.- . ; ~ arrayn~e ~~ the name of. ~e m.:ray y~ab~e, ~ ✓- 1
•. ,.· • • - •

,' exp in square brackets represents total nUlllbef Of elements


• • • I
requked Md it must be
i
... . positive - constant. . . ._ . . .
r' list of values in curly braces i~ values to be assiglled to amly elements, these m~st be~

by comma •· ~ . • · · , . • . . . ~~ ~----~__.,- . .,
~ ~0
, ' .. ~
' ( ' ., ' k .. f. ' J" .,,

;

L •
• . a, ' ) ; •

t' ,~
// "/IJ, •,, • J ~ ,.,i ~•; ;,•,•• •~ •, ,1 : "f ~ .,. _,• < I • 4 • :••: ') ,c

., · exp must be any constant Le. numeric valu~ or syni~n~ CODStant, in no way, this can
variables. (As explained in following valid initializations #5). . • •
. .
xample. int num[4]={5,16,51~67); f • ·.;: • .\ L •· -~ ~ • • •• - ,

Here, rium is an arfay Variible nairie of int data type Who8e size is 4 and values ini~
folJows according to their index number: num[0]=5, nuni[1]=16, num[2]=51, nuniPr·
~me others valid Initializations (and declarations) are as follows:
. /· int mnr~s[ ]=~90,89,100}; . ., •. •• . _
Here, arrays size ~~s. not b~en specified expltcitly because it is optional to mention array
• when when 1n1tial
size . ~alues of array • elements 'are given.' In such case, size of array is
number of values g1ven 1n curly braces. : •
.~intnu_m[5J={4,5}; . , ,.•.
1 If we give values 0 ~ some of the ele~ents of th~ ~y then remaining element for Which no
value has ~en specified in the l~st, are automatically ~signed value Oby C compiler&ere,
num array 18 declare~ t~ have 5 elements, but yalue of only two elements has been given. So,
- but•remaining elements
]will be in1·t·ia1·tzed wit• h value 4 and 5' respectively ••
, num[O] .and . I .
. . num[
will _be 1n1tiahzed with 0. • . ' ·\
f int v~ue(,10) = {O}; • • _ '
Here also, o~y the first el~ll!ent is assigned 0, rest of the elements 3l'e assigned 6au~inatiCally
by the compiler. as explained above i.e. value[O] = O, value[l]=O, value[2]=0. • • •
s.
#define N ~- ;~.:¥~ t:.~· :~_-{. .>).· _·;·; •

• · ' . main() · · ., · ~, ~:- ~:·:·· -.t: •• • •


' •
1
I\ I I 1 f¥ , 1

{ , I ~
·, .... l
'
(
\
\

int num[N]= {12,27,36}; ' ' •


'
:
;
"'.
..

/* some code*/,, ' I I I • I,.


' •' . I• ' •

-.
• I

}
,
.• . .~ . ' '

. Here, Array size N is defmed using symbolic const4nt using #. defin~ p~ep~~e~sor ~ective.
JI char name[ ~={ 'v', 'a', 's', 'u'}; , • • -

.-• ,_.. \~..


I • • • • I \

Here, name 1s an array of character data type (also called String). In cas~. of char data type,
value~ to be initialized are enclosed ~n single quotes and compiler adds· a NULL character
after the last chanicter of the array. • • .: . .. • , • , , •. .., , . : ./ ,_' / .. , :· •.. '. , :
7. char StudentName[] = ~'Sandeep Sood"; t ·.-· •• l • • • •

This is another way of initializing ml'ay of char.data type.~~ut.tQis meth~ is rno~e comlllonly • ' • • r I • ,. . 'Ii 4, •

used with Strings. (Note. : Strings will be discussed in sub~eqµent chapters)· • ~ • • • • •


Some invalid declarations/initializations of arrays are as follows : ..
• ' I ,. , ~ .., • 11\ '• .. '
\

• • •,, ••
\)'.' int value[O] ; Invalid declaratio~~ ~a~~- ~y size _c~. iiOt ~ zero.
\31 int value[l ]={ 134,51 }; . . Invalid initializa,UOD: because ~~~ize._sh0~4 not
. . be less than the total
L
values.
• •..
•, ~ • •,. ~ ~ .J ~

· -){float discount[-2]={ 15, 25, 45); • •Another invalid initialization, u ·array size c~ot be
. . . . . •
.
•, , • " . .
t, I
,\

~ .
1n -ve. • •
'\
'
. •, . . .

· 4. float value[]; • · •Array size cannot 1?e left ·empty. But float value[]
I J., •, . = {15 .2, 9.1 } is a valid initialization., .. • ·
~ tf'-'11 ·1; i
. . .

~.,v• . • • • ' , • •

P\ an array · . . .. •. .:. -· . ·,:. ·


store data inl~-;_;;~y· either using· scanf ( >. inside _an iterative (or lOO~iilg'S~te.tnents)
er ll&i • g values directly to different elements u~mg ass1g~ent statement m the program.
1-two thods of storing data in the array are explamed below one by one. _, • ,
~) llllq •IPfDent statem,nt (without~ loops). . · =.: . ,,., ., .
• ,la followins prograni, elemeaits are assigned val~s o~e bf ~nc wt~qut ~g ~Y ~terative or
, ~ ....... But, this me~od·~ is rath~
., ~-'
v~~-~~~~:~e~~. ·~·~-···•'*::~.::.:=: laii1
L!!,:-1 <Ill"""" . -~"-~ ..,,;,----
--(t9c ,..___ • • .;
✓Progt'aJn 7
·1·· To store d ta
,e, ,. 2 ;- ,f
-~--l-'...J..J__
_l I 5 tatement.
main() 8 into an array without using any IOOP ng •

l m·t · • data type with size 4


I
I
!
_ arr[~]; , ~ ~ ~ ~ - - _ J
clrscr( ); ...,..___ _ _ _ __J
arr(Ql-IS
Array arr declared of int •
lrs r() . sed to clear the output screen i.e. it
1s u contents front screen•
cthe cprevious . . . '"
erases
r
1 .... .,- ;
... arr[l )=25 '• J
arr[iJ=8;. Values assign.ed one by one at different array indj.

atr[3]=19; ces.
~rin~" ~~",arr[PJ);~ Display values one by one of different array.elellleota
.. • ' • ,"41 4 '

~. •pnntf(': %d",arr[J]);.
, -
·j printfC' %9",arr[2J); . Output:
printf(" %d",arr[3]); •
!~ ~ 19
getch( ); •
}
_ ) Reading array elements fi m keyboard (Using scanf inside loop).
sta
The following program reads values in array usipg _Iterative or looping tement which is t
~
· f~ as compared to assigning values individual index numbe~ one by_ one. To understand it let~
:. -~ discus~ following program, like, all valu~s can be given i,y user m one line or each value may be.
separateline. . , . . ._.,• · · • • • • •
. . ., 1, • • •

\/'Program 7.2. To read an array r~ keyboafd UStng l~pblg statement is as follows,:' .


.
'
: · main( ) . • • • • ; '• •
. . _{ . :, . _.. . . • .. _ Array arr declared of int data type_ with size IS

__ ~t
·v .
~~J~; •• · •• : ",' ; Ask user to enter value o~ n ~o tell how many elCllleQls I
·· . , clrscr(
. ,
); ~ . .. ... -r . . ' ....-.~-.
'
~-.-.-------
. . .· .
user want to input• , •::- ~ . .,. ~ - ; > r • .- • • • • • • •

__ P_-~1!(~~-~w ~._an_r~elemen~ ,~'); .-:r


. , . ,. . r::===~=====~~:::=::::.::..=?:t:.::::..~::..::..~~--::-::
1\vo statements (for loop and scanf(')) are used ID:
~-::-::-::~
. .- : ,sc!lllf('.'%d'': n ; , : :· " ~ . • enter ~a~ into an array quickly at run time rather 11
t ••

. '
'

I
~t
a ~-::0·.. - • •. .
...,j.;:' -(?1,\1-~.J.<n;J
: : ~ •. •
........- :• ·" - A't\t
" v--• l] .,__.....
I
comptle ~e~ Not_e: W~ can. enter next elemen't•
- by pressing space bar key oncem
after another
·.· : · · , , -~~~~"~d",~-~[U.); by preging enter key...• • • "
".(i>rin~(l'~]~ltlents ~: ''; /'
· fo.r(i=O;i<n;i-t+) • • , • Y ~o statements (for loop and printf( )) are ~ll
· . p?ritf(:·~ ;,;~cmU . .. di~lay _data stored in an array. Here, in printf( 1om
getch( ); • space is given in double quotes after %d to separall
'· array el~ments. We can display array element.indif·
J f~rent !mes by adding \n (new line) in printf( )jtd
• ' I
hke· pnntf("\n%d",arr[i]); Then, output screen will
Output: display elements as shown below: -
How many elements?·3 10 • 4

10 15 9 . -- ..) ' - • <I.,


15
Elements are: JO J5 9 9
''l
sum +~ l/~ [i] ; ', ,·, .. .,,

.
t
. ' ! ••
I I
I

'

. I• •
, (
. . ,. .
, • I'
. •• !lo l ... ' .. '

.
}
~

htD=n/(sum); I' I

..
1

p~ntf("Hannonic Mean is %5.2::.f_:',h:m j

:):_;_ .. -- ~ -~ -- -_ _ ;~
getchO; -- -- -- -- ,
Output - 1 ,. • • • • , •• \ • •
} Total eieme~~ to be entered are? (N
ot more than 15): 4
Enter 4 elements . . \

Enter arr[O] element: 2.5


. , •• Enter arr[l] element: 5.2 • \
, )
• 1

Enter arr(2] element: 1.9


Enter arr[3] element: 4.3
'. Harmonic Mean is 2.96

. :•·_: •_:·~. ~~-~siQNiiT 'ARRA. Ys (,!'\


.

~.....i::it...,,.,~,;.-..,.,.,'¥~·v.,>,o'>.·,,;·. J
-
• , ~
. . t also supports two dimen~io~ai.
'
,. I • '
1

arrays. Two dimensional arrays is als


arraY or double su~scripte~ array o~ d~u o referred to as 2D
b~e ~~mension arr a~ As you kno~
•airay single subscnpt .(or smgle par in o~e ~mensional
r of square bi-ackets) is used butfui
•double subsc~pts (~r two pair_ of squ two dimensional lllTays
are brac~ets) are u~~- A:'.tw~ :~ ifCn
represented _simply m a tabulm: ~~~- A_ s~~?~l _arr~y~ can,_~e .
table 1~ ~ ~o~lec~to~ of r~ws ~d co
twil ~ens1onal arrays,_ ~very ele,~en,-t. of: lu ~s . S11ml3:1"ly, m • •
.~ ~y ,:is· st~red}n r,o.~ -~ d (:o l~ ~
important to ~o~ ~~ ~a~ ~.o~ ~~- ~l~ ,fo ~l t ~.s. als~
~~~~s. ~~-~ d~~b~e ~~~s1~n array
niere are two me th~ s ·for. are ~tore~ 1n·memory. sto ~g ~ult1d1mens1onal arrays
· n-ma11·or order •-• • • 1n memory: Row-ma1or. order and
1
C0
1um
11 .. ~ .!, ~ ··• ·· - • • ,. ; • , • · : • ·• ·


~
• • •
. 1 • • • ,. ~ ,. ; •• -· •
. • •• !' • .. ,, . .' •' "• ,• .
• •
..
~ ~ . • •
,; ~

(;°_~);-',:..Y3','' ••
-~ ' \ ,. t t. • • ' ,-l ', • ...
' • •
. • . • ..

.
I .. •

er
1S,' - - ~ • • : ' . - . ! O , -. '
rd ' . f ..
~
1 l • • ...
' • I
. .~ , ! , ·; , ' ' •
• ' • '• I • • •
,¥.~:.J: .:,",,;, ,~'~_,.;,:,,. ... 1 ~ . •
• • • • ' ' ' •. °: f
,', •
' • 1 •
' •, l ,l • • • ~ 1 •
j
' ~ ,\I
, •r •• .•
l • ,. • t' .• i_ •
In row-major order; a· inultidimenSion
• ,, ,\., ', ., t "

al an'aY-llr linear· Memory is aCCeSSed ·such '

rows that
. th~- othei] Clanguag~ 'use
tre stored one after s· 'th e. iow-major ·order inethod to\ st~Je array
e1cinents and, therefore, termed as the C-orde .
r. The pictorial representation of the row . ' .. ' ...
"'-,•


'ollo
llfO .
ffi'J •
1
' . •
.
-major order is
-,
. .

'
,,
I

\
'


~•
.. .
i . •
1,
~,
:
► "-~.
'

,
·I .... ..
.
' .

l

:· •
'•
0( • • • \'
• ~\ ... \ ••
h
6 \ l
'
' ~ •
~
• 'I. ., \ ,' • : r ,,
~
\
r• t , ,.
• ' ,- ,
, ' ~,• •• a,
• • • \.
.' .. t . , \, , \ ,_ ~ll \ • • • '
.\ " . r -~ ._ .
I•

l i .

• ,N

_; ~-.'t\
. . ., >.. ·--~t:;.,. ~, ~

. . .

II■■ '.

"' '
I 'I • •
I' •• •

. .'
I • \ •

•.
... ,., \
1
, ~ 'l ·• ~ t

~
~
·,
..

~~~~
.. ' • l • , '\ ... t . .,_ • ~ ':_ ~ ...; " ,,.
9
~
0
~~ ~~ Fl -....•......:~-~....R~... ""~IU•IIIWI• .. r,, ,...
.........
: •:•..... ::aM
.... ,....,.... ~-·~.H
, -~,--,·........,:i'l:re••-· ...
•:............_,..14.........
· :...
: ~ ......- - , \
• al yelement
then
s are allocated in llletn
element s of 2nd row Ot,,, lt •
Above figure shows how tw~en sion arra
that initian)' elements of first row are stored in memory . <lild so ~lat\
0
consider the following example to illu5ttate th~concept. •~
vforexample •

l 2 3] . ·a·oro ~as: {1, 2, 3, 4, 5, 6}


4 5 6 is represente~ m ~e row-m g ,

n:~
-inffl.--: o~ Order .
nsional
.
array in
.
linear memory
.
1s accessed such that
)1-•R .......Z!~=-::~~·- - • • . .
{!it Column-major order, amulti:iR.AN programming langu~ge uses the methOd of Coli
are stored one after the oth~The p. ORTRAN order. The pictonal representation of the Colt
major order and is also tenned as the F . . . . • . Cob
1
major order is as follows :L--r .--~~ +.--- r---i-
, >,;:~ ;"·t.~~;" ,:{:
...: ;> •! ~ ~\".' <, ~1
~ ~'< :._:Jit'~ ,:. ~-,.

O 1 2 3

• -' I ◄
• I

• • • t

.
I •

I
,o ' 0 I

• ·L.-- -~~~ ~~--- --=-: -:-:~ ~~~- ------ -~


• . • • Fig. 7.9. Column-major ord~r . . . •
• , •
1 " • f ',
'

, . Above di~ sh~~s how twerdiinensional amly ele.ments are allocated in memory. It i
that initilillJ'column-0 elements ate stored in meQl~ then column-I, column-2 and at col
elements are stored. Let us conside~: the following example to illustrate the concept.
/For example. _ . .,_
1 2 3] ' ' , - . •• 1 • l ' •

' [ 4 5 6 is represented in the ~iumh-major order as: {{4, 2, 3, 6} 5,


• I • • , , • • •
...
j • . .
/DECLARATION OF
.
TWO. DIME
, ~SIONAL ARRAYS ..

The syntax for declaring two_ dim~nsional arrays is : · · .


~torage_class data_type artaY- ~ [1at cUmension size] [2nd dimemion size
.
fil
Where, , .. , .
• storage_class (extern, static, auto) refers to th~ scope of array variable which is opl
• data_type re~ers to the kind of values you want to store such as int, float etc.,
• array_name 1s the name of the array, , . . ·
st th total 1
• 1 dimension size refers to the total rows and 2nd dim • . • &. e
of two dimensional arrays.. ens1on size re,ers to
.
• Note that dim~nsi~n siz.e mlJSt be any positive values and It also be de.fiPed I
preprocessor directive #de~. can
i, ExaJJJple. int an-[4] [3]; Here 18
!:a-.

· t data type• wa, • array with three rows and four cols and
a doubJe dimens1on
js of JJ1

0 1 2

0
1 l 15 13 I
2 7 19 70 I I

3 77 5 9 I

45 16 • II
· . • ·8• •
Jndex number m two dimensional arra s 1• . •. I
~ J
I

ai,ove table shows Row number as o, I, , :e one dimen s10nal array, starts with 0. Therefore,
2
coJUJIIIIS· or four rows, column number as 0, 1 and 2 for three

As it is clear from the above table thathi~y arr[41[31contai.ns total 12
roduct of row and column i e 3* elements. Actually, it is
•• 4 w c is 12• Therefore, you can store total 12 values as per
tbe P d ciaration •
abOve e •
dimen
one also sional array every valuete1ement is•
. like,
Just al arrays so ~ bo

.referred by index number in two-
diJnens1on ' or a ve example we have'
arr[O][O] = 10 arr[OJ [1] =15 arr[O] [2] = 13. ·
arr[l] [OJ = 7 arr[lJ .[l] =19 . arr[l] [2] = 70 -
.
[1] =5 • , arr[2J [2] =9
'

arr[2] [OJ= 77 . arr[2]


arr[3J [OJ= 45 f i'~ arr[3] [1] = 8 arr[3] [2] =1.6
.
This is
Total memory allocated for above array named arr as per above declaration is 24 bytes.
take 24 bytes.
1,ecause there are total 12 elements, each being int, takes 2 bytes. So, in total, arr will
Some valid declarations of two dimensional arrays are:
float marks[2] [4] ; l '

char names[5][20J ;
;INITIALIZATION OF TWO DIMENSl9NAL ARRAYS
[be syntax is: •
nd
•- •
nt list 0
storage_class data_type array_name[tst dimension size][2 dimension si7.e]={eleme
cTwo dimensional arrays can be initialized in following ways: ••
int arr[2] [3] = { 10,15, 20, 7, 13, 9};
/4 above initialization can also be written as
int arr[2J [3] = {
◄ --lst
{10, 15, 20}, -4-
{ 7, 13, 9} ◄ 2n4 •

J; 1 1 1
1st 2nd 3rd
Co lum n
b[r1{2J==a[i][jJ; •
.. l++• /*put non-zero element at array b[r][2J i e
•. th·
J ' /*increments r, to move to next colullln .,., . Ir~\:
Printf(''\np
ti . . ackec1 Storage is :\n"); .
Or(t:::()• I<r 1• • • .
. f ., ' . ; ++) /* r for n~n-zero ente_.n__·e_~...,;I_,·----..:.:_
. .. .
Output:
for(j=O; j<3 ; j++) • . • : I •

Enter number of rows clrld


Printf("%d\t",b[iJ[j]);
Enter 16 elements o f ~Coli: 1
prlntf(''\n"); 12 : 0 • 6 o
}
getchO;· ~
22 0 0 o
}
t
·o 16 3 0
0 0 0 7
Packed Storage is
• 4 4 6
0 0 12
0 2 6
1 1 22
2 1 16
2 2
... • f. ; . . . .{

. . 3 3
3
7

... _ . .ExplariatioJL Above c~, creates _s~~e.lllatrix from 4><4 matrix: Ini~ai!Y, statement~
: " checks ~~[i)~~!. != Oand _incremen~ ~ 1f 1~ 1~ true and f~r the sec?nd ~e tf ~!~~sames~
!l·~:' true t1ien assignment statements .executed. b[O][O]=m 1_s used to store number of rows in .
: ·'. Jrultrix, ..b[OJ[1J=n is u~ t0 'store number of columns of original matrix, and b[0)[2J=nzis
.
•store number of non uro entries. of original matrix in b. • . . ·..
• ••• • ~~-~wiMEN.P./siONAL
!!m.......,~,.,,.,,,..__
ARRAvs. , •
,,.,,.c,,,.. . • .

•. •. :.. As,~e'fui~e. di~ussec€vo dimensi0nal ~~ys c~mes Ullder m~ItidimenSional arra~ .


• Therefore, multidimensional arrays may be larger than two dimensions also. To d~lare am~
than two dimensional, say, three dimension~ arrays 3-pair of square brackets is µsed~ The s
• • , \ ( ' Iii ,. ' t . ... ... ·, • , ,

declaring n- dimensional arrays is as follows:· •• • . • •..• • · ·


storage_class data_type array_name[ 1st dimension size] [2°d dimension size] [3rd dimensd
• .
Where,
)· storage_class (extern, static, "auto) refers to the scope of array variable which is
• .
}.- data_type refers to the kind of values you want to store such as int,' float etc., .
; a~ay_name is the name of the array, 1st, 2nd and 3rd dimension is· to used to define~
.perfonn som~ caJculations. , . _·. •
.. } ~ime~sion size must be any posi~ve values and it can also be defined by using pre
•~~ ,~~~~~
.~-. ~
- - -
--
--·--~_,,...........,,.,-.::Z:.::_.
._ I
- ..~, . ,,.
......-,.... ,. ~ . ~ - - -..
...._
,_ - *"'"•••
-
41iUht<cMloc:W: i 't.._C't, "( JHN"'1 --~•"""'•M1~~1Uf• .. .-..-i,,..,.·w·;p,..._8't• a. . . .
• ..._,.
JBD
L:.:~
• 'IUIIID.-ffl---~~'
...,:_;..&V
.. --~
~
Let us· discuss an exarnp•Je •or decJ . aration of th
jJlt arr[5][4][3]; ree -dim ensional arrays is: •
t1ere, arr is an array name of lilt . ,
dat a . l

. ,
P
[5][5]· type Whose • '.18 it can store total 60 elements.
Ar ~P le. mt an-I [5] ' size 5x4 x3 i.e.
v-- float arr2[S . .
][5][4][4]- • ~ ~ • .. •

exa mple array arr J . ' , . . 1• , • •

,,. our is a 3D . .• . ,
JP
ege r typ e eleme nts A (A 3D array is ys of arrays.) array which can
d 125 int
nin • nd array arr . an array of arra
i,ol ts In c prograJtu 2 ting-point
el~eP~ of array, a

sin
. g
we Dee d to
1 array can hold tho !•
dec lare s:~ e
4
a D ~ y which can hold_ 400 floa integers)
raI vanables (for example .to, store 150
1,Ut ill De el
&ration and lnitializa . usands of values. , . . .
JloW to n 3Df Array. Before·we discuss it let us have a look of 3D
tioay
A3D array can be assumed as .an arr • array (collection) of 2D arrays
,rraY• • array of ID arrays of arrays, it
0 • 1s
you know 2D. array itseIf ts t can help
How it so? Let us see a diagram tha
_..,1
Ill" as arra y.
you to understand ~s . . • •
. .. . · 1 ·····•·· ....

I --2_J____ 3 j ". dh 2-d array


-,-
· · ·•~·•.......__ .
!
11
I
12 11 1'i·]••. ····t 2-d ar.ray
• ' ..............~ ..,
nd
; :2 l 22 ?
-
3 " 2 2-d array
t ..................... ........................................
! :

.t..1 24 2s 26
.........................................................
r-··

'. 27 . 28 I 29
............ ........1
............ ............ ............

F!g. 7.16. Initialization of, 3D array


3D Array Conc~ptu~ View . .
ay of 2~d._arrays. • •
. No~ ~t , ~ ~ y is ~~~y .a~ arr .
, ·, · t'h 2- d ari:-ay , : ,
·. 2~ -d ~a rr ay :-.
<f 2- ar ra y
O.. ~-·6.5. Uj·- ~
~ n f ~·-·· · · · · -· . !!!.~[·-··s J_. ~-C
~~~
2 J .T4 ~s s'[-
. . . . . . .6-.,-[
·9·
. . . . . 1T-
. . . . . ."'
· l
· Tf"
· · · . :·
"" 1016 10Is 1020 1022 1024 ·rn2?"Hi"2·s· loif ·To3"
... . . 1014
JL.11012 __
]lJ°
. . . . . . J14
. . . . . . ··J1
..J.
s·. [ 16 1 ] 18]i'
19 fojf 121
21. ·iro·s 23f 14] isr 26127 28 '29
L1ll32
"103

·rn4
·0· To4
2· - r o ~
L r o
° 4 6
· H > 4
i 1

0
,

, 1006 o o s
1010
Memory locations •·. · ..~ . J ·: tv1emory locations • ~. • ,
Memory
.,
locaflons .
resentatlo"' . ~J : _.. "c·~ . , .~../ ··.,~ . :• -'--
Fig. 7.17. 3-0 array memory rep r \ ' 1 • II' , ~I

~y ~ther v~able ,or amly, by



I
~
'\.#
t

the com pil~ .~im~. as we


initial!ze
We can initialize a 3D array at

we
i

ized 3D array con tains gar bag e v~ ue. ~t 's see a·~omplete.e~m,ipte:.on.~~w
defaultan'un:initial
• •\, ... ..,
' ' • , ,.
f ..
t ,1; 1,, a....
,· ' I
i :
,• , 1 'f l , • , /

~
• t • ;
: _', ·,
can w~ ~th ~ •3~ array~• , i• . •,. • ,
. . ., . .. .. . . . . .
I .

ay thr et: dim ens ion al arr ay s 1

Program 7.53~ To d,ispl


.) . i
t f , '~

.
• J,
I

' I

' I

. ..
' ' _r . I

I •
..
t .,

You might also like