Arrays in C: Example Where Arrays Are Used
Arrays in C: Example Where Arrays Are Used
Arrays in C: Example Where Arrays Are Used
Since arrays provide an easy way to represent data, it is classified amongst the data
structures in C. Other data structures in c are structure, lists, queues, trees etc.
Array can be used to represent not only simple list of data but also table of data in
two or three dimensions.
Declaring an Array
Like any other variable, arrays must be declared before they are used. General form
of array declaration is,
data-type variable-name[size];
int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of array. It
means array arr can only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e first element of arr array will be stored
at arr[0] address and the last element will occupy arr[9].
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will
contain garbage value(any random value). An array can be initialized at
either compile time or at runtime.
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
2 3 4
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
printf("%d\n", arr[j]);
}
}
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}