C Language

Array In C

In C Language by Baqir Ali

Scientific programs very often deal with multiple data items possessing common characteristics. e.g. x1, x2, x3, x4,…

In such cases, it is often convenient to place the data items in question into a structure, so that they all share a common name.

What is an Array?

An array is a consecutive series of variables that share one variable name Or An array is a collection of homogeneous data elements.

For example: a program to compute the average temperature over a 24-hour period might store 24 temperature readings in an array named temperature.

The individual data items in an array must all be of the same data type Whenever you see “array” in C, think “vector”, that is a one-dimensional array of something.

Array In C
Array In C

Array Terminology

  • A value in an array is called an array element.
  • The number of elements stored in the array is called the array length.
  • A subscript is an integer expression enclosed in square brackets that, when used in combination with the array name, designates a particular element in an array.
  • Arrays are declared in much the same manner as ordinary variables, except that each array name must be accompanied by a size specification (which specifies the number of elements).
  • For a one-dimensional array, the size is specified by a positive integer constant, enclosed in square brackets.

Array Declaration

Several valid array declarations are shown below:

 int j[100];
 double x[20]; 

Thus, j is a 100-element integer array, and x is a 20-element floating point array.

Array Dimensions

The number of subscripts determines the dimensions of an array. For example, x[i] refers to an element of a one-dimensional array, x Similarly, y[i][j] refers to an element of a two-dimensional array, y,

What you can’t do!

  • Note that variable size array declarations, e.g.,
    • double a[n];
    • where n is an integer variable, are illegal in C.
  • The following are invalid numbers of elements:
    • a[-24], b[37.5]

Using Constant Sizes For Array

It is sometimes convenient to define an array size in terms of a symbolic constant, rather than a fixed integer quantity which makes it easier to modify a program that utilizes an array, since all references to the maximum array size can be altered by simply changing the value of the symbolic constant.

 #define N 100     // defines a constant 100 to N
 int array_num[N];   // which is legal now