Jan 11, 2002
Reading assignment:
Deitel and Deitel 4.1-4.5
We begin by completing the recursion example, the towers of Hanoi.
Here's the source code for the program from class today:
hanoi.cpp
Now we'll move on to arrays and strings:
Arrays:
- An array is a consecutive group of memory locations storing elements
of the same type
- Arrays are indexed starting at 0
- You can gain access to individual elements of an array using square
brackets. For example, arr[3] accesses the 4th element of array arr.
If you subscript an array, as in arr[3], you get an lvalue. This
means you can assign values to subscripted arrays, as in arr[3]=newvalue;
- Know how to declare and define them:
double arr[22]; or int arr[20] = {1, 2, 3};
If there are too many initializers, it's a syntax error, if there
are too few, the rest are set to 0
- You can arrays of objects too, as in
your_favorite_class obj_arr[YOUR_MAX_ARR_CONSTANT];
- If no size is given, the size is determined by the initializer, as in
int arr[] = {1,2,3,4,5}; defines a 5-element integer array
- If you don't initialize in the definition, you can do it with a loop
- Computations on arrays are typically done with loops - Examples in class
today and on next pencil-and-paper assignment
- To pass an array to a function, just put its name as the parameter.
You'll probably have to pass the length of the array as well.
Here's a prototype: void array_function_example(int b[], int arrlen);
If you think this is yucky, you're right - it's recommended to use
the vector class instead for a more robust system of using arrays.
We will learn this shortly.
- There's something a little funky about arrays when you pass them to
functions - It's actually an automatic pass by reference - the caller
can modify the values in the array.
- You can protect an array that you pass to a function by declaring
the parameter as const, as in
void array_function_example(const int b[], int arrlen);
- It's important to be able to sort the elements in an array and to
find elements in an array. There are many algorithms that have been
invented to do this - we'll study them shortly
Program from class today:
firstarrayprog.cpp