EECS 211
How to read Chapter 7

Chapter 7 is primarily about arrays. Arrays are the last big missing piece. With arrays, we can start to do some real programming.

Since almost every programming language has arrays or something very similar, and you already know at least one other programming language, this chapter should be mostly review. The main things you need to know are

How to Use Arrays

How to Loop Through an Array

The many examples show the standard way to loop through an array -- with a for loop, using a counter called i, from 0 to N, where N is the size of the array, e.g.,

for (int i = 0; i < n; ++i)
{
   ...a[i]...
}

How to Pass an Array to a Function

The examples also show how to pass an array to a function. For generality, you pass the array with [], which means the length can be anything, plus the actual number of elements, e,g., ;.

int foo ( int a[], int length )
{
  for (int i = 0; i < length; ++i)
  {
     ...a[i]...
  }
}

How to Pass an Multi-dimensional Array to a Function

Although multi-dimensional arrays are easy to declare and use, they're fairly tricky to pass to functions. In order to know the distance from the first element of row i (a[i][0]) to the first element of the next row (a[i+1][0], the compiler has to know how many elements (columns) are in each row. So you can't write void func(int a[][], int rows, int cols), you have to write void func(int a[][cols], int rows), and cols has to be a constant integer. This makes the function not very general.

There is a way to do this with pointers, but it's less readable than normal array use.

Fortunately, much of the time, your arrays will be data members of classes, accessed only by member functions, and they will not need to be passed as parameters.

How C++ Arrays are Different

How C/C++ arrays differ from some other languages: