An array is a kind of data structure that can store a fixed-size sequential collection of elements of the same type. Why we need Array in Programming? Properties of Array Array declaration in C Array Initialization in C Accessing Array Elements Advantages/Disadvantages of an Array in C
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.
Consider a scenario where we need to find out the average of 100 integer numbers entered by user. In C language, we have two ways to do this:
It is clear that second solution is better than first. It is convenient to store same data types in one single variable and later access them using index.
Array declaration syntax in C
dataType array1DName[arraySize];
dataType array2DName[arraySize1][arraySize2]
dataType arrayMultiDName[arraySize1][arraySize2][arraySize3].......[arraySizeN]
Example of array declaration in C
int i, j, intArray[ 10 ], number;
float floatArray[ 1000 ];
int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */
int NROWS = 100;
int NCOLS = 200;
float matrix[ NROWS ][ NCOLS ]; /* NROWS rows by NCOLS columns */
Example of array Initialization in C
int i = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 }, k;
float sum = 0.0f, floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
double piFractions[ ] = { 3.141592654, 1.570796327, 0.785398163 };
Example of Array In C programming to find out the average of 4 integers
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
/* Array- declaration – length 4*/
int num[4];
/* We are using a for loop to traverse through the array
* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20