You are on page 1of 14

Chapter 2

==== ==== ==== = ARRAYS & STRINGS

2.1 Introduction
Programs v~?' often deal with multiple data items possessing common characteristics. ln
such cas~s, it rs often convenient to place the data items in an array . so that thev all share
a common name. In this data structure, all the elements are stored in contiguous l~cations of
memory.

~ n array is a finite, ~rdered and collection of homogeneous data el~nJ~Q tS. Array is finite
because it contains only limited number of elements· and ordered as all the elements are
. ' '
stored one by one in contiguous locations of computer memory in a linear ordered fa shion.
All the elements of an array are of the same data type only and hence it is tenned as
collection of homogeneous elements. Follo~ing are some examples: ·
i) An array of integers to store the age of all students in a class.
ii) An array of strings to store the name of all employees in an organization . .

2.2 Terminolo gy
Size Number of elements in an array is called the siz.e of the array. It is also alternatively
termed as length or dimen:iion.

Type Type of an array represents the ·kind of data type it is meant for. For example,
array of integers, array of character strings, etc.

Base Base of an a:rray is the address of memory location where the first element in the
array is located.

Index : All the elements in an array can be referenced by a subscript like a, or a[i] , this
subscript is known as index. Index is always an integer value. As each array
elements is identified by a subscript or index that is why an array element is also
termed as subscripted or indexed variable.

Range of index: lndiGes of array elements may change from a lower bound (0) to an upper
bound (u-1 ), which are called the qoundaries of an array.
~2.~2~*~
' ~D~a~ta~S~t!:ru~c~turl!!!_e~s~Uf!_s!!_in~g~C::___________~-.~----..__
. f ent In each memory location. computer can
W ord : -Word
· denotes the sized o. an e Iem This· word size
. vanes
. · ftom
_ mach111e
. to machine
.
store an elementofwor size w, say. . ·

2.3 One-Dimensional Array


·: · . -. d • ·red to reference' al I the elements in an array then the
If only one subscript 1 m ex .1s requi
. ·mple an array For an examp 1e ·
1
array will be termed as one-d1mens1ona array or si · ' .

int a[50];
st
where a is the name of the array, int represents th~ type of data to be ored in .array
elements, 50 represents the maximum number of values to be stored.
' '

The above definition.in C impiies that any number Oto 49 is a valid index of the array a. Thus,
a[O] means the 0th element of a. a[5] represents the 5th element and so on. However, a[SS]
does·not represent a valid component of a because the index (i.e. 55) is beyond the range of
indices specified in the definition .
2.3.l Memory Allocation for an Array
- I •

Meml ./ repres,entation of a11 ar~ay is very simple. Because, computer memory is linear, an
one-dimensional array can.b e.mapped onto 'the memory cells in .a straight forwar_d manner.
Since the eleme.1ts of an array are sto,red in contiguous locations of memory,-the storage for
element a[i+ 1] will be adjacent to storage for ele~ent a[i] for i = 0 .. . n-2.
I '

Let the memory !~cation where the fiTst element can be stored is b. If each element requires
1
one word then·the location for any element, say a[i], in the array can be obtained as ·
address (a[il) = b + ix w, where w is the word size.
a[O] · a[ 1] a[2] a[3] ·a[4] a[5] a[6] a[7]
Memory :ells I I .I j
16 18 20 22 24 26 28 30
. Figure 2.1 Memory Allocation for an Array of integers with w =2
For ~xarnple, consider the array a[ IO] and b is the address of a[O]. and w = 2. Then the
location of a[7] can be computed by · .

b + 7x 2 · that is, b + 14
Figure 2.1 shows memory allocation t~r an array of integers with width two bytes.
· Arrays & Strings* 2.3
2.3.2 Operations on arrays
Various operations that can be perft d •
. . . orme on an array: traversmg, sorting searching insertion
deletion, mergmg. ' , ,
2.3.3 Traversing _

This operation is used to visit all t/1e elements in an array.

void TraverseArr ay (int a[], int n)


{
inti;
for (i=O; i<n; i++)
process (a[i]);
}

where processO is a function which when called for an element can perform an action.
2.3.4 Sorting ·
This operation will sort the array in a specified order (ascending/ descending). The following
function is used to store the elements of an integer array in ascending order.

void SortArray (int a[], int n)


{
int i, j , temp;
for (i=O; i<n-1; i++)
{
for U= i+1; j<n; j++)
{
if ( a[i] > a[j])
{
temp= a[i];
a[i] = afj];
afj] = temp;
}

}
}
2.3.5 Searching
This operation is applied to search an element in an array.
int SequentialSearch(int a[], int n, int k)
{
int i;
for (i = O;i < n;i++)
{
if (k == a[i])
return (i);
}
return (-1 );
}

2.3.6 Insertion
__not ful l.
This operation is used to insert an element into an array provided that the array_is
·
Figure 2.2 shows insertion of an element to an array.
void insertArraf(iri"t a[], irit n, int pos, int num)
{ I •

int i;
for (i = n-1; i > pos; i--)
a[i] = a[i - 1];
a[pos] = num;
}

a[ O]
.
.
.
Push down one / I/ Element is to be
stroke to make a , ..
(
'" inserted here
/

room for the new


element to be
~
inserted .
.
C .
C a[n -1]
Figure 2.2 Insertion of an element to an array
Arrr.zys ~ Strings * 2.5
2.3. 7 Deletion

This operation is used to delete a particular element from an array. For example, ifpos = 3,
the value of a[3] will be deleted.
void DeleteArray (int a[], int n, int pos)
{
inti;
for (i = pos; i < n; i++)
afi] = afi+1 ];
n = n-1 ·,
}

~----1
f--- Element is to be deleted

Push up each
element (after the
victim element) by
one position

Figure 2.3 Deletion of an element to an array

2.3.8 Merging
Merging is an operation when we need to compact the elements from two different arrays in
to a single array. Figure 2.4 ~hows merging of two arrays.
void MergeArray ((int af ], int m, int bf], int cf], int n)
{
int i, j;
j = O;
for (i = O; i < m, i++) ·
{
cU] = af iJ;
j = j+1
}
for(i = O; i < n, i++)
{
cU] = bf iJ ;
j = j+1
}
}
2.6 * Data Structures Using C -
a ·
C

m elements from a

size (a) =m I ...._


... -
- .......
b n elements from b
.

..
size (c) =.- m + ,,
.

size (b) = n

Figure 2.4 Merging of arrays a and b to array c


- *~D~a~t~a~St~r~uc~tul!!_.r~
~2-~8~ ·U
e5:__~'s::i~ng~C
~-·- - - - - - - - - - - - - ~
· F. '1 7
Column major representation of a[3][4] is shown 111 -igure £., . •

a [0][2] a [0][3 ]
a [O][O] a [O][l)

t t t i
a [1][2] .a [ I ][3 ]
a[l][0] a [1)[1]

t t t ·i .
'.
a [2][1] · a [2][2] a [2][31
a [2][0]

Figure 2.7 Column major representation


Figure 2.8 (a) and (b) shows storage representation of two dimensional array in row-major
and column-major order respectively.

RowO
a[0][0l
a[O](l]
.__--1
(:--bas e(a) . .
ColumnO
a[0][0]
a[l][O]
-- (:--ba se (a)

a[0][2] a[2][0]
a[0][3]
a[l](O]
Ja[O](l]
Column / , a[l][l] ·

Row I Ja[l ](l]


. . l d(l][2]
l a[2][1] · - ~
a[0][2]
. a[I ][3] Column2 a[1][2]
a[2][0] a[2][2]
-+-- 4-
Row 2 a[2][I] . a[0][3]
a[2][2] Column 3 a[l ][3] .
a[2][3] a[2][3] I

Fi~ure t.8 (a) Figure 2.8 (b)

Storage Represent~tion in Storage Representation in


row-major order column-major order
(row-by-row) (column-by-column)
Ch ap ter 4

~ = = = = = SPARSE MATRIX AND POLYNOMIALS

.1
4 In tro du cti on
The t!_o important applications of arrays
and linked list ar; - sparse matrix and pol
yno mia ls.
arse matrix is a ma trix mo st of wh ose ele
5 ments are zero. A spa rse matrix can also
l;s ent ed by using arrays and linked lists be
. Various operation~ like addition and mu
:; be performed usi ng dif fer ent repres ltip\ication
entations.
A olynomial is ma de _of dif fer ent ter~ s,
each of which consists of a coefficien
e~ nen!:,.T his cha pte r ~nc t and an
ludes the represent
ifsts' and various operations performed on theatio n of polynomia ls thro ugh arrays and link
se polynomials.
ecl"

4.2 Sparse Matrices


A matrix is a ma the ma tica l obj ect wh ich
arises in many phy sical problems. In
science, we are inte com put er
res ted in stu dyi ng wa ys to represent ma
tric es so tha t the ope rati ons to be
performed on the m can be car ried out
efficiently . A gen era l n~atrix con sist of
m row s and n
columns. Fig ure 4.1 sho ws exa mp le of
two matrices.
Col 0 Co l\ Col 2 Col 3 Co \4
Ro wO 5 10 15 20 25
a = Ro w 1 4 11 14 17 12 is a 4 x 5 ma trix
Ro w 2 34 22 13 16 -6
Ro w 3 17 26 38 51 43
Co I O Co I 1 · Co I 2 Col 3 Co \ 4 Col 5
RowO
Row 1 -7
0
0
1
--" '
0
9 --
0
1 0
0
.,
2
0
b == Row 2
Row 3
0
0
0
0
0
0 - 7
0
0
0
0
0
is a 6 x 6 matri2<

Row4
Row 5 -
8
0
0
0
0
-3,_
0
0
0
0
0
0
Figure 4.1 -Matrices
4.2 :tit Data Structures
Using C .
~
lum ns an d th e m atrix b has six rows and s i xun-in s
ws and five co · na I array, say, a[ m][n ]. Then w
.
The matrix, a has four ro · · d'11 ne ns 1o
a matrix 111 a two w~ can
It· is very natural to store ], an d th is elem en t can be found quickly. No
writing a[ i]U \· f we
work with any element by en ts ar e ze ro . Su e 1 a matrix is called
that many of the el em ~~~' Se
look for matrix b, we see sp ar se m atr ix , bu t it is a concept which we
definiti on of ar
matrix. There is no precise 1e nt on l 8 el em ents are non-zero .
matrix bout of 3
recognize intuitively. In
te rn at iv e fo rm of re pr esentation. This coin es ou1
to consider an al . are large ·e.g. I 000 x
A sparse matrix requires . we want to deal with
ac tic e m an y of the m at rices .,,. . le element10oo '
becaus e in pr 1011 po ssib
e th ey ar e sp ar se , say, only I000 out of once m1 I . representafs are
t at the sa m e tim . tem at1 ve
bu
tag e of m em or y sp ac e, we reqwre. ior.an a ion
'
av oid th e w as
non-zero.. To · ,
of the m at nx .
. the non-zero_ elements
we exphc1tJy store only yi .
id en tifie d by row
its and column position, sa ,} , We
is uniq ue ly
Each element of a matrix . . ·

sto re a m at

rix as a lis t of 3-tuples of.the form
might then
(i,J, value). m
is list of3- tupl es in soine way, perhaps placing the
to organize th at all the 3-tuples of a~o
Also it might be helpful
that the row numbers are
in increasing order.
cr~a
W e
sin
ca
g
n
o~
als
de
o
r.
re
Th
qu
us
ire
,
th
we might store the matrix r
columns are in in is shown
row be stored so that the r of no n-ze ro. el em ents ofthe matrix. This
re 8 is the n~m be
in the array b[9][3], whe ·
in Fi gure 4.2

0 I 2

b[O][ 6 6 8
' .~
b[ I] [ 0 0 7
.., I
b[2][ 0 J

b[3][ 0 5 2
b[4][ I I

.h[S][ I 2 9
b[6][ 2 3 7
b[7][ 4 0 8
b[8][ 5 2 3

Figure 4.2 Sp arse m atrix stored as triples


._'
the nu m be r of row s and columns of the spa
d b[O][ I] contain ents in
The _elements ?[O][Oj an 0] [2 ] co ntai ns the nuniber of nonzero elem
e eleme; t b[
matnx respectively. Th -
sparse matrix.
trices.
perfo rm ed on this tri ples representation of ma
operations
The following are some
Sparse matrix and polynomials * 4·.3
1 Transpose of a sparse matrix
4.2.
This is where·we move the el~ments so that the element
in the i, J position gets put in the},
. sitiQ!l• Anothe~ w~y o~ say mg that we are i?terchangin
g rows and columns. The elements
?th e diagonal will rema1ry unchanged, Since i =j.
The transpose ~f the matrix b is stored in array c, which
is shown in Figure 4.3.
0 I 2 ·
c[O][ 6 6 8
c[1][ 0 0 7
- ·4
c[2][ 0 8
c[3][ I I
c[4][ 2 I 9
c[5][ 2 5 3 ' ..)

c[6][ 3 0
c[7][ 3 2 7
c[8][ 5 0 2
Figure 4.3 Transpose of & sparsa matrix
Since b is organized_by row, _the first idea for transpose
algorithm might be
for.each row i
{ . ' ': . '
,,

take element (i, j, value) and


store it in U, i, value) of.the tr~nspo~e .
}
The difficulty in_this approach is that we are not kno
wing where to p,ut.the eleme1i.t' (j, · i, ,
value) until all other elements which precede it.have been
processed. Ifwe'jµ~t pla:c_e t~em ..
consecutively, then we will force to move elements dow
n very often:•WP. can avoid this data
movement by finding the elements in the order we wan
.
t. them. · ·
for all element in column j
{
place element (i, j, value) in position U, i, value)
} ·'

The data structure for the sparse matrix is

int smatrix[terms+1 ][3];

wnuherbe terms is the number of non-zero elements. Sinc


rn er e, we require· to stor~ the values. for
rn . 0 f rows, number of columns, and number of non ·
-zero elements in the 0th row of the
atnx, so we require terms+ I number of rows.
s UsingC .

(4
* Data Structure
a r s e mat
rix
ranspo. se o f a sp
4·1 T
Progra·m
stdio :h>
#include<
stdlib .h>
#include< .
efine N T ERM 100 . .
#d t [][31);
lnp utM airix(in
t [][3], in t [][31),
void st in
atr_ix(con {31);
n sp o se M [1
void Tra M atrix (const int
p la y
. void Dis ()
void ma in
~
[~);
{ [NTERMJ
J[3 }, mat2
.

[N T E R M
int mat1
clrscr();
u tM a trix (mat1 );
lnp t1, ·mat2);
M a trix (m a
Transpose atrix is .. ,InIn");
Sparse m · ·
printf("In Inatrix(mat1 );
..
<t

, DisptayM e m a trix is... \n\n");


T r a n i,p osed Spars.
rintf/a("ylnMlnatrix(mat2);
· Pis .

D p . .
} i

tM a trix ( in t mat[)/31).
Void lnpu .

{
int i; '
the .. ."
w s in );
I
r the number o f ro matrix.
Ente
. printf("ln ", &mat[O)[O)); .
a n f( " % d r o f c
• sc
E nter th e num b e
the m atrix ·• ")·.
Printf("ln olumns in
0
" &mat[0)(1 ))
sc.ani("¾dn,ter the numb'e n t . s .i n the matrix• ");
nn tr( ''. ln E ze ro e ne
P r no.n. .
" ", &mat[OJ[2i+) +) );
sca1-1 ;%
~ f( d at[0)[2] ·
'"'"m '
for( .
{ .

"\n En te r the .
Printf(
t;ow n umber : ");
", &ma [OJ),
scanf("%~d []
Printi("\ ncnter the co/ m b e r : " );
· n n u
r< '%d ", & mat {i}[1u1)m
,
scantf('\n~
Prin a/ . rr
en'' te&r the V ue • );
scanf("o/,.0 d , rnatfi)f2JJ; .
} J ·
- .
void TransposeMatrix( con st int mat1 [J[ J•t
Sparse matrix and polynomials * 4.5
{ . 3 , in mat2[1[3J)
int i, j, ·k, m, n, t;
m = mat1 [OJ[OJ;
n = mat1 [01[1 J;
t = matt[0][2];
mat2[0J[O] = n;
mat2[0][1] = m;
mat2[01[2] = t;
k =1; .
for U=O; j<,t·j++) Jr;. I
for(i=1 · 'i<=f: i++) t. -;:. '
'. t '
if(mat1 [11[1] == j) ~akl C.+-}[1] ;::: 1
{
I o 4- I
mat2[kJ[O] = mat1 [i][1 ];
, mat2[k][1] = mat1 [i][O];
mat2[k][2] = mat1 [i][2J;
k++ '· ?._.
}
}
void DisplayMatrix(const int mat[][3])
{
int i, t;
t = mat[0][2];
printf("\t \t%d\t%d\t%d\n", 0, 1, 2);
printf("\t·-~-------\n");
for(i=O· i<=f i++)
f I I
.. ..· · . .
printf("\t[%d1[\t%d\t%d\t%d\n", i, mat[i][O], mat[i][1], mat[i][2]);
printf("\n");
}

Output

Enter the number of rows in the matrix : 7


Enter the number of columns in the matrix : 7
Enter the number.non zero entries in the matrix : 6
Enter the row number : o
Enter the column number : 5
Ente·r the value : 1
Contd...
4.6 * Data Structures Using C
Enter the row number : 1
Enter the column number : 4
Enter the value : 1
Enter the row number : 3
Enter the column number : 4
Enter the value : 3
Enter the row number : 4
Enter the column number : 1
Enter the value : 2
Enter the row number : 5
Enter the coiumn number : 4
Enter the value : 4 ' ' .
'
Enter the row number : 6
Enter the column number : 4
Enter the value : 2
Sparse matrix is ...
0 1 2

[OJ[ 7 7 6
[1 )[ 0 5 1
. [2][° 1 4 1·
[3][ 3 4 3
[4][ 4 .1 2
[5)[ 5 4 .4
[6][ 6 4 2

Transposed Sparse matrix is ...

0 1 2

[O][ 7 7 6
[1 ][ 1 4 2
[2][ 4 1 1
[3][ 4_ 3 3
[4][ 4 5 4
[5][ 4 6 2
[6][ 5 0 1
es had bee
The matrix transpose function has a computing time of O(nt) . In case the matric
of an n x.
represented as two·dimensional arrays, we could have obtained the transpose · n WI
matrix in time O(nm). But this O(nt) time for the sparse matrix transpo~e functw
'.
\

become O(n m ) w he n ti s of th e·or


2
.. Sparse matrix an d polynomials * '4.7
-

de r ,nn (i.e. a\l th e el em en ts ar e no


worse th an th e O (n m ) tim e us in g n- ze ro ) Th is w ilt be
~ o dimensional arrays. .- · . -.·.-,
· · .-, ·
.We ca n in fa ct tr an sp os e a m at rix
re pr es en te d as ,a se qu en ~e of trip~
function fo r th is fast' al go rit hm pr ~s i~· !im e _ O(n+t). Th e·
oc ee ds by first de te rm in_in g ~he nu
column of th e m at ri~ . Th is gi ye s m be r-o f el ~~ en ts in ea ch .
th e nu m be r-o f elernentsdn e.~~h _ ro
~ of tra !) sp os e 1natrix. .
There ar e fo ur lo op s in FastTran
,

tively. Ea ch ite ra tio n of th e lo op


spose() w hi ch ar e. exectiti~.f n: ~t, ii-1.
.
• .~: • t~

s .ta ke s o~ly a co ns ta nt ·a m ou nt of
• ••
-

a~1~
'
ft i~ es -re sp ec -
t .

.

magnitude is O (n + t). Th e co m pu tit pe ,' s ·o th e or de r of


tin g tim e of O(n+t) be c9 m ei( O(n-
of nn1. Th is is sa m e as w ~e n tw o -d im ,,;) .w he n ti s of th e or de r
en si on al ar ra ys w e.r e in ~s e F. as
more sp ac e. . tT ra ns po s; re qu ire s_

You might also like