Comment

Puzzles D01 ... D10

Part D — 1D Arrays


These puzzles involve arrays. Arrays are extremely important in programming. All programs of any importance use many arrays. If you wish to be a programmer, you must become familiar with arrays.

Arrays in C are not as flexible as array objects in an object-oriented language such as Java. An array in C is a block of memory conceptually divided into individual cells that are accessed using an index. There are no instance variables or methods associated with an array. Because of this, the parameters to a function that processes an array includes the length (the number of cells):

void printArray( int length, int array[] )
{

}

With some C compilers, the length of every array in the program must be known at compile time. The length of an array cannot be determined from data as the program runs. Programs look like this:

#define SIZE 25
. . .

int array[SIZE];
. . .

Some compilers allow constants for this:

int const SIZE=25;

. . .

int array[SIZE];

. . .

And some others (such as gcc) let you do this:

void main()
{
  int size;
  printf("enter size: ");
  scanf("%d", &size);
  int array[size];        /* the array, a local variable, size determined at run-time */
  . . .
}

Most of the puzzles assume that array size (length) is fixed at compile-time. The size is hard-coded. But for some puzzles the array size is determined as the program runs. This does not work with all C environments, so you may have to adjust your own code.



Next Page         Home