- Array is a linear data structure which holds same type of elements in continuous memory location.
- Total number of elements in array is called size of array.
- Elements of array are accessed on index basis.
- An index represent position of any element in array.
- Address of element at 0th index called base address of array.
- So address of element at index is
- Address (index) = baseAddress + index*sizeOfElement
- If Array has N elements then index states from 0 to N-1.
- Size of element size = 5 unit.
- Base address badr = 1000
- Number of elements N = 4
- So index range from 0 to 3 i.e 0 <= index < N-1
Element at index 3 can be accessed using one of two method given below.
- Directly by using index
- Value = Array[index] = Array
- Using address
- adr = badr + index*size = 1000 + 3*5 = 1015
- Value = *(adr) or value at address adr
Operations on Array
On Any data structure we perform following five basis operations
Traversing means consider each element in a data structure for example
- Print each element of array.
- How many even numbers or odd numbers or prime numbers are there in array? etc.
On such type of questions we need to apply given condition on each element of array.
Example-2 -> Count odd numbers in given Array of size N. So we can use following approach.
- For index 0 to N-1 repeat step 2 to 3.
- If element at index k is odd.
- Increment counter.
- Print counter.
for given Array let’s take
- Total elements N = 5
- Counter counter = 0
- Index k =0, i.e 0 <= k < N-1
- value = value at any index
So for asked query steps are:
- At k = 0
- value = Array[k] = Array = 78 that’s an even number so don’t increment counter.
- Set k = k + 1 = 1
- At k=1,
- value = Array[k] = Array = 45 that’s an odd number so increment counter.
- Set counter = counter + 1 = 1
- Set k = k + 1 = 2
- At k=2
- value = Array[k] = Array = 29 Again it’s an odd number so increment counter.
- Set counter = counter + 1 = 2
- Set k = k + 1 = 3.
- At k=3
- value = Array[k] = Array = 60 got an even number so don’t increment counter.
- Set k = k + 1 = 1
- At k =4
- value = Array[k] = Array = 102 that’s an even number so don’t increment counter.
- Set k = k + 1 = 1.
- Now k = 5 which is greater then valid range i.e 0 <= k < N-1 so stop traversing here.
Finally we have counter = 2 which is the number of odd numbers in given Array.
Update mean override old value at a given index with given new value. Almost all programming language has same technique to update value in array like Array [index] = new value.
Example-3 -> Take an Array like
update value at index 2 with new value 100 in given array. Simply Set Array =100, after update array becomes