Initialization of Arrays in C
Posted by
Ravi Kumar at Sunday, September 18, 2011
Share this post:
|
We can initialize the elements of the array in
the same way as the ordinary variables when they are
declared.The general form of initialization of array is:
static type array-name [size] = { list of variables};
the values in the list are separated by commas.
For example, the statement
static int number [3] = {0,0,0}
will declare the variable number as an array of size
3 and will assign zero to each element. If the number of
values in the list is less than the number of elements,
then only that many elements will be initialized the
remaining elements will be set to zero automatically.For
instance,
static float total[5] ={ 0.0, 15.75, -10};
will initialize the first three elements to 0.0, 15.75,
-10 and the remaining two elements to zero.
Note that we have used the word static before type
declaration. This declares the variable as a static
variable. The size may be omitted. In such cases the
compiler allocates enough space for all initialized
elements.
For example, the statement
static int counter []={ 1,1,1,1};
will declare the counter array to contain four elements
with initial values 1. This approach works fine as long as
we initialize every element in the array.
Character arrays may be initialized in a similar manner.
Thus, the statement
static char name[] = {J, o ,h , n};
declares the name to be an array of characters,initialized
with the string John.
Initialization of arrays in C suffers two drawbacks.
1.There is no convenient way to initialize only selected
elements.
2.There is no shortcut method for initializing a large
number of array elements like the one available in FORTAN.
Program showing One-Dimensional Array:
main()
{
int i;
float X[10],value,total;
print f (Enter 10 real numbers \n);
for (i=0;i<10;i++)
{
scan f(%f ,&value);
X[i]=value;
}
total=0.0;
for(i=0;i<10;i++)
total =total + X[i] * X[i];
print f (\n);
for (i=0;i<10;i++)
print f( X[%2d]=%5.2f\n, X[i]);
print f(\n total =%2.f \n , total);
}
OUTPUT:Enter 10 real numbers
1.2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
X[1]=1.10
X[2]=2.20
X[3]=3.30
X[4]=4.40
X[5]=5.50
X[6]=6.60
X[7]=7.70
X[8]=8.80
X[9]=9.90
X[10]=10.10
total= 446.86
consider an array of size ,say 100. All the 100 elements
have to be explicitly initialize. There is no way to specify
a repeat count. In such situations, it would be better to
use a for loop to initialize the elements. Consider the
following segment of a C program:
for(i=0;i<100;i=i+1)
{
if(i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
the first 50 elements of the array sum are initialized to
zero while the remaining 50 elements are initialized to 1.0