This class is just going to look at functions that operate on arrays, and the few new concepts that arise with them.
In reality, there's nothing new at all! It's just that the consequences of the following fact:
readints()
which creates an array A and read N integers from input
int* A = readints(N, "numbers.txt");
sum()
to compute the average:
double average = sum(A,N) / double(N);
int* readints(int N, string filename);
This function should return an array of N
int
s, populated with values read in from a file named filename
.
int* readints(int N, string filename) {
// Create the array
int* B = new int[N];
// Open the file
ifstream fin(filename);
// Read values into the array
for( int i = 0; i < N; i++ )
fin >> B[i];
fin.close();
// Return pointer to array
return B;
}
int
s still exists when the function call
returns, because memory allocated with new
has no scope or
lifetime.
In summary:
new
.
new
.
sum()
is as follows:
int sum(int* A, int N);
Note about the pointer A:
(Thus, some people will say that arrays are always "passed by reference" in C++ (that's a technical term that we'll discuss later). Well, really what happens is that arrays themselves are not passed, rather pointers to the arrays are what we pass, and receiving a copy of the pointer still allows us to modify the actual array.)
A
.
int
sum(int* A, int N);
. 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;
}
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
int
s, 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.