C Array
An array is a collection of elements that are used to hold the fixed number of values of the same type. We cannot change the size and type of array after its declaration.
Why should we use an Array?
We should use an array because of its properties:
- It reduces the code while using the array.
- It is easy to traverse the data.
- It is easy to short the element of an array.
- It is easy to access the data randomly.
There are two types of arrays in C language:
- 1-D Array
- 2-D Array
One Dimensional Array:
A list of items can be given one variable name using only one subscript and such a variable is called one-dimensional array.
Declaration of C Array
We can declare an array by using the following syntax.
data_type array_name[array_size];
Initialization of Array
There are two ways to initialize the array:
- First way: We can initialize the array of elements inside the bracket with a comma in one line.
Example : char vowel[6]={‘a’,’e’,’i’,’o’,’u’};
- Second way: We can initialize the array of the elements one by one. It is easy to access the elements in comparison to the first way.
Example
vowel[0]=’a’; vowel[1]=’e’; vowel[2]=’i’; vowel[3]=’o’; vowel[4]=’u’;
Let us consider an example of an array;
#include <stdio.h> int main(){ int i; char vowel[5]={'a','e','i','o','u'}; for(i=0;i<5;i++){ printf("[%d]=%c\n",i,vowel[i]); } return 0; }
Output
[0]=a [1]=e [2]=i [3]=o [4]=u
Two Dimensional Array
Two-dimensional arrays are used in the form of row and columns. It is also known as matrices
The 2D, 3D or other dimension is also known as a multidimensional array.
Declaration of two-dimensional arrays
The given following syntax to declare the 2D:
Syntax:
data_type array_name [row-size1][column-size2];
Let us consider an example:
int add[3][3];
Initialization of 2D Array in C
int array[3][3]={{1,2,3},{2,3,4},{4,5,6}};
Example:
#include<stdio.h> int main(){ int i=0,j=0; int arr[3][3]={ {1,2,3}, {2,3,4}, {3,4,5} }; for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf("arr[%d][%d]=%d\n",i,j,arr[i][j]); } } return 0; }
Output
arr[0][0]=1 arr[0][1]=2 arr[0][2]=3 arr[1][0]=2 arr[1][1]=3 arr[1][2]=4 arr[2][0]=3 arr[2][1]=4 arr[2][2]=5
There are following some important points while using an array:
- We must use the same data element or data at the time of initialization.
- Array index will start with ‘0’ and end with ‘size-1’.
It uses static memory allocation at the time of working with an array.