Monday, January 26, 2009

Arrays in C language

In C, as in Fortran or PL/I, it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration
int x[10];
The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are
x[0], x[1], x[2], ..., x[9]
If an array has n elements, the largest subscript is n-1.
Multiple-dimension arrays are provided, though not much used above two dimensions. The declaration and use look like
int name[10] [20];
n = name[i+j] [1] + name[k] [2];
Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row (opposite to Fortran), so the rightmost subscript varies fastest; name has 10 rows and 20 columns.
Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end).

main( )
{
int n, c;
char line[100];
n = 0;
while( (c=getchar( )) != '\n' ) {
if( n < 100 )
line[n] = c;
n++;
}
printf("length = %d\n", n);
}

As a more complicated problem, suppose we want to print the count for each line in the input, still storing the first 100 characters of each line. Try it as an exercise before looking at the solution:

main( )
{
int n, c; char line[100];
n = 0;
while( (c=getchar( )) != '\0' )
if( c == '\n' ) {
printf("%d0, n);
n = 0;
}
else {
if( n < 100 ) line[n] = c;
n++;
}
}

No comments:

Post a Comment