PM Datastructure
Linear Arrays
An Array is a data structure used to collect multiple data elements of the
same data type into one variable.
The elements of the array can be referenced using a subscript or index
which cocsist of consecutive numbers (0 to n-1).
Elements of the array are stored in successive memory locations.
UB(Upper Bound) – Largest Index
LB(Lower Bound) – Smallest Index
Length= UB-LB+1
Declaring Arrays
An array is declared as
datatype arrayname[size];
Eg: int a[10];
Initialization of arrays
We can initialize array elements at the time of declaration.
Syntax
datatype arrayname[size] = {list of values};
eg: int a[3]={10,4,6};
int b[5]={1,2}; means int[b]={1,2,0,0,0};
int a[]={1,2,3,4,5};
int a[3]={};----------All elements will be initialized zero.
about:blan 1/39
k
,9/18/24, 2:25 Module 2
PM Datastructure
We can assign values to individual elements of arrays using assignment operator.
Eg: a[5]=10;
Representation of array in memory
All the data elements of an array are stored at contiguous locations in the main memory. The
name of the array represents the base address or the address of the first element in the main
memory. Each element of the array is represented by proper indexing.
In the above image, we have shown the memory allocation of an array arr of size 5. The
base address of the array is 100 bytes. It is the address of arr[0]. Here, the size of the data
type used is 4 bytes; therefore, each element will take 4 bytes in the memory.
Calculating address of array element
The starting address of array is called base address.
The address of a particular array element is calculated using the formula
Address of A[I] = B + W * (I – LB)
I = Subset of element whose address to be
found, B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).
Example: Given the base address of an array A[1300.......1900] as 1020 and the
size
of each element is 2 bytes in the memory, find the address of
A[1700]. Solution:
about:blan 2/39
k
,9/18/24, 2:25 Module 2
PM Datastructure
about:blan 3/39
k
, 9/18/24, 2:25 Module 2
PM Datastructure
Insertion at End
INSEND(INT A[10], INT N, INT ITEM)
1. Start
2. Set A[N] = ITEM
3. Set N=N+1
4. Return
Insert at a particular position
INSMID(INT A[10], INT N, INT ITEM)
1. Start
2. Set i=N-1
3. Repeat while i>=pos-1
A[i+1] = A[i]
Set i=i+1
4. End While
5. Set A[pos -1 ] = ITEM
6. Set N=N+1
7. Return
Let's take an array of 5
integers. 1, 20, 5, 78, 30.
If we need to insert an element 100 at position 2, the execution will be,
about:blan 4/39
k