Array
Array
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 ' •
•
~;
~ ••
~
1
I • •
~,
~
' · •• ,......... ,._.. _____ >-.,-.◄ ·~--
,~.,.t
•
l ••
•
-.
, '-'.
~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 '
::, '•,
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
.__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 ,
eJP square br~ckets represents total number of elements required. exp is ariy expression with
in
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
stored. ' <' • ' ' ) ' . • ' . ' ·, ' i . ' ). "' ,. .. . .. . ' f l' ... • , • I f \. • •• 1! ' ' • •, . - • I :I :
Contiguous
memory · .,___
locations
. . .
. .. .., ..
~" -
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. . . . • • • • • • !
,.
' ,. ' .
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
•·: • •• •~ ' • • •
I
• ·
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:.~· :~_-{. .>).· _·;·; •
{ , I ~
·, .... l
'
(
\
\
-.
• I
}
,
.• . .~ . ' '
. Here, Array size N is defmed using symbolic const4nt using #. defin~ p~ep~~e~sor ~ective.
JI char name[ ~={ 'v', 'a', 's', 'u'}; , • • -
•
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, •
• • •,, ••
\)'.' 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• . • • • ' , • •
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, • • •
__ ~t
·v .
~~J~; •• · •• : ",' ; Ask user to enter value o~ n ~o tell how many elCllleQls I
·· . , clrscr(
. ,
); ~ . .. ... -r . . ' ....-.~-.
'
~-.-.-------
. . .· .
user want to input• , •::- ~ . .,. ~ - ; > r • .- • • • • • • •
. '
'
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
.
t
. ' ! ••
I I
I
'
•
. I• •
, (
. . ,. .
, • I'
. •• !lo l ... ' .. '
.
}
~
htD=n/(sum); I' I
..
1
:):_;_ .. -- ~ -~ -- -_ _ ;~
getchO; -- -- -- -- ,
Output - 1 ,. • • • • , •• \ • •
} Total eieme~~ to be entered are? (N
ot more than 15): 4
Enter 4 elements . . \
~.....i::it...,,.,~,;.-..,.,.,'¥~·v.,>,o'>.·,,;·. J
-
• , ~
. . t also supports two dimen~io~ai.
'
,. I • '
1
•
.
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 "
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 •
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
, . 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 ' •
· 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
'
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 •
. . 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,,,.. . • .
. ,
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]- • ~ ~ • .. •
,,. 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 ·····•·· ....
.t..1 24 2s 26
.........................................................
r-··
'. 27 . 28 I 29
............ ........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
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 .
.
• J,
I
' I
' I
. ..
' ' _r . I
I •
..
t .,