Array Objectives: The Syntax For Declaring An Array in C Example
Array Objectives: The Syntax For Declaring An Array in C Example
Objectives
At the end of this topic, the students will be able to aware of the importance of using the array in their
programming applications, when to use it properly and how to implement array. It also covers the basic
operations of the single–dimensional and two–dimensional array such as how to initialize the array, how
to fill-up elements, how to retrieved specific data element, the proper naming and declaration, the
equivalence between Pointers and Arrays, array implementation using function passed by reference and
so on.
What Is an Array?
An array is a collection of data storage locations, each having the same data type and the same name.
Each storage location in an array is called an array element. Why do you need arrays in your programs?
This question can be answered with an example. If you're keeping track of your business expenses for
1998 and filing your receipts by month, you could have a separate folder for each month's receipts, but it
would be more convenient to have a single folder with 12 compartments.
Single-Dimensional Arrays
A single-dimensional array has only a single subscript. A subscript is a number in brackets that follows an
array's name. This number can identify the number of individual elements in the array. An example should
make this clear. For the business expenses program, you could use the following line to declare an array
of type float:
The syntax for declaring an array in C
Data_type ArrName[#ofElements];
Example
int a[10];
char arrChar[6];
float expenses[2];
The array is named a as an expenses in every month, and it contains 10 elements. Each of the 10
elements is the exact equivalent of a single int variable. All of C's data types can be used for arrays. C
array elements are always numbered starting at 0, so the 12 elements of expenses are numbered 0
through 11. In the preceding example, January's expense total would be stored in a[0], February's in a[1],
and so on.
When you declare an array, the compiler sets aside a block of memory large enough to hold the entire
array. Individual array elements are stored in sequential memory locations as shown in the figure below.
Example declaration
Int a[10];
The allocated memory block for the above array declaration.
In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9. The
subscript that specifies a single element of an array is simply an integer expression in square brackets.
The first element of the array is a[0], the second element is a[1], etc. You can use these ``array subscript
expressions'' anywhere you can use the name of a simple variable, for example:
a[0] = 1; // 1
a[1] = 3; // 2
a[2] = a[0] + a[1]; // 3
a: 1 3 4
In the first expression, the first location of the array a is a[0] in which the integer value 1 is stored. The
second location is at a[1] where it contains a value 3 based on the expression 3. The third location
contains a value from the summation of the element of a[0] and a[1] which is 1 + 3 respectively.
The subscript does not have to be a constant like 0 or 1; it can be any integral expression. For example,
it's common to loop over all elements of an array:
int i;
for(i = 0; i < 10; i = i + 1)
a[i] = 0;
This loop sets all ten elements of the array a to 0.
a 0 0 0 0 0 0 0 0 0 0
In array, you can neither set all elements of an array at once nor assign one array to another; both of the
assignments
a = 0; /* WRONG */
and
int b[10];
b = a; /* WRONG */
are illegal.
To set all of the elements of an array to some value, you must do so one by one, as in the loop example
above. To copy the contents of one array to another, you must again do so one by one:
Copying an array without a helper function. Copying an array using a helper function.
1: #Iinclude <stdio.h> 1: #include <stdio.h>
2: #include <conio.h> 2: #include <conio.>
3: void main() { 3:
4: int a[5] = { 1, 2, 3, 4, 5 }; 4: void copy(int *source, int *dest, int size);
5: int b[5]; 5:
6: int I; 6: void main() {
7: for (i = 0; i < 5; i++) 7: int a[5] = { 1, 2, 3, 4, 5 };
8: b[i] = a[i]; 8: int b[5];
9: } 9: copy(a, b, 5);
10: }
11:
12: void copy(int *source, int *dest, int size) {
13: int I;
14: for (i = 0; i < size; i++)
15: dest[i] = source[i];
16: }
Each elements in the array a is copied to the array b in which the size of array b must be equal to array a.
An array element can be used in your program anywhere a non-array variable of the same type can be
used. Using the array name followed by the element subscript enclosed in square brackets accesses
individual elements of the array. For example, the following statement stores the value 89 in the second
array element (remember, the first array element is a[0], not a[1]):
a[1] = 89;
a[10] = a[11];
assigns a copy of the value that is stored in array element a[11] into array element a[10]. When you refer
to an array element, the array subscript can be a literal constant, as in these examples. However, your
programs might often use a subscript that is a C integer variable or expression, or even another array
element. Here are some examples:
float expenses[100];
int a[10];
/* additional statements go here */
expenses[i] = 100; /* i is an integer variable, the location of the element in an array depends on
the value of the variable i */
expenses[2 + 3] = 100; /* equivalent to expenses[5] */
expenses[a[2]] = 100; /* a[] is an integer array */
That last example might need an explanation. If, for instance, you have an integer array named a[] and
the value 8 is stored in element a[2], writing
expenses[a[2]]
expenses[8];
When you use arrays, keep the elements numbering scheme in mind: In an array of n elements, the
allowable subscripts range from 0 to n-1. If you use the subscript value n, you might get program errors.
The C compiler doesn't recognize whether your program uses an array subscript that is out of bounds.
Your program compiles and links, but out-of-range subscripts generally produce erroneous results.
WARNING: Remember that array elements start with 0, not 1. Also remember that the
last element is one less than the number of elements in the array. For example, an array
with 10 elements contains elements 0 through 9.
Array Initialization
Although it is not possible to assign to all elements of an array at once using an assignment expression, it
is possible to initialize some or all elements of an array when the array is defined. The syntax looks like
this:
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
The equivalent memory block of array a based on the above initialization expression.
0 1 2 3 4 5 6 7 8 9
a
The list of values, enclosed in braces {}, separated by commas, provides the initial values for successive
elements of the array.
When you declare an array, you can specify the number of elements with a literal constant (as was done
in the earlier examples) or with a symbolic constant created with the #define directive. Thus, the following:
#define MONTHS 12
int array[MONTHS];
is equivalent to this statement:
int array[12];
With most compilers, however, you can't declare an array's elements with a symbolic constant created
with the const keyword:
Initializing Arrays
You can initialize all or part of an array when you first declare it. Follow the array declaration with an equal
sign and a list of values enclosed in braces and separated by commas. The listed values are assigned in
order to array elements starting at number 0. For example, the following code assigns the value 100 to
array[0], 200 to array[1], 300 to array[2], and 400 to array[3]:
If you omit the array size, the compiler creates an array just large enough to hold the initialization values.
Thus, the following statement would have exactly the same effect as the previous array declaration
statement:
You can, however, include too few initialization values, as in this example:
int array[10] = { 1, 2, 3 };
If you don't explicitly initialize an array element, you can't be sure what value it holds when the program
runs. If you include too many initializers (more initializers than array elements), the compiler detects an
error.
There are a number of similarities between arrays and pointers in C. If you have an array
int a[10];
you can refer to a[0], a[1], a[2], etc., or to a[i] where i is an int. If you declare a pointer variable ip and set it
to point to the beginning of an array:
int *ip = &a[0];
you can refer to *ip, *(ip+1), *(ip+2), etc., or to *(ip+i) where i is an int.
There are also differences, of course. You cannot assign two arrays; the code
int a[10], b[10];
a = b; /* WRONG */
is illegal. As we've seen, though, you can assign two pointer variables:
int *ip1, *ip2;
ip1 = &a[0];
ip2 = ip1;
Pointer assignment is straightforward; the pointer on the left is simply made to point wherever the pointer
on the right does. We haven't copied the data pointed to (there's still just one copy, in the same place);
we've just made two pointers point to that one place.
The similarities between arrays and pointers end up being quite useful, and in fact C builds on the
similarities, leading to what is called ``the equivalence of arrays and pointers in C.'' When we speak of this
``equivalence'' we do not mean that arrays and pointers are the same thing (they are in fact quite
different), but rather that they can be used in related ways, and that certain operations may be used
between them.
The first such operation is that it is possible to (apparently) assign an array to a pointer:
int a[10];
int *ip;
ip = a;
What can this mean? In that last assignment ip = a, aren't we mixing apples and oranges again? It turns
out that we are not; C defines the result of this assignment to be that ip receives a pointer to the first
element of a. In other words, it is as if you had written
ip = &a[0];
The second facet of the equivalence is that you can use the ``array subscripting'' notation [i] on pointers,
too. If you write
ip[3]
So when you have a pointer that points to a block of memory, such as an array or a part of an array, you
can treat that pointer ``as if'' it were an array, using the convenient [i] notation. In other words, at the
beginning of this section when we talked about *ip, *(ip+1), *(ip+2), and *(ip+i), we could have written
ip[0], ip[1], ip[2], and ip[i]. As we'll see, this can be quite useful (or at least convenient).
The third facet of the equivalence (which is actually a more general version of the first one we mentioned)
is that whenever you mention the name of an array in a context where the ``value'' of the array would be
needed, C automatically generates a pointer to the first element of the array, as if you had written
&array[0]. When you write something like
int a[10];
int *ip;
ip = a + 3;
which (and you might like to convince yourself of this) gives the same result as if you had written
ip = &a[3];
len = p - string;
After the loop, p points to the '\0' terminating the string. The expression p - string is equivalent to p -
&string[0], and gives the length of the string. (Of course, we could also call strlen; in fact here we've
essentially written another implementation of strlen.)
Multidimensional Arrays
A multidimensional array has more than one subscript. A two-dimensional array has two subscripts, a
three-dimensional array has three subscripts, and so on. There is no limit to the number of dimensions a
C array can have. (There is a limit on total array size.)
For example, you might write a program that plays checkers. The checkerboard contains 64 squares
arranged in eight rows and eight columns. Your program could represent the board as a two-dimensional
array, as follows:
checker
0 1 2
0
1
2
Similarly, a three-dimensional array could be thought of as a cube. Four-dimensional arrays (and higher)
are probably best left to your imagination. All arrays, no matter how many dimensions they have, are
stored sequentially in memory.
The above initialization can have a tabular representation of the figure below.
0 1 2
0
1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
Or,
When you initialize multidimensional arrays, you can make your source code clearer by using extra
braces to group the initialization values and also by spreading them over several lines. The following
initialization is equivalent to the one just given:
int array[4][3] = { { 1, 2, 3 } , { 4, 5, 6 } ,
{ 7, 8, 9 } , { 10, 11, 12 } };
Remember that a comma must separate initialization values--even when there is a brace between them.
Also, be sure to use braces in pairs--a closing brace for every opening brace--or the compiler becomes
confused.
Filling–up a 2D Array
To illustrate the use of multidimensional arrays, we might fill in the elements of the above array a2 using
this piece of code:
Example:
Filling up a 2D array without helper function. Filling up 2D array with the help of a function.
1: #include <stdio.h> 1: #include <stdio.h>
2: #include <conio.h> 2: #include <conio.h>
3: 3:
4: void main() { 4: void fill(int multi[][7], int row, int col);
5: int a2[5][7]; 5:
6: int i, j; 6: void main() {
7: int count = 0; 7: int a2[4][7];
8: 8: fill(a2,4, 7);
9: for (i=0; i<5; i++) 9: }
10: for (j=0; j<7; j++) 10:
11: a2[i][j] = count++; 11: void fill(int multi[][7], int row, int col) {
12: } 12: int i, j;
13: int count = 0;
14: for (i=0; i<row; i++)
15: for (j=0; j<col; j++)
16: multi[i][j] = count++;
17: }
0 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 32 33 34
return bool;
}
Programming Exercises.
1. Write a C program that will accept ten integers and put them in a single dimension array. Find
and display the largest element in the array.
2. Implement problem 1 using a helper function to find the largest element in the array.
3. Write a C program that will fill a 2D array with integer numbers so that the sum of the elements in
each rows, each columns, and diagonals are equal. The row and column size should be equal
and odd numbers.
Sample Output.
8 1 6 15
3 5 7 15
4 9 2 15
15 15 15