Array in data structures ( static array )
An array is a set of items stored at adjacent memory locations. The idea is to store various items of the same data type collectively. This makes it easier to determine the location of each component by simply joining an offset to a base value, i.e., the memory location of the first component of the array (usually expressed by the name of the array). The base value is index 0 and the disparity between the two indexes is the offset.
For clearness, we can think of an array a line of stairs where on each step is placed a value (let’s assume one of your mates). Here, you can identify the location of any of your friends by simply identifying the count of the step they are on. Mainly in this article, we are talking about static arrays.
Size of the array
In C++ language array has a fixed size recommending one’s size is given to it. It can’t change (Only for static array). The intention was that for expanding if we alter the size we can’t be certain that we get the next memory position to us as free. The shrinking will not act because the array when listed, becomes memory statically, and hence compiler is the only one to kill it.
Models of indexing in the array
- 0 (zero-based indexing): The first component of the array starts from index 0.
- 1 (one-based indexing): The first component of the array starts from index 1.
Advantages of array
- Arrays allow arbitrary access of components. This makes accessing components by position quicker.
- Arrays have better cache locality that can obtain a pretty big difference in execution.
- Accessing elements in the array is O[1].
- Using arrays, other data structures like linked lists, stacks, queues, trees, graphs can be implemented.
- Accessing the element is faster then any of the data structures available.
Disadvantages of using array
- Static arrays are implemented on the stack and they are fixed size so you can not increase or decrease the size of the array once it has been declared.
- You have to provide the size of the array during compile time.
Example
//integer array
int arr[]={15,16,20,24,5,19,18};
// accessing and printing component from the array
cout<<arr[4];
// Char array
char arr[]={'a','b','c','d'};
C++ code for example
#include<iostream>
int main(){
// declayring the array;
int arr[7];
//assigning values to array
arr={15,16,20,24,5,19,18};
//changing the value of a component at perticular index
arr[5]=23;
//printing the values of the array
for(int i=0;i<7;i++){
std::cout<<arr[i]<<" ";
}
}
Post a Comment: