Next: Checkoff
Up: Arrays as Arguments
Previous: Array Elements as Arguments

Arrays as Arguments

You can also pass entire arrays, not just individual elements, as arguments. Why in the world would you want to do that?

Click here for an answer

Let's try to get you thinking in this direction. Try to imagine some useful functions and subroutines that would take arrays as arguments. Remember: a function should return a value without modifying its arguments, and a subroutine does not return a value but usually modifies one or more arguments.

Click here for some possibilities

Actually, the third example above is a bad example, because functions may not return arrays as results. What approach can you take if you want to implement the third example anyway?

Click here for the answer

The key idea is that any changes made to an array in a subroutine will be apparent at the point of call.

Let's take a look at a subroutine that implements possibility (c) above, as subsequently modified. Look at ``aparm2.f'' (or view it directly). Compile and run it.

Here are a few things to notice:

  1. As always, we can use different names for the arrays in the subroutine (X, Y, and Z) and the main program (A, B, and C). This is no different from when we pass other kinds of arguments.

  2. As we compute the dot product of X and Y, we assign the result to Z. This has the effect of modifying the corresponding actual argument (C) in the main program. Again, this is no different from when we pass other kinds of arguments.

  3. Both the dummy arguments (X,Y,Z) and the actual arguments (A,B,C) are declared to be arrays of size 5. This is very restrictive. Why?

    Click here for the answer

  4. Notice how easy it is to print out all of the elements of an array. What would you do if you wanted to print out only some of the elements of an array?

    Click here for an answer

Try modifying ``aparm2.f'' so that it computes the sum of the corresponding elements of A and B instead of the product.


Next: Checkoff
Up: Arrays as Arguments
Previous: Array Elements as Arguments

Hamlet Project
hamlet@cs.utah.edu