Page 87 - 6437
P. 87
The number of values between braces { } cannot be larger than the number of elements
that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is
an example to assign a single element of the array:
balance[4] = 50.0;
th
The above statement assigns the 5 element in the array with a value of 50.0. All arrays
have 0 as the index of their first element which is also called the base index and the last index of
an array will be total size of the array minus 1. Shown below is the pictorial representation of the
array we discussed above:
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array. For example:
The above statement will take the 10th element from the array and assign the value to
salary variable. The following example shows how to use all the three above-mentioned concepts
double salary = balance[9];
viz. declaration, assignment, and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
90