Arrays

Arrays In C

Introduction

It may be difficult to store a collection of similar data elements in different variables. For example, consider that the scores for all the 11 players of a soccer team have to be recorded for a match. Storing the score of each player in variables having unique names is certainly more tiresome than having a common variable for them. This is what an array does .An array is a collection of data elements of the same type. Each element of the array has the same data type, same storage class and same characteristics. Each element is stored in successive locations of the main store. These elements are known as members of the arrays.

Array Elements and Indices

Each member of an array is identified by an unique index or subscript assigned to it. The dimension of an array is determined by the number of indices needed to uniquely identify each element. An index is a positive integer enclosed in square brackets [1 placed immediately after the array name, without a space in between. An index holds integer values starting with zero. Thus, an array player with 11 elements will be represented as,

player [0], player [1], player [2],.... player (10].

As is seen, the array element starts with player [0], and so the last element is player [10] and not player [11]. This is because in C, an array index starts from 0; and so for an array of N elements, the last element has an index of N-1. The limits of the allowed index values are called the bounds of the array index, the Lower bound and the Upper bound. A valid index must have an integer value either between the bounds or equal to one of them.

The term valid is used for a very specific reason. In C, if the user tries to access an element outside the legal index range (like player [11] in the above example of an array), it will not generate an error as far as the C compiler is concerned. However, it may access some value which can lead to unpredictable results. There is also a danger of overwriting data or program code. Hence the programmer has to ensure that all indices are with in the valid bounds.

What is an Array

  • The storage class
  • The data type of the elements of the array
  • The array name which indicates the location of the first member of the array
  • Array size, a constant which is an integer expression evaluating to a positive value

An array is defined in the same way as a variable is defined, except that the array name is followed by one or more expressions, enclosed within square brackets, [ ], specifying the array dimension. The general syntax of an array definition is:

storage_class data_type array_name|size_expr]

Here, size_expr is an expression denoting the number of members in the array and must evaluate to a positive integer. Storage class is optional. The array defaults to class automatic for arrays defined within a function or a block and external for arrays defined outside a function. The array player will therefore, be declared as

int player[11]

Remember that while defining the array, the array size will be 11, though the indices of individual members of the array will range from 0 to 10.

The rules for forming array names are the same as those for variable names. An array name and a variable name cannot be the same as it leads to ambiguity. If such a declaration is given in a program, the compiler displays an error message.

Some Norms With Arrays

  • All elements of an array are of the same type. This means that if an array is declared of type int, it cannot contain elements of any other types.
  • Each element of an array can be used wherever a variable is allowed or required.
  • An element of an array can be referred using a variable or an integer expression. The following are valid references:
player li]; /* Where i is a variable, though care has to be 
taken that i is within the range of the 
defined subscript for the array player.*/ 
player (3] - player|2] + 5; 
player [0] += 2: 
player [1/2+11;
  • Arrays can have their data type as int, char, float, or double.

Handling

Arrays in C

An array is treated differently from a variable in C. Two arrays, even if they are of the same type and size, cannot be tested for equality. Moreover, it is not possible to assign one array directly to another. Instead each array element has to be assigned separately to the corresponding element of another array. Values cannot be assigned to an array as a whole, except at the time of initialization. However, individual elements can not only be assigned values but can also be compared.

int player1(11], player2[11];
for(1=0:1<11;1++)
player1[i]= player2[i];

The same can also be attained by using separate assignment statements as follows:

player1[0] - player2[0]; 
player1(1] - player2|1];
.
.
player1(10] - player2(10];

The for construct is the ideal way of manipulating arrays

Example

/* Program demonstrates a single dimensional array */ 
#include <stdio.h›
void main ()
{
int num [5];

int i;

num [0] = 10;

num [1] = 70;

num [2] - 60;

num [3] - 40;

num [4) = 50;

for (1=0:1<5:1++)

printf ("\n Number at [8d] is id", i, num[i]) ;


}

Output

Number at [0] is 10

Number at [1] is 70

Number at [2] is 60

Number at [3] is 40

Number at [4] is 50

Array Initialization

Automatic arrays cannot be initialized, unless each element is given a value separately. Automatic arrays should not be used without proper initialization, as the results in such cases are unpredictable. This is because the allocated storage locations assigned to the array are not automatically initialized.

Whenever elements of such an array are used in arithmetic expressions, the previously existing values will be used, which are not guaranteed to be the same type as the array definition, unless the array elements are very clearly initialized. This is true not only for arrays but also for ordinary variables.

In the following code snippet, the array elements have been assigned values using a for loop

int ary[201,1;
for (1=0:1<20:i++)
     ary[i] - 0;

Initializing an array using the for loop can be done using a constant value or values which are in arithmetic progression.


The for loop can also be used to initialize an array of alphabets as follows:

Example

#include <stdio.h›
void main ()
{

   char alpha [26];
   int i, j:
   For(1=65,コー0;1<91:i++, j++)
   {
       alpha[j] = i;
       printf ("The character now assigned is : \n", alpha[j]);
   }
   getchar () ;
}

Output

The character now assigned is A 
The character now assigned is B
The character now assigned is C

The above program assigns ASCll character codes to the elements of the character array alpha. This, when printed using the %c specifier, results in a series of characters printed one after the other. Arrays can be initialized when they are defined. This can be done by assigning a list of values separated by commas and enclosed in curly braces {} to the array name. The values within the curly braces are assigned to the elements of the array in the order of their appearance.

Example

int deci [10] = 10, 1, 2, 3, 4, 5, 6, 7, 8, 9};
static float rates[4] = {0.0, -2.5, 13.75, 18.0};
char company [5]= {A',P',P',"L',E'};
int marks [100] - (15, 13, 11, 9}

Arrays deci, company and marks are assumed to be external arrays by virtue of their position in the program. The initializing values must be constants and cannot be variables or expressions. The first few elements of the array will be initialized if the number of initializing values is fewer than the defined array dimension. The remaining elements will be initialized to zero.

For example, in array marks after the above initialization, the first four elements (0 through 3) are initialized to 15, 13, 11 and 9 respectively. The rest of the elements are initialized to the value zero. It is not possible to initialize only elements 1 through 4, or 2 through 4, or 2 through 5 when initialization is done at the time of declaration. There is no facility in C to specify repetition of an initializing value.

In case of an explicit initialization, class extern or static, the array elements are guaranteed (unlike class auto) to be initialized to zero.

It is not necessary to declare the size of the array that is being initialized. If the size of the array is omitted, the compiler will compute the array size by counting the initializing values. For example, the following external array declaration will assess the dimension of the array ary to be 5 as there are five initializing values.

int ary [] = {1, 2, 3, 4, 5} ;

String / Character Arrays

A string can be defined as a character type array, which is terminated by a NULL character. Each character of a string occupies one byte and the last character of a string is always the character 10′. This ‘\0’ is called the null character. It is an escape sequence like ‘\n’ and stands for a character with a value of 0 (zero). As I0′ is always the last character of a string, character arrays have to be one character longer than the longest string they are required to hold. For example, an array, for example ary, that holds a 10- character string should be declared as:

char ary [11];

The additional location is used for storing the null character. Remember that the ending character (null character) is very important.

The string values can be input using the scanf () function. For the string ary declared above, the code statement to accept the value will be as follows:

scanf ("&s", ary) ;

In the above statement, ary defines the location where the successive characters of the string will be stored.

Example

#include ‹stdio.h>
void main ()
{
     char ary[5];
     int i;
     printf("\n Enter string :" );
     scanf ("is", ary) ;
     printf("n The
     string is %s \n\n", ary);
     for (1=0; i<5; i++)
         printf("|t&d", ary[i]);
}

The outputs for various inputs are as follows:

If the entered string is appl, the output will be:

The string is appl
97 112 112 1 08 0

The input for the above is of 4-characters (appl) and the 5th character is the null character. This is clear from the ASCIl codes for the characters printed in the second line. The fifth character is printed as 0, which is the value of the null character.

If the entered string is apple, the output will be:

The string is apple
97 112 112 108 101

The above output is for an input of 5 characters namely a, p, p, I, & e. This is not considered a string because the 5th character of this array is not 10. Again, this is clear from the line giving the ASClI codes of the characters a, p, p, l, e.

If the entered string is ap, the output will be as shown below.

The string is ap
97 112 0 6 100

In the above example, when only two characters are entered the third character is the null character. This actually indicates that the string has ended. The remaining characters are unpredictable character.

In the above case, the importance of the null character becomes clear. The null character actually specifies the end of the string and is the only way in which functions that work with the string will know where the end of string is.

Although C does not have a string data type, it allows string constants. A string constant is a list of characters enclosed in double quotes(“”). Like any other constant, it cannot be altered in the program. An example is,

“Hi Learner!”

The null character is added automatically at the end of the string by the C compiler.

C supports a wide range of string functions, which are found in the standard header file string.

arrays

Two Dimensional Arrays

So far, we have dealt with arrays that were single-dimensional arrays. This means that the arrays had only one subscript. Arrays can have more than one dimension. Multidimensional arrays make it easier to represent multidimensional objects, such as a graph with rows and columns or the screen of the monitor. Multidimensional arrays are defined in the same way as single-dimensional arrays, except that a separate pair of square brackets [], is required in case of a two dimensional array. A three dimensional array will require three pairs of square brackets and so on. In general terms, a multidimensional array can be represented as

storage_class data_type ary|expil [exp2]... [expN;

Where ary is an array having a storage class storage_class, data type data _type, and exp1, exp2, up to expN are positive integer expressions that indicate the number of array elements associated with each subscript.

The simplest and most commonly used form of multidimensional arrays is the two-dimensional array. A two dimensional array can be thought of as an array of two ‘single-dimensional’ arrays. A typical two-dimensional array is the airplane or railroad timetable. To locate the information, the required row and column is determined, and information is read from the location at which they (the row and column) meet. In the same way, a two-dimensional array is a grid containing rows and columns in which each element is uniquely specified by means of its row and column coordinates. A two-dimensional array tmp of type int with 2 rows and 3 columns can be defined as,

int tmp [2] [3];

Initialization of Multidimensional Arrays

A multidimensional array definition can include the assignment of initial values. Care must be taken regarding the order in which the initial values are assigned to the array elements (only external and static arrays can be initialized). The elements of the first row of two-dimensional array will be assigned values first, and then the elements of the second row, and so on. Consider the following array definition:

int ary (3] [4] = {1, 2, 3, 4, 5, 6, 7,8, 9, 10, 11, 12};

The result of the above assignment will be as follows:

ary[0][0] = 1 ary [0] [1] = 2 ary [0][2] = 3 ary [0] [3] = 4
ary (1][0] = 5 ary [1][1] = 6 ary[1][2] = 7 ary (1] [3] = 8
ary [2][0] = 9 ary [2](1] = 10 ary[2][2]=11 ary[2][3]=12

Note that the first subscript ranges from 0 to 2 and the second subscript ranges from 0 to 3. A point to remember is that array elements will be stored in neighbouring (side by side) locations in memory. The above array ary can be thought of as an array of 3 elements, each of which is an array of integers, and will appear as,

arrays

The natural order in which the initial values are assigned can be altered by forming groups of initial values enclosed within braces. Consider the following initialization.

int ary [3] [4] ={
(1, 2, 3),
14, 5, 6},
1, 8, 9}
};

Two-dimensional Arrays and Strings

As seen earlier, a string can be represented as a single-dimensional, character-type array. Each character within the string will be stored within one element of the array. This array of the string can be created using a two-dimensional character array. The left index or subscript determines the number of strings and the right index specifies the maximum length of each string. For example, the following declares an array of 25 strings, each with a maximum length of 80 characters including the null character.

char str_ary [25] [80] ;

Summary

  • An array is a collection of data elements of the same type that are referenced by a common name.
  • Each element of the array has the same data type, same storage class and common characteristics.
  • Each element is stored in successive locations of the main store. The data elements are known as the members of the array.
  • The dimension of an array is determined by the number of indices needed to uniquely identify each element.
  • Arrays can have the data type as int, char, float, or double.
  • The element of an array can be referred using a variable or an integer expression.
  • Automatic arrays cannot be initialized, unless each element is given a value separately.
  • The extern and static arrays can be initialized when they are defined.
  • A two-dimensional array can be thought of as an array of single-dimensional arrays.