by Dinesh Thakur Category: Array

Array Declaration

Every array is given a name. The rules for naming arrays are the same as those used for variable names. As with scalar variables, an array must be declared before it is used. The declaration of a one-dimensional array takes the following form:

arr_type arr_name [arr_size] ;

wherearr_nameis the name or identifierof array being declared, each element of which is of type arr_type. The expression arr_size enclosed in square brackets is an integral constant or a constant integral expression that specifies the array size, i. e., the maximum number of elements in the array.

We can declare arrays of any built-in type such as char, float, unsigned int, etc. In addition, we can declare arrays of user-defined types such as structures, enumerated data types, etc. Note that we can declare one or more arrays in a single declaration statement. We can also mix scalar variables and arrays in a declaration statement.

When a compiler comes across the declaration of an array, it reserves a block of memory for the specified number of array elements. For a one-dimensional array containing elements, the memory required, i.e., the array size is given as x sizeof(arr_type) bytes.

Also note that when an array is declared in a block as shown above, the array elements are not initialized to any specific value and instead contain garbage values. This behaviour is similar to that of scalar variables.

Example of Array Declaration

Several examples of array declaration are given below.

a) int x[7];

This statement declares a one-dimensional array named x having 7 elements, each of type int.

b) float num[100], min, max;

This statement declares three entities of type float: an array nurn having 100 elements and scalar variables min and max.

C) #define MAX_SUB 6

int marks[MAX_SUB];

This example first defines a symbolic constants MAX_SUB with value 6 followed by a one dimensional array named marks of type int and size 6. This array can be used to store the marks of a student in six subjects.

Accessing Array Elements

The elements of an array are numbered starting from 0 (and not from 1). There for a one-dimensional array having arr_size elements, the element subscripts or indexes are in the range 0 to arr_size -1.

To access an individual elements of an array, C provides the array subscript operator []. An array element can be accessed by writing the array name followed by a subscript expression within the array subscript operator as shown below.

arr_name[expr]

whereexpris an integral expressions that specifies the position or index of an element in the array. Thus, the elements of an array a having 10 elements are referred as a [0] , a [1], ... , a [9]. Also, the ith element is referred as a [i].

For element access to be valid, the value of expressionexprshould be in the range 0 toarr_size -1. Remember that C does not provide any mechanism to verify that the array element being accessed actually exists. Thus, we can declare an array arr having 10 elements and access a non-existent element at location 10 as arr[10] or even at location 1000 as arr [1000]. This is a very common source of errors. It is the programmer's responsibility to ensure that a program does not access non-existent array elements.

Operations on Array Elements

For an array of typearr_type,we can perform a number of operations on its elements like those we perform on a simple variable of that type. Thus, we can use an array element in an expression (arithmetic, relational, logical, etc.), assign a value to it, perform increment and decrement operations using the ++ and - - operators, pass it as an argument to a function and so on. Note that the array subscript operator (along with some other operators) has highest precedence amongst all the operators. Thus, when we use an array element in an expression, we do not need to enclose it within parentheses.

To increment (decrement) a value of an array element, we can use the prefix or postfix increment (decrement) operator as shown below.

++arr_name [expr]           arr_name[expr]++

-- arr_name [expr]          arr_name [expr] --

We may often require the address of an array element, e. g., to read its value using the scanf function. This can be obtained it using the address ofo perator (&) as shown below.

&arr_name[expr]

Operations on Entire Arrays

Except initialization of arrays, which is discussed in the next section, the C language does not provide any statement or operator to perform operations on entire arrays. Basic operations such as array copy, console I/O, etc. are also not available directly. We can use a loop to perform operations on an entire array. As the number of elements to be processed from an array is often known, the for loop is an obvious choice.

The elements of a one-dimensional array arr of sizencan be processed using a for loop as shown below.

for (i = 0; i < n; i++) {

/* process element arr[i] */

}

Although for loops are more suitable for operations on arrays, the while and do ... while loops can also be used. Note that for operations on a string, which is a one-dimensional array of characters terminated by a null character, the while loop is more suitable.

Array Initialization

C allowsinitialization of an array by specifying an initialization list in the array declaration using the syntax given below.

data_type arr_name [arr_size] = {expr0,expr1 , . . . , expr_n } ;

where arr_name is the name of the one-dimensional array having arr_size elements, each of type data_type and the initialization list consists of zero or more constant expressions separated by commas and enclosed in curly braces. These expressions should be of the same type as that of the array; otherwise, their values are converted to type data_type using standard conversions. However, if such conversion is not possible, the compiler will report an error.

This initialization statement causes the array elements to be initialized with the values of the specified constant expressions. The first array element (arr_name[0]) is initialized with the value of the first expression (expr0), the second array element (arr_name[1]) is initialized with the value of the second expression (expr1) and so on. If the initialization list has fewer elements than the size of the array being initialized, the remaining elements are initialized with the default value that is zero for arithmetic types such as char, int, float, etc. However, if the initialization list contains more elements than required, the compiler gives a too many initializers error.

It is possible and often convenient to omit the array size as in

data_type arr_name [ ] = {expr0, expr1 , . . . , expr_n};

In this case, the array size is taken to be equal to the number of entries in the initialization list.

Illustrates declaration of an one dimension array

#include<stdio.h>

#include<math.h>
void main()
{
   int Total = 0, i, j, k;
   int Packages[4] = {10, 20, 30, 20};
   double Prices [5] = { 6.7, 7.5, 5.8, 4.9, 8.0};
   char Letters[4] = {'A', 'B', 'C', 'D' };
   clrscr();
   printf("The number of toys in Packages are as below.\n");
   for (i=0; i<4 ;i++)
       printf("Packages[%d]= %d ", i, Packages[i]);
       printf("\nThe five Prices are as below.\n");
          for (j=0 ; j<5 ; j++)
               printf ("%.2f\t", Prices[j]);
               printf ( "\nLetters [2] = %c\n", Letters[2]);
       for (k =0; k<4; k++)
          Total+= Packages[k];
          printf ("Total number of toys in all packages %d\n", Total);
}

One-dimensional Arrays C





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles