We'll look at this stuff first from the prespective of our simple program from last class for computing averages. Here's that program. We're going to try and break it up into separate componants using functions. Essentially we'd like the bulk of the program to consist of these two function calls:
// Create array A and read N int's from input int *A = readints(N,cin); // Compute average double average = sum(A,N) / double(N);In defining these two functions, we'll see how arrays get passed in and out of functions.
int* readints(int N, istream &IN);. This
function should return an array of N
ints, populated with values read in from
IN. The basics of the function should be fairly
straightforward. The important thing is to understand what happens!
So, here's the function definition:
int* readints(int N, istream &IN)
{
// Create the array
int* B = new int[N];
// Read values into the array
for(int i = 0; i < N; i++)
IN >> B[i];
// Return pointer to array
return B;
}
And here's a pictorial depiction of what goes on. Notice that what
gets returned from the function is a point, not an actual
array. The array of ints does not disappear
when the function call returns, because memory allocated with
new has no scope or lifetime ... it just sticks
around until the end of the program, or until it's explicitly
destroyed with a call to delete, which we'll discuss
later.
![]() |
![]() |
![]() |
![]() |
![]() |
new
and return them by returning a pointer to the block of memory
allocated by the call to new.
So, getting back to our example, we need to implement the
function int sum(int* A, int N);. Notice that when
we pass an array to a function we always have to pass the length
of the array along with it, otherwise we have no idea how many
elements are in the array pointed to by A.
Hopefully the definition of this function looks straightforward.
int sum(int* A, int N)
{
int total = 0;
for(int i = 0; i < N; i++)
total = total + A[i];
return total;
}
The question is this: What really goes on when we run it?
Hopefully the pictures below, which illustrate what goes on in a
sample run of the above function, will make clear to you what
really goes on when arrays are passed to functions.
![]() |
![]() |
![]() |
![]() |
![]() |
contains predicate.
Write function
bool contains(string *A, int N, string s);
that tells you whether or not the string s is
contained in the array A.
getarray function.
Write a function
int* getarray(int N, int x);
that allocates and returns a pointer to an array of
N ints, each initialized to the
value x.
shiftleft function.
Write a function
double shiftleft(double *A, int N, double x);
that shifts all the elements in array A to the left by 1
position, puts the value x in the rightmost
position in the array, and returns the value that had
previously been in the leftmost position.
average function and the
shiftleft function to do the smoothing problem
from the last lab. Here's my solution.