Chapter 2
Chapter 2
2) ARRAY
2.1 INTRODUCTION
Before defining an array just recall, what is a variable? Variable is a name given to
some memory location, in which we can store only one value at a time. Memory occupied
by a variable is always contiguous. For example, if we declare a variable of integer type it
will occupy two bytes in memory along with its value, name and a memory address, as
every variable has these compulsory features associated to it without which the
existence of a variable is not possible.
int a-10;
it will look like in memory as given below:
Location Name
10 Location Value
65524 Location
Address
Suppose we want to store the marks of 100 students in a program, it can be done
using two ways:
1. Either declare 100 variables to store marks of 100 students,
2. Or Declare an array that can store 100elements accessed using a single name.
Array is a linear data structure in which the elements are stored in a proper sequence
or linear relationship between the elements and is represented by means of sequential
memory location. All the elements are of same type.
2 7 10 Element
1 2 3 - Index
2.2
contiguous memory locations (i.e. one
ARRAY
after he
ARRAY
2.3
All the elements are stored at the element and highest "type": is the data type (int, char or float)
other). The lowest address correspond to the first
correspond to last element of the array. addres8 name': is the name of the array
"subl, sub2, ...": are number of subscripts available in an aray,
2.2 DEFINITION OF AN ARRAY which are used to specify the dimension of an array.
elements of a specific Example
" An array is a collection of homogeneous data data type (ie int s (4O]; /* one subscript so one-dim array "/
int or loat or char) that have been given a single name, which are stored a
contiguous memory locations (Le. one after the other). where int" specifies the type of the variable
Each individual element of an array is referenced by a subscripted variable, Th. "_" is the name of the array variable
subscript or an index is enclosed in brackets after array name. "[40j" is the subscript that specifies 40 elements can store in it.
Example: Note: The elements in an array start with 0, not 1, and end with one less than
In [101
value of subscript.
Data Type Array Name Subscript Since one integer value requires 2 bytes of memory : For array S, compiler reserve
" If one subscript is used, the array is known as a contiguous block of 80 bytes in memory.
one-dimensional or linear arrav.
If two subscripts are used, the array is known as
and so on. tw0-dimensional array or matrix 2 3 39
The arrays, which have two or more
subscripts, are known as
multidimensional
array. For each subscript, we use a pair of
brackets. 2000 2002 2004 2079
e.g. int a [5] (6]; /* two dimensional array have two subscripts "/
Fig. 2.1
datatype ArrayName subscript1
subscript2 2000, 2002, .... are the addresses of memory location.
2.3 ARRAY DECLARATION
Index of array starts from 0 location and ends with one less tharn value of
Before using array in a program, it subscript ie. 39.
must be declared first like
To declare an array, we other variables. Some other examples of array declaration are
must provide the following
1. Data type of
2. The name of
an array information. chart name(20];
the array (rules are same as
2. The number of variable name) float sal[20];
4. The subscripts in an array float a<5][ 10]; /*Two subscripts so two-dim array */
:
maximum value of each
So the general
from or syntax of array subscript In this two dimensional declaration of any array, data type is float, "a" is the name of
Storage_sp type name
declaration is : the array and the number of elements are the product of two subscripts ie. 5 x 10 = 50.
here [sub1] [sub2] ..,
Data type float takes 4 byte data in memory so the compiler allocates a contiguous
storage_sp": is storage class
specified which is block of 200 bytes.
optional
2.4 ARRAY ARRAY 2.5
2.4 TYPES OF ARRAY . Here datatype is integer.
There are two types of Array ArrayName is "a".
row_size is 5.
1. Linear Array
Col size is 10.
2. Non Linear Array
linear array is one Dimensional Array or
1D o 2. Three dimensional Array
1. Linear Array. Another name of
" It has three subscripts. So these are
Only one subscript is used. called 3D arrays.
nm then we declare it Syntax:
Example. If we want to store "AMRISH" in the arTay name
Datatype arrayname (space_size] [row _size] col_size]
Char nm [7]
Example:
1 2 3 4 5 6
Suppose there are 4 students and get different marks in three subjects in two house
A M R test then their marks are displayed by using 3D array as
int st (4]
" When we declare the character type array then the size should be one cell more (2 (3];
than the given data length because the Last cell should contain NULL("\0")
empty cell. students house test subjects
If we want to assign the value St |1] [1] [1]= 20, St [1] [1] (2] = 25 St [1] [1] (3] = 26
int a(5] = {20,25, 12, 3, 2} St [1] 2] (1] = 26 St [1] (2] (2] = 16 St [1] (2) [3] = 36
::
" Here we note that no extra cell is required to accommodate the data of length 5.
2. Non Linear Array :
St (4) (2] [1] = 36 St [4] (2] (2] = 29 St [4) [2] [1] = 16
2. N -Dimensional Array
Non linear Array can be categorized as
It has n size of row, column and spaces and so on.
1. Two dimensional array
2. Three dimensional array General syntax is datatype arrayname [S1]|$2] ... [Sn]
3. N dimensional array
Here SN: nth size of array.
1, Two Dimensional Array 2.5 ONE DIMENSIONAL ARRAY
These array are in the form of row and column form
" First
An array is a fixed size, collection of homogeneous data elements store under a
subscript will depict the row size and second subscript will depict the single name given by user as per their requirement. By homogeneous, we mean that it
Size. column
consists of components which are all of the same type, called element type or base type.
Syntax: And by fixed sized, we mean that the number of components is constant, and so does
datatype arrayname (row_size} (col_size] not change during the lifetime of the program execution. In arrays, a single name is able
to store different values of same type, but they must be separated by their
Example: location/index values. In array's index values will vary from zero(0) to size-1, here
int a (5||10] "size" must be an integer constant, which will remain same during the execution
Array a" with row 5 and column 10 of the program.
ARRAY ARRAY
2.9
2.8
variable in size In 3rd example, we
Remember not to specify a inteper declare and initialized an array name marksl] and assign with the
an integer constant. And "5" is an
3. "size must be in statement-1. values 55,66, .76,24,88 which will store at the locations marks|0], marks(1), marks|2],
program 2.1" size is "5"
of aray. In the declare
marks|3), marks|4].
constant. For example if we
int N=10;
Note: In 3rd example
io need to specify the array size at the time of initialization,
invalid. as it will be
int arrN]: //is during the execution of
the program assign with the size of 5.
uanable and can be change 95.3. Accessing Array Elements:
Because here "N is a
But if we declare array as As variables can be accessed
#defineN 100 using either cout or cin or using any
same way we Can acCess array. It is expression. In the
convenient to access arrav with the help of lo0p.
int arrN]; // is valid. during the execution of
An array element is accessed by
writing the identifer of the array followed by the
can never be change
Beuse here N is a Constant and s1ibscrit in square braCkets. Thus to set the 3rd
program. the following assignment is used: element of the array in program 2.1
2.5.2. Array Initialization arr(2] = 10; // will assign the value 10 tothe
inittalization means assigning a value at the time of
declaration. (i we initialize
In our
arr2)
program we are using the variable « as a
Vanable, t prevents to assign garbage values to a variable). D-B elements of the array. This variable can take subscript to refer to vari0Us
garbage value.
int a: // declarea variable &assign it with different values and hence can reter to thne
different elemernts in the array in turn. This ability to use
a10; //will assian the value 10 to a variable. makes arrays sO useful. variables as subscripts is what
We can declare &assion values at the same time known as initialization. E.g Program 2.2: Entering Data into an Array from
int a=10; // a is being declared & assigned values at the same time. (i.e) user
initialization is performed. void main)
AS we have initialized the variable in the same way we can init1alize arrays. The
syntax to initialize an array is as follow: int marks[10]; /|array declaration
1. type int i;
2. type
array_name<size]=value list separated by comma<;
array_namel]={value list separated by comma<; forli-0;i< 10;i++)
For example: {
1. int
marks(5]={55,66,
76,24,88};
2. int marks[10]-{55,66,76,24,88);
printf("Enter marks");
scanf("%od",&marks|il); // reading data from user
2. int marks[|={55,66,76,24,88);
In 19t example, we declare and initialized an array name for(i=0;i<10;i++)
the values 55,66, 76,24,88 which will store at the marks|5] and assign with
marks[3), marks|4]. locations marks|0], marks[1], marks|2),
printf("Marks in %d Subject is %d",i+1,marks{i);
In 21d example, we declare and
the values 55,66, 76,24,88 which willinitialized an array name marks[10] and assign with
store at the locations marks[0], getch);
marks|3), marksl4). In it all marks|1], marks|2),
with the values of zero (0). other locations from marks|5] to marks(9] will be initialized
LocationValue
Addres always 2002
arr(5:int Now Base " " 2002
Address Here 210
Calculation
Let "
the
consider address m0}
ml] the
shown In are In 2.54
us
name subsequentmarks case
not fg
calculate
of 2004 Wen Memory
nstored
of
23
nth are
the of is of farray
ig (a etevents
arr|0] 100
the
the element Address 2.3 allocation
35 following 2008 stored
2006 addresses ml,
the in
address
array m|3)m4]m|2] (b). all the m2 ere
address not
tarray).
he in m
Le. = for etored
of
example: where Base contiguous
are clements are dimensional
array
one o
m single in
arr[1] of
34 102 is as stored arrey
address nt
the 0uh dimensionalh 2010
shown md
base element Fig.2.4 are
element memory anywhere Fig.2.3
below stored
address +
size
arr[2] 78 104 is
in
array memory
an locations. in (This When
stored. of
of data array a elements
the contiguous m<O]
is
addresses the
array. Base type If are m1)
arr(3] 99 106 the case stored (b)
address *
(n starting memnory when in 2]
- array
1) m[3]
of tne
arr(4] an address location elemente m{4)
86 108 ARRAY
array
is is a
to declare addressAccordingly,
Base LA, Note: integer following
formula element :Now called numberassume wil
The
bytes on In AR AY
find LA[20];
Assume float Where but As LOC arrlll Now. Here Base for Here
the Where
sume the
Location an
(LA) previously
of needs (LA[k]) = we Address the C calculating is we lower UB data
of. numberstarting two above
called 100 is at
array. "w any can value
constant have the
Base memory Let is from bytes
the base
iselement to = LA calculate + bound. the elementsindex "N example
computer
the keep noted, 2 of
of(LA) LAthe address * (B) address
the defined largest of100 in
LA|5] of is 1= C elements
number
of LOC base integer
will Bytes +starting set memory
to
is of track computerlinear a Note of
will 6001 loat th e 102 th e consists 109 \00
(LA[k]) address
LA does of be 100. anindex, the
be type of by onlyelements element /Thusstarting occupied
bytes,
2and array that array is means is
Every
and array address That Length the
calculated words not called
as = the of of is vary lengthcalled of
wfollow: Base
following LA. the need LA[k] simply in starting address since is, of can
integers element that base
is per of according th e five the length
4 the by of be
(LA) Using address to LA thelements
e UB UB- address
the
as as memory keep are of
sequence memory
a anelement element upper obtained in
follow: is it formula:
+ base address integer of next when 1, or total
the second LB array
of
W trackstored to 2,size
of array th e element bound, of
float cell (K- *address the occupies (C) arr|0] LB1 from
1 3 of size the
of of of data of wi l
forLower of in the second elernent * integer array
N of
type first the addressed LA. index is and the Inconsurne array
the the type i.e . the
the address computer. stored
and element successive 2 of of LB index general If array "arr
arrayBound)
computer element of
bytes of type not
lower the the the arr|1|. at is two
locations. the explicitly
set the
LA. of of array array, of baseindex
whosefirst wil and
every Recall is element snallest by bytes.
bound For LA,
calculates memory 102*/ memory address
We length
the be
every
example denoted as: can
5
in
element that for formula stated, int
eg ) use index, 2-
0. cells. or 2.11
Now the
1or the 100. the we 10wil
we the by of
212
In in
mermory.
actual 2.6 Location Address
Value
actual This terraysmultdmensonal
ciements becaus
eiements as than
Its int La shown The
6021LOC(LAS])
LOCILA5)
LOCLA5])6001LOC(LA|
20 S5||
memory memory a23} TWO
us one
all ofarrays". are
suppose is in the artar
the considered DIMENSIONAL
seres arrav
elernents
map map (10, considered figure descrnbed 20.75 6001 600| 6001
20, that arrav cunsists LAjO
is will 25. of 4
conceptual 30, we 4*5 4
Row 1 Row O look the Each
consists
elements. in
are 60};50,40, have subarravs.
primary ofthis
(5-O
ike one ARRAY LA|1| 55.62 6005
stored two
of chapter
set
because 40 10 Col 0
thdimensional
e array, arrayoftwo Thisseries
at Fig.2.5 following Multidimensional or
contiguous more is of so and LA|2] 55.36 6009
elements clements. far
there 50 20 Col 1
the called is
: array arrays
second referred
are is array.
memory
60 Col 2
as multidimensional
defined
an
However,
a LA|3] 45.26 6013
no 30 follows: arrays
and to
rows array.
by as
locations. subsequent an a
and can The sets LA|4] 45.00 6017
columns be first
one-dimensional
ol
array
array can
described sets set
elemente have
present of of LA|5]55.00 6021
array ARRAY
arros. array
mo
o A
elements
different
arrays
makes so
set
Accessing
to arrays
by Array
2.6.3
initialization, ARRAY
In Accessing writing As
main()
void
Program for(i=0;i<row_size;it+) Note:
our arr|1]|2]
the Can one
r(i=0;i<3;i++) injt; int elementsprogram
of forlj-0;j<col_size:j++) 21ddimensi0nal ln 14 54 88 55
the be
a[3]|[4); the Array_name|i]]
1/Operate
using
array array 2u
2.3: rowaccessed
1dentifier as
useful. array. 10; =and it
Entering in we with will and
// the // 3ra
array This are the using array be4tn
array of
wil the assign
Data variableusing r column
foassign are example
declaration
in loop arraynested 56 23 24 66
accessed with
into turn. the of
can syntax the followed
variable the for the no
two This value
take array loops
is using size need
dimensional ability
as 10
different we by as according to
and i follow: the loop,
to follows.
to the use: specify
usevalues asj subscript in 78 14 76
arr[ the to
arrayvariables a An the
subscript 1|2) values
and array same
from in row_size
hence square way in
as accessed
element is
user
subscripts to array.
multidimenS1onal
can refer brackets. at
the 0 24
refer to
isvarious time
what to Thus
the of 2.15
number
Enter
90Enter80
numbernumber
Enter
70Enter60
numbernumber
Enter
50Enter
number 40
number
Enter
30
number
Enter
20
number
Enter10 2.16
Output:
getch),
printfrin). fort-O,1<Ije*)
prntf"ata
7/brio enterd
ign).:
lory-Oj<4
Jj**)
printfd|t".a<i][l): loop printfrEnter
Kan number).
wnll
dispiay
al).
data
//
in Reading
the
form
data
of
matrix from
user
ARRAY
programmers
ordering. of(not want could locations define
parameters the array Address array inthe array rowsshowns/4|/2], students, o64
possible Now (2) (1)
LocationValues
The Let
ARRAY
just same occupy base 90 50 entered
10Data
number
is
Enter120 Enternumber
Enter100
randomly is The Eachactual the and Memory
a any memory is in
which us
4x2
mapping address array table which number
functions (roWmapping element
memory columns. reiterate
100 60 20
and or function the mapping S[O|[0] 1001 6001 store
2x4 choose above. and elements below representation
same contains 70 30
most that shown
below as 110120
or location. is maps In 4 the 1
10
that that column)
consistent. memory S[o| [1] 6003 6001. students 1s
even is a is 55 memory
high not are onlyarrangement 80 40
fit mapping
etficient to roll
limited satisfies Theconceptually
stored
level this that So important as[1][0]
locations) unique 1002 6005 roll nos. of
bill, produces what That arrangement whether Two
languages to
to as in no's in
compute the
long one Dimensional
one of
there two you is, memory s|1||1]
as
above and 6007 continuous it and arTay
dimensions). as a long 70 true. column
an given
really is
use: are
at it
constraints offset as of a thenelerments
This
run was location one-dimensional
row two element
need twoS[2||0] 1003 6009 array their
unique. into chain. is and Array
functions time things
occur:
major While elements becausemarks. the in
a is (that
and linear a in a
ordering thereHowever, will function s|2]|1] 6011 Assume marks
with
tw o the is , 65 two
in works work memory The
array array no of ordimensional
particular are
two s|3|0] 1004 6013 a
array a array in
cotumn
majorand for fine. two-dimen
two-dimensional the
a what ofalways doesn't
large any Indeed, eight entries namearrangementother,
that size you
number memory maps s[3|[1] 6015 contain array
in 85 S as
most arrayreally you input sional have
to
the b of
Row 3Row 2
Row 1 Row 0
highl1ghted 2.10
LoctA|2,
LocA{2,
LoctA{2, btes
LocIA|2,
LocA|2, To folo as
ind
address 2.64:1
find 7. 6 Here. the Let n
2<) 2) 3) 2<) 2j)
intheAferus J, LIs
5. 4 3 2 ARow 3Row 2 Row 1
Row 0 the
ofanRow
=
=6001 is
N. W,
BaseA. address be memonmemorrartay Major
6017 6001 6001 6001 - the
the the B is
address the tro-dimensional in
Figure is1 row
column the
+ + + + to total
scale is Loc of
a l ch Order
celwhi
16 2*[3*2+2] below of belocation no
2*(8]
2*[6+2] the (A
partcular if
performed factor base [ the
6019 6013 6007 6001 Col 0
cell location of L, clements
[2,
and
columns
whose address J]MNarray. 6019 6013 6007 6001 addressed
by =
Address 21onluwhose which Base location in
if address in of (A an
cell ifthe Array cells the ) A| are array
address I,
calculated
will
Jocations arrau is
to
+w|N*(I-1
are array. J]When
in
start
arr
6021 6015 6009 6003 Col 1
is be increased. the A from
location to is6021 6015 6009 6003 arranged
start fnd. ind. array two a
asfrom[OJ0,. wll
6001
)
folowW
not +(J- dimensiwithonalA and row
: Start
1|] M cach wise
xN
The isfrom
address 46023 6017 6011 6005
jlabIe
twcelo l
5023 6017) 6011 6005 Col 2 size x occupies
0, formulaarray. 3 shows
0. ARRAY
is To
th.
highlighted
To Here,
follow find elements
the
Let
index
columnMicrosoft of 2.6.4.2
an
Column
Row 4Row 3Row 2Row 1
2, Loc(A|Loc(A|
Loc(A|Loc(A|2, 2,
2Loc(A|
, 2, highlighted findToARRAY
find 6. 5. 4. 3. 2. 1. : Aincreased array Column
Minus MW,
I, Base(A),
address be aremajor BASIC) the
inthe
J,
is is is is two-dimensional element.major
2] 2|) 2|) 2]) 2|) in
stored = -the
= address
the
address the the total
the Loc ordering 6009 6001 =6001 =6001 6001
l row is
of the useordering Major Figure
below, is
column scale
no a
tolocation the (
particular column
A[ lastestFORTRAN
this Array +8 + + +
of be of
factor base the 2*14|2*|3*1213*(2 below of
performed
and the location rows , the
J]) method is
leftmost
M by as the 6001 Col 1 cell
figure. cell whose in by address = 6019 6013 6007 +-1)
Base location x
column. you and other 1 and (2,
which
Array. +
(3, onlywhose array. indexmoved to
N Address
(2-1)| 2]
2] address of (
A[I,
index
various
function if
if
ifaddress cells th e A
cell the ) When increases cell
array. +w* J| through arrays. wil
array is are in dialects locations
locations to frequently be
is increased. [M* the A
be is
location tofind. In 6021 6015 6009 6003 Col 2 calculated
find. a the
arrayA consecutive row
(J- two of
start
start fastest.
will 1
dimensional majorBASIC used
from )+ with from
as
to (I- In (e.g., to follow
M memoryordering
(0, start xN column compute (1,
0]. from 1)] older
size 4
: 1].
The xlocations. the 5023 6017 6011 6005 Col 3 The
0, formula 3 major versions the
address 0 artay.
rightmost address
address
array
is To 2.19
is a In of is
221
ARRAY
2.20 ARRAY (v) Sorting
Address will be calculated as follow : (vi) Merging
Loc(A|3, 2|) - 6001 + 2*14*2+3} 2.7.1Traversing
LocA|3, 2|) - 6001 + 2*|8 + 3| Traversing means visiting and accessing each elernent of array exactly once.
Loc(A|3, 2|) 600I + 2*|11]
LocA|3, 2)) - 6001 + 22
Values are stored and retired from array tyne variable by indicating its position in
an array.
LociA|3, 2) - 6023
Col 1 Col 2 To acceSS the elements in the array the index is varied from Lower bound to upPPer
Col 0 bound.
6009 6017
Row 0 6001 For array of size n, for loop execute n time.
6011 6019 Algorithm
Row 1 6003
6013 6021 A linear array A 1s declared with lower boundLB and upper bound UB
Row 2 6005
6007 6015 6023) Our aim is to traverse the array and apply the process to each element accessed.
Row 3
from [1, 1]. The address is UsingFor Loop:
To find the address of the cell 3, 21 if cell locations start
highlighted in the below figure and address will be calculated as follow Algorithm: TRAVERSE (A, LB, UB)
Loc(A[3, 2) = 6001 + 2*(4*(2-1) + (3-1)] Description: Here Ais a linear array with lower bound LB and upper bound UB. This
Loc(A|3, 2) = 6001l + 2* [4*1 +2) algorithm traverses array A and applies the operation PROCESS to each element of the
Loc(A|3, 2|) = 6001 + 12 arrayA.
LoctA(3, 2)) = 6013 [Initialize Counter I to LB of Arrayl
Col 1 Col 2 Col 3 Step 1: Repeat for I:=LB to UB
Row 1 6001 6009 6017 Apply PROCESS to A| I)
6011 6019
Row 2 6003 |End of For Loop]
Row 3 6005 6013) 6021 Step 2: Exit
Row 4 6007 6015 6023
Using While Loop:
Algorithm: TRAVERSE (A, LB, UB)
2.7 OPERATIONS ON ARRAY
Description: Here A is a linear array with lower bound LB and upper bound UB. Thi
As discussed in the beginning of the chapter, array is the collection of homogeneous, algorithm traverses array A and applies the operation PROCESS to each element of th
Iixed size data elements, so we can insert an element in the array only if the there exist array A.
Space in an array or delete an element will never reduce the size of the array but we will
overwrite the elements with the previous values. We can perform different operation on |Initialize Counter I to LB ]
the array as listed below: Step 1: Set I:=LB
(i) Traversing
Step 2: Repeat steps 3 and 4 while I# UB
(ii) Inserting
Step 3: Apply PROCESS to AJI|
(üi) Deleting
(iv) Searching Step 4: Increment Counter Set I:=1+1
2.22 ARRAY ARRAY
2.23
started at step 2] 20
(End while Loop 10 30
40 50 60
element. Each
Step 5: Exit
Here Array Ais traversed
starting from first
element to last
element: 70 10 20
After insertion an
30
element at end
40 50 60
processed exactly once.
2.4 Traversal
/This program
Program of Array
gets the elements of Array from the user and displavs these After insert an element at
10
Beginning
70 20 30 80 40 50 60
/
elements to the user (Traversal of Array). After Insert an element at
tinclude<stdio.h>
particular Location I.e. after 30
#include<conio.h>
Algorithm: INSERT_BEG(LA, LB, UB, ITEM)
#defineN 10 Description: Here LA is a linear array with lower bound LB and upper
tis algorithm lnsert an element ITEM at the bound UB.
void main) beginning of the linear array LA.
Step 1: [initialize counterl set I:=UB
Step 2: Repeat steps 3 and 4 while l LB
int laN]; Step 3:
int i;
[Move element to its right ] Set LA[[+1];= LA.I]
Step 4: [decrement Counter] Set I:=1-1
clrscr);
[End while]
printf"\n Enter %d element of an Array\n",N);
Step 5: [Assign value] Set LA[LB]:=ITEM
for(i=0;i<N;it+)
Step 6: Increase array sizel Set UB:=UB+1
Step 7: Exit
scanf("%d,&la|il);
Algorithm: INSERT_END(LA, LB, UB, ITEM)
printf"\n Elements of Array are "); Description: Here LA is a linear array with lower bound LB and upper bound UB.
This algorithm nsert an element ITEM at the end of the linear array LA.
forfi-0;i<N;it+)
Step 1: [Initialized counter] Set I:=UB
printf("\n %d",lail]); Step 2: [Increase Counter] Set I:=[+1
Step 3: [Assign value] Set LA[]:-ITEM
getch(); Step 4: Increase array size] Set UB:=UB+1
Step 5: Exit
2.7.2Inserting element in the Array Algorithm: INSERT LOC(LA, LB, UB, ITEM, LOC)
lnserting means adding new element in the array. Description: Here LA is a linear array with lower bound LB and upper bound UB.
Insertion of an element at the end of linear array is at the end This algorithm Insert an element ITEM at the LOC of the linear array LA.
Consider the following : Step 1: [initialize counter] set I:=UB
10 20 30 40 50 Step 2: Repeat steps 3 and 4 while I > LOC
Initial Array Step 3: [Move element to its right ] Set LA|+1}:= LA]
ARRAY ARRAY
2.25
I:=I-1
2.24 Counter] Set
[decrement
Step 4: la<loc-1]=item;
(End while] LA[LOC]:=ITEM printf( \n Elements of Array are );
Set
[Assign value) UB:=UB+1 for(i-0;i<N;i++)
Step 5: sizel Set
[Increase array
Step 6: printf(\n %d",la[il);
Exit
Step 7:
the user
and gets one another getch);
Program 2.5 Array from
elements of
N-1
progTam gets the
/* This Insertion. */
element and
location for its 2.7.3Deleting Element from Arrav
#include<stdio.h> To remove the elemnent from array.
#include<conío.h>
An array named, A is a Linear array having n
elements in it.
#define N 10
Consider the following:
void main) 20 30 40 50
10
int la<N],loc,item; Initlal Array
int ij; 10 20 30 40
clrscr);
of an Array\n",N- 1):
After deleting an element at end
printf("n Enter %d element
for(i-0;i<N-1;i++) 20 30 40
After deleting an element from beginning
scanf("%d", &la[il);
20 40
Array"); After deleting an element at particular Location i.e. after 20
printf("\n Enter item to be Insert in
scanf("%d",&sitem); Lb ’ Lower bound and UB ’ Upper bound
delete the element say,
getagain: Variable K is positive integer such that K< = n Our aim is to
printf("\n Enter location of array <= %d\n",N); data at kth position from array A
scanf("od", &loc); Algorithm: DELETE_BEG(LA, LB, UB, ITEM)
if(loc>N) bound UB.
Description: Here LA is a linear array with lower bound LB and upper
goto getagain; ITEM from linear
This algorithm deletes an element from beginning and assigns it to
j=N-2; array LA.
while(j>=1oc-1)
Step 1: [initialize counter] set I:=LB
Step 2: (Set item] Set ITEM:-LA|I]
lalj+1]=lail:
Step 3: Repeat steps 4 and 5 while I < UB
Step 4: |Move element to its left] Set LAI]:= LAI+1]
2.27
ARRAY
ARRAY int i,j;
2.26
clrscr();
Set I:=l+1
JdecrementCounter) printf("\n Enter %d element of an Array\n',N):
Step 5:
[End while) for(i=0;i<N;it+)
Set UB:-UB-1
|Decreasearray size|
Step 6.
Exxt ITEM)
Step 7.
END(LA, LB, UB, scanf("%d",8la|il);
Algorithm: DELETE bound Il
bound LB and upper
linear array with lower to ITEM from
linear
Description: Here LA is a end and assigns it array
an element from getagain:
This algorithm deletes
LA. orintf("\n Enter location of element to be delete <= %d\n",N);
l:=UB
|Initialized counter] Set scanf("%d", &loc);
Step 1: ITEM:=LA[I)
Step 2 |Assign value) Set
UB:=UB-1 if(loc>N)
Step 3: |Decrease array size] Set
goto getagain;
Step 4: Exit
ITEM, LOC)
item=la|loc-11:
Algorithm: DELETE_LOC(LA, LB, UB,
bound LB and upper bound UR for(j=loc-1ij<N-1ij++)
Description: Here LA is a linear array with lower
given location LOC and assigns it to ITEM
This algorithm deletes an element from a
from linear array LA. lalj]-lalj+ 1];
|initialize counter] set I:=LOC
Step 1:
Step 2: [Assign Value] Set ITEM:=LA|I]
printf("\n Deleted item is = %d",item);
Step 3: Repeat steps 4 and 5 while I < UB
Step 4: (Move element to its left ] Set LA[I]:= LA[I+1] printf("\n Elements of Array are );
Step 5: [Increase Counter) Set I:=1+1 for(i=0;i<N-1;i++)
(End while)
Step 6: |Decrease array size] Set UB:=UB-1 printf("\n %d",lali]);
Step 7: Exit
Program 2.6 getch);
/ This program gets N elements of Array from the user and gets the location for
deletion of an element from array. */
#include<stdio.h>
2.7.4 Copying
will be
#include<conio.h> Copy is the process to make the duplicate copy of existing elements. Copying
then traverse
#defineN 10 performed only by allocating new memory same as of previous array and
each element of an array to insert it into another array.
void main)
10 20 30 40 50
Initial Array
int la{N],loc,item;
2.29
ARRAY ARRAY
50
40 1b[i]=la{i);
20 30 another
array Into
an entire
After copying
UB2)
LB, UB, LA2, LB2,
Algorithm: COPY (LA, lower bound LB and upper bound UB printf("\n Copied Elements of Array are );
linear array with to UBT
Description: Here LA is a to LB2and UB forli-0;i<N-1;j++)
from LA to LA2, LB
oopics all elements
This algonthm
Step 1:Set I-LB I s UB printf("\n %d",lb[il);
steps 3 and 4 while
Step 2: Repeat LA2[IJ:-LA(
Step 3 |Copy Values) Set
Counter Set I:=]+1 getch);
Step 4: (Increment
End while Loopl
Set LB2:=LB
Step 5: 2.7.5 Merging
Set UB2:=UB
Step 6:
Step 7: Exit Merging process is used to merge two or more different linear arrays in to single
array.
Programn 2.7 5 14 15 18 51 55 88
from the user and copies all the elemens
/ This program gets N elements of Array First Sorted Array
to another array. / 7 25 48 76
#includestdio.h>
Second Sorted Array
include<conio.h>
3 5 7 14 15 18 25 48 51 55 76 88
#define N 10
void main) Merged array in which two sorted arrays are copied into third one.
ALGORITHM MERGE(LA, M, LB, N, LC, K)
int la{N],Ib[N]; Here LA is first sorted linear array with Melements and LB is second sorted array
int ij; ith N elements. LC is the third linear array in which all the elements are to be
cirscr); arranged with size K
printf"\n Enter %d element of an Array\n",N); Step 1: Set I: =1, J: =1, K: =1
for(i=0;i<N;it+) Step 2: Repeat while I<=M and J<-N
IF LA |I| < LB (J] Then
Set LC [K]:= LAI]
scanf("%d",&la<il); Set I: = I +1
/* Else
copying process "/
Set LC|K]:=LB|J]
fori-0;i<N;it+) Set J:=J+1
2.30
ARRAY ARRAY
2.31
lc[k<=1blil;
|End If jt+;
Set K: K+1
lend while step2) k++;
Repeat While IsM |Copy all remaining elements from LA to L
Step3:
Set LC [K]:= LA [I) while(i<m)
Set I: = I+1
Set K: = K+1
lc[k<=la[i];
End Repeat] i++;
|Copy all remaining elements from LB to LI
Step4: Repeat WHILE JSN k++;
Set LC (K]: = LB |J];
Set J: =J+1 while(j<n)
Set K: = K+1
[End Repeat) lc[k<=lb|jl;
Step5: Exit jt+;
k++;
Program 2.8
J* Program to Sort the elernents by Merge Sort Technique.*/
#include<conio.h>
void main()
#include<stdio. h>
#define M 100
#defineN 100 int la[M]),1b[N], lc|M+N];
int asize,bsize,i,j,k;
void merge_sort(int *,int,int *,int, int );
void merge_sort(int lal], intm,int lb[],int n, int lcl]) printf("\n Enter the size of First Listn);
scanf(%d",&asize);
int i,j,k; printf("\n Enter od element for sorted Array - I\n",asize);
i-0;j-0;k-0; for(i=0;i<asize;it+)
while(i<m && j<n)
scanf("%d", &la{il);
if(la<ij<lbil)
printf(\n Enter the size of Second List\n");
lc[k<=la<i];: scanf("%d",&bsize);
it+; printf("\n Enter %d element for Sorted Array - II\n",bsize);
for(j-0;j<bsize:j++)
else
scanf("%d",&lblj);
ARRAY ARRAY
2.33
2.32
row
column matrix element
bsize,lc);
merge_sort(la,asize,Ib, sort is \n");
after applying merge Fig. 2.7(a) will be represented by
printf"\n Sorted List
for(k-0;k<asize+bsize;k++)
Col. no. where non
zero
printf"\n %d".lc[kl); element exists
getch); + No.of colums in original matrix
No.of rows in original matrix +3 2+No.of non-zero elements
2.8SPARSE MATRIX Row no
as Sparse Actual value
of elements are zeros is referred to 3 2
An array in which a large percentage
Col. no. where non zero
complexity by using the concept of Sparse element exists
Array. We can save the time as well as space
array representation in memory with special technique.
lot o
computer with a technique, which saves a Fig. 2.8 (a)
Sparse array can be represented in he first roW 1s : 3 rows 3 columns and 2
elements as zero or null. non-zero elemnents of fig. 2.8|a).
space if original array contains the most
of zerOs than the non zero elements in The second row corresponds to second row.,
A matrix that has relatively higher number first column, value 1.
known as sparse matrix. Similarly the third row corresponds to third row, second
column, value 1.
It may be seen irom the above example that no
e.g. space has been saved in
comparison to fig. 2.8(a).
000 0
1000 Rut this is not the case for higher number of rows and
100 columns. This can be seen
Lo 10 0020 from the following represerntation of fig. 2.7(b).
Lo 0 10J
. No. of rows in original Matrix =5, No. of column = 4. No. of
Fig. 2.7 (a) Fig. 2.7 (b) non zero elements =
2
" Infig. 2.7(a), only 2 memory units are utilized and other 7 are wastage of memory . First non zero row 1s 3rd, So in the second row we have the
element 2.
spaces. Similarly in fig. 2.7 (b) only 3 units are utilized and other 17 are zeroes, . Position of non zero element (column is 1) and its value is 1.
hence there is wastage of memory space as well as time. To save the space of
Next non zero element exists in Row no, 4. Non zero element exists X at column
memory and time, sparse matrix requires some sparse representation. no. 3 and its value is 2.
Sparse Matrix Representation
Sparse matrices are represented by using 3 tuple form, where we have 3 columns and 5 4 3
n+1rows where n are non-zero elemnents. 3 1 1|
4 3 2
The first row in the 3 tuple form is the size of the sparse matrix and 5 3 1J
number of
non-zero entries.
All other entries are row, column, value of the
non-zero entries. Flg. 2.8(b)
Matrix tuples have the structure indicated below:
element exist at column
ARRAY ARRAY
and
third list
2.35
non zerO no. point torepresent the Column
2.34 3 second
row n0. 5, position and
element exists at example First the first row of value in the column. For
" Next
non zero
2.8(b). the row
specifies the corrèsponding
number second partsparse array node, in which three parts, exists. First
compared to 20 units in fig.
1. 1
and its value is
uses only 4 x 3-
12 units of space as
saved
representation.
in this form of
Hence part
number.
Third
part contains the
corresponding value of that address of contains the link of column position and their
column and the node having first
next node having next row
units have been kind ofdata structure. link part
the space of8 otherwise link
We know that
linked-lists are very
but
popular and a useful
some of them are
singly linked-list type and
The
There
doublyof
row sparse array.
from
to the node
having next columnspecify NULL if no further value in the same
and value with same row number
position
af linked-lists,
are several types
linked-ist type which are
always used because
of their
advantages.
be managed well
by using some elements
kind of
PROBLEM 2.9.
#include <stdio.h>
Store an array using sparse representation.
mentioned above can also in memnory
sparse matrices 2.9 can be represented
linked-lists. The Sparse
Matrix shown in figure
below figure 2.10
using #include <conio.h>
Linked list as shown in int a100][100], b|100||100):
void main)
0 0 58
24 74 0 0
0 int i,m,n,p,4,col,t;
0
0 0 35 cirscrl);
0 printf("Enter the no. of rows");
62
0
scanf("%d", sa<0j|0]);
13
ordntf("Enter the no. of cols):
Fig 2.9
scanf("%d", &a<0][1):
printf("Enter the number of non zero
In igure 2. 10 there are First List represent the Row position of Sparse Arrav and terms");
scanf("%d", &a<0|[2]);
FIRST
for(i=1;i<=a[o]|2];i++)
Row Col Val Link Col Val Link
+ 1 24| + 6 58| NULL
printf("Enter the value (that is non zero)");
scanf("%d", &a<il|2]);
+8 7A| NULL
printf("Enter the row for %d :",a•il/2);:
scanf("%d", &a<il[0|);
4 7 NULL
printf("Enter the col for %d :",alil[2):
10 82NULL
scanf("%d", &a|i]|1]);
}
3 62 NULL /* Printing for testing the sparse input */
printf("The martix you entered is
t*t************************ **
2 13NULL Row Col Value ");
***********k*************
Fig 2.10 Linked representation of sparse matrix
2.36
for getch); /*
getch); printf("%dprintf("The { for( t;=b[0][0]
q=1;b[0][2]b[0][1] a0][1];a/0][0];
|2};t=
= n= m for
m;
=a(0|n; = /*printf" %d
i=( Printing col Calling (i=
0;i = 0;i
1;
<=
Transpose the /*end col function <=
a<0][2];i++) transposed
%d for(p <=n; a<0|%d[2];it+)
of for
outer }qtt;a<pl[2);
b[al|2] = b[al[0] ifa[pl[ = col++)
of =alpl|
b[all1]
O};
the 1;
%d above
matrix for = p<=t;p++)
1]
evaluation %d
loop*/ a<p|[ ==
matrix */ 1]; col) of
bi]|0],bi]1,b[i](2]);", is");
transpose
alij/0],a(i]I1),a(i||2); ,
"/