DATA STRUCTURE AND ALGORITHM (Array)
ARRAY
An Array is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.
![]() |
| Array |
Array declaration by specifying size:
// Array declaration by specifying size
int array1[20];
// We can also declare an array of user specified size
int n = 20;
int array2[n];
Array declaration by initializing elements:
// Array declaration by initializing elements
int array[] = { 10, 20, 30, 40 }
Array declaration by specifying size and initializing elements:
Advantages of an Array in C++:
- Random access of elements using array index.
- Use of less line of code as it creates a single array of multiple elements.
- Easy access to all the elements.
- Traversal through the array becomes easy using a single loop.
- Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array in C++:
- Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
- Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
A sample C++ program:
Output:
15 12 -1 15
Connect with the Author:


Comments
Post a Comment