sábado, 30 de noviembre de 2013

Arrays in Functions

Indexed variables can be arguments to functions.  For example, if a program contains these declarations:

int i, n, a[10];
void my_function(int n);

Variables a[0] through a[9] are of type int, making these calls legal:

my_function(a[0]);
my_function(a[3]);
my_function(a[i]);

A formal parameter can be for an entire array, such a parameter is called an array parameter it is not a call-by-value or call-by-reference parameter.
An array parameter is indicated using empty brackets in the parameter list such as:

void fill_up(int a[], int size);

Function Calls with Arrays

If function fill_up is declared in this way: void fill_up(int a[], int size); 
and array score is declared this way:  int score[5], number_of_scores;
fill_up is called in this way:  fill_up(score, number_of_scores);

An array argument does NOT use the empty brackets.

fill_up(score, number_of_scores);

When an array is an argument in a function call, an action performed on the array parameter is performed on the array argument.  The value of the indexed variable can be changed by the function.

Because a function does not know the size of an array argument, the programmer should include a formal parameter that specifies the size of the array.  The function can process arrays of various sizes.

Using const in Arrays

Array parameters allow a function to change the value stored in the array argument.  If a function should not change the values of the array arguments, use the modifier const.  For example:

void show_the_world (const int a[], int size);

const is used to modify an array parameters in the function declaration and definition.

If a function with a const array parameter calls another function using the const array parameter as an argument, the called function must use a const array parameter as a placeholder for the array.

Problem example using const parameters:

double compute_average(int a[ ], int size);
void show_difference(const int a[ ], int size)
{
double average = compute_average(a, size);

}

compute_average has no constant array parameter
This code generates an error message because compute_average could change the array parameter.



Recall that function can return a value of type int, double, char, or a class type
Functions cannot return arrays

Partially Filled Arrays

When using arrays that are partially filled, functions dealing with the array may not need to know the declared size of the array, only how many elements are stored in the array.

Searching Arrays

A sequential search is one way to search an array for a given value:
  • Look at each element from first to last to see if the target value is equal to any of the array elements.
  • The index of the target value can be returned to indicate where the value was found in the array.
  • A value of -1 can be returned is the value was not found.


No hay comentarios.:

Publicar un comentario