The data type specifies the type of element that will be contained in the array, such as int, float, or char.
The size indicates the maximum number of elements that can be stored inside the array.
Here, the name of array is age. The size of array is 5, i.e., there are 5 items (elements) of array age. All elements in an array are of the same type (int, in this case).
Size of array defines the number of elements in an array. Each element of array can be accessed and used by user according to the need of program.
Note that, the first element is numbered 0 and so on.
Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting address of age [0] is 2120d and the size of int be 2 bytes. Then, the next address (address of a [1]) will be 2122d, address of a [2] will be 2124d and so on.
After an array is declared, its elements must be initialized. Otherwise they will contain “garbage”. We can initialize the elements of arrays in the same way as the ordinary variables when they are declared.
The general form of initialization of array is .
The values in the list are separated by commas.
You can initialize array in C either one by one or using a single statement as follows :
int age[5]={2,6,34,5,1};
It is not necessary to define the size of arrays during initialization.
int age[]={2,6,34,5,1};
In this case, the compiler determines the size of array by calculating the number of elements of an array.
Following is an example to assign a single element of the array :
# include<stdio.h>
#include<conio.h>
main( )
{
int i,n;
float a[50], large, small;
printf(“size of array value:”);
scanf(“%d”, &n);
printf(“ \n array elements are \n”);
for(i=0; i<n; i++)
scanf(“ %f ”, &a[ i ]);
large = a[0];
small = a[0];
for(i=1; i<n; i++)
{
if(a[ i ] > large)
large = a[ i ];
else if(a[ i ] < small)
small = a[ i ];
}
printf(“\n Largest element in vector is %8.2f \n”, large);
printf(“ \n smallest element in vector is %8.2f \n”, small);
getch( );
}
Size of vector: 7
Vector elements
34.00 – 9.00 12.00 10.00 - 6.00 0.00 36.00
Largest element in vector is 36.00
Smallest element in vector is – 9.00
# include<stdio.h>
# include<conio.h>
main( )
{
int i, j, k, n;
float a[50], temp;
printf(“size of vector:”);
scanf(“%d”, &n):
printf(“ \n vector elements are : \n”);
for( i=0; i < n; i++)
scanf(“ %f ”, &a[ i ]);
for( i=0; i < n-1; i++)
for( j=i+1;j<n; j++)
{
if(a[ i ] > a[ j ])
{
temp = a[ i ];
a[ i ] = a[ j ];
a[ j ] = temp;
}
}
printf(“\n vector elements in ascending order : \n”);
for ( i=0; i<n; i++)
printf (“ %8.2f ”, a[ i ]);
getch ( );
}
Size of Vector: 8
Vector elements are
91.00 20.00 1.00 7.00 34.00 11.00 -2.00 6.00
Vector elements in ascending order;
-2.00 1.00 6.00 7.00 11.00 20.00 34.00 91.00