A list of items can be given a variable name using only one subscript and such a variable is called a single dimensional array. For example, if we w ant to represent a set of five numbers say {1, 2, 3, 4, 5} by an array variable member. We can declare the variable member as follows
int number[5];
one thing to be noted is that the subscript of the starts with zero. The computer reserves five storage locations as given below
Number[0]
Number[1]
Number[2]
Number[3]
Number[4]
The values to the array elements are assigned and stored: as given below
Element Value
Number[0] 1
Number[1] 2
Number[2] 3
Number[3] 4
Number[4] 5
These elements can be used in programs just like any other C variables.
Array initialization
The elements of the array can be assigned initial values by following the array definition with the list of initial values enclosed in braces and separated by commas. For example, the declaration
int mark[5] = {91,85, 100,94, 80}
defines the array mark to contain five integer elements and initializes
mark|0] to 91
mark[1] to 85
mark[2] to 100
mark[3] to 94
mark[4] to 80
Rules for array initialization
If the number of initializers is less than the number of elements in the array, the remaining elements are set to zero. Therefore, in the following initialization
int mark[5] = { 88,90, 67, };
is equivalent to the initialization
int mark[5] = {88,90, 67, 0,0};
It is an error to specify more initializers than the number of elements in the array.
It is not necessary to specify the length of an array, explicitly, in case. if initializers are provided for the array. In that case, the length of the array is derived from the initializers. For example, the declaration
int mark[] = {88,90,67,99, 100};
is equivalent to
int mark[5] = {88,90,67,99,100};
A character array can be initialized by a string constant, resulting in the first element of the array being set to the first character in the string, the second element to second character and so on. The array also receives the terminating '" in the string constant. Thus, the initialization
char name[6] = "SNEHA ";
is equivalent to
char name[6] = {'S, 'N', 'E', 'H', 'A', '};
Note
The following program calculates the sum and average of ten numbers using single dimension arrays.
Example 3.3
/*Program to illustrate the single dimension array */
#include <stdio.h>
int main()
{
int sum, ave, i, number[10];
printf ("Enter ten numbers \n");
/* To read the values of ten array element s */
for (i=0; i < 10; i++)
scanf ( "%d", &number[i]);
/* To find the sum and average of ten numbers */
sum = 0;
ave = 0;
for(i=0; i < 10; i++)
{
sum = sum + number[i] ;
}
ave = sum/10;
printf( "The sum of ten numbers is %d", sum);
printf ( "The average of ten numbers ia %d", ave);
}
So far, we have been introduced to linear arrays. The C language allows arrays of any dimension to be defined. The following topics provide us to get an understanding about multidimensional arrays.