Arrays in C Language - With Examples:
An array is a collection of similar type of data items. Each data item is called an element of the array. The data type of the elements may be any valid data type like char, int, or float. The elements of array share the same variable name, but each element has a different index number known as a subscript.
The variables that we have used till now, can store only one value at a time. Consider a situation when we want to store and display the age of 100 employees. For this, we must do the following-
- Declare 100 different variables to store the age of employees.
- Assign a value to each variable.
- Display the value of each variable.
Although we can perform our task by the above three steps. Just imagine how difficult it would be to handle so many variables in the program. The program would become very lengthy. The concept of the arrays is useful in these types of situations where we can group similar types of data items.
For the above problem, we can take an array variable age [ 100] of type int. The size of this array variable is 100 so it can store 100 integer values.
The individual elements of this array are-
age, age, age, age,age, ………………………………….. age, age
In C the subscripts start from zero, so age is the first element, age[ 1] is the second element of an array, and so on.
In C Programing language can be as two type Arrays.
- One dimensional
- Two Dimensional Array
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.