• An array in C or C++ is a collection of items
stored at contiguous memory locations and
elements can be accessed randomly using
indices of an array. They are used to store
similar type of elements as in the data type
must be the same for all elements. They can
be used to store collection of primitive data
types such as int, float, double, char, etc of
any particular type
Why do we need arrays?
• We can use normal variables (v1, v2, v3, ..)
when we have a small number of objects, but
if we want to store a large number of
instances, it becomes difficult to manage
them with normal variables. The idea of an
array is to represent many instances in one
variable.
Array declaration in C
• There are various ways in which we can
declare an array. It can be done by specifying
its type and size, by initializing it or both.
1. Array declaration by specifying size
int arr1[10];
• Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 }
Array declaration by specifying size and initializing
• int arr[6] = { 10, 20, 30, 40 }
above is same as int arr[] = {10, 20, 30, 40, 0, 0}
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.
Accessing Array Elements:
• Array elements are accessed by using an
integer index. Array index starts with 0 and
goes till size of array minus 1.