=====
CS 111 - Week 14 Lecture 1 - 2024-12-03
=====
=====
TODAY WE WILL:
=====
* announcements
* how to write a function with an array parameter
* prep for next class
=====
* Should be working on Homework 11!
* at least first attempts in by 11:59 pm Friday, Dec. 6
=====
* (staticly-allocated) array in C++:
* to declare:
desired_type desired_name[desired_size];
* desired_size expression MUST be of type int
* to acces one of its elements
desired_name[desired_index]
* index of the 1st element is 0!
(0 steps from the beginning of the array)
* desired_index expression MUST be of type int
* when you have just declared an array,
you SHOULD NOT assume what is in it yet!!
(need to INITIALIZE its values!)
* you can just assign its values, one at a time
string things[3];
things[0] = "rock";
things[1] = "paper";
things[2] = "scissors";
* you can use a loop:
string things[3];
int index = 0;
while (index < 3)
{
things[index] = "";
index = index + 1;
}
* OR -- JUST at the time of declaration --
you can initialize an array by following its
declaration with an assignment operator (=)
and a set of curly braces containing the desired
comma-separated list of initial values
string things[3] = {"desk", "chair", "lamp"};
=====
can a function have an array as a parameter?
YES! but note:
=====
* ...a C++ array does not "know" its size
...C++ "sees" the array as where it BEGINS
...this is useful! because it allows functions
with array parameters to be usable
with array arguments of any size!
...(and it is efficient enough, because the array argument
is passed by copying over the location where it starts,
instead of copying over the entire array)
...in the meantime, since that poor function does not
have a reasonable way to determine how big its
array argument is,
it is considered GOOD PRACTICE to also include a parameter
giving the array's size
=====
EXAMPLE 1
=====
* let's write a function to sum all of the values in a array
of doubles!
* NOTE: in a function signature comment, we'll indicate an
array parameter's type by giving the type of its elements
followed by empty square brackets:
* // signature: sum_array: double[] int -> double
* to declare an array parameter in the function header,
put the array's element-type, then its name, then EMPTY
square brackets
blah(... desired_type desired_name[], int desired_size, ...)
* at the parameter end, its size is NOT yet known,
but when the array argument is declared, it WILL have a size!
* and, to pass an array as an ARGUMENT,
JUST give its NAME! <-- NO square brackets!
* so a function with a header such as:
double sum_array(double nums[], int size)
* if another function (main or otherwise) had:
double prices[4] = {2.99, 3.00, 4.01, 1.00};
then it could have this statement printing the
value of calling sum_array with this argument array
and its size:
cout << sum_array(prices, 4) << endl;