Saturday, November 1, 2014

4.1.2 ONE-DIMENSIONAL ARRAY

Def:

A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array. 

e.g.    If we want to represent a set of five numbers, say (35,40, 20, 57, 19) by an array variable ‘number’, then we may declare the variable ‘number’ as follows:

            int   number[5];

and the computer reserves five storage locations as shown below:
          
35
40
20
57
19

number[0]
number[1]
number[2]
number[3]
number[4]

NOTE: In C, the counting of elements begins with 0 and not 1.

Declaration of one-dimensional arrays

General form:

            type   array_name[size];

The type specifies the type of element that will be contained in the array, and the size indicates the maximum number of elements that can be stored inside the array.

e.g.      float salary[50];

            int group[10];

 Initialization of one-dimensional array

§  Compile-time Initialization

We can initialize the elements of arrays in the same way as the ordinary variables when they are declared.

General form:

            type   array_name[size] = { list of values };

            e.g.      float     total[5] = { 0.0, 15.75, -10, 6.3, 2.4};

 NOTE: If the array is not initialized, it would contain garbage values.

 §  Run-time Initialization

An array can be explicitly initialized at run-time. This approach is usually applied for initializing large arrays.

e.g.
(i)         int   num[10];
for ( i = 0; i <= 10; i++)
                        {
           scanf ( “%d”, &num[i]);
            }

(ii)        for ( i = 0; i < 100; i++)
            {
                        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 at run time.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.