Introduction To Array
The C language provides a capability called 'array' that enables the user to design a set of similar data types. Here we will describe how arrays of various types can be created and manipulated in C. An array is a collection of similar elements that share a common name. These similar elements could be all integers, or all floats, or all characters but not a combination of these data types. Note: Usually the array of character is called a 'String'.
Array Declaration
Like other variables an array needs to be declared before used in the program. Expression syntax:
datatype arrayname [no of elements];
Example-
int marks[20];
Here int is the datatype of the array, marks is the name of the array and the number 20 tells how many elements of the type int will be in our array. The bracket ( [] ) tells the compiler that we are dealing with an array.
Accessing Elements of An Array
We can access all the elements of an array by the element number (Index number). The array index starts from zero. For example, marks[0] is the first element of the array and marks[3] is the fourth element of the array not third.
Entering Data into an Array:
marks[0] = 60;
marks[4] = 78;
for(i=0; i<=20; i++)
{
printf("\nEnter the marks");
scanf("%d",&marks[i]);
}
Reading Data from an Array:
a = marks[2];
b = marks[6];
for(i=0; i<=20; i++)
{
printf("\n%d",marks[i]);
}
Some Important Points about Array:
1. An Array is collection of similar elements.
2. The First element in the array is numbered 0, so last element is 1 less than the size of the array.
3. An array is also known as subscripted variables.
4. All the array elements are always stored in contiguous memory locations.
5. The amount of storage required for holding elements of the array depends on its type and size. Total bytes = sizeof (data types) * size of array