Showing posts with label Function. Show all posts
Showing posts with label Function. Show all posts

Saturday, August 29, 2009

Arrays as parameters

Even though call-by-value is the default parameter-passing mechanism in C++, arrays as parameters have some special features. Placing a pair of brackets ( [] ) after the name of a parameter indicates that the parameter is an array:

double arraySum( double array[ ], int array_size )
{
    double sum = 0.0;

    int i = 0;
    while( i < array_size )
    {
        sum = array[ i ] + sum;
    }
    return sum;
}

It is not necessary to specify the capacity of the array. There is no restriction on the capacity of the array passed to the function. It is necessary to use another parameter or a constant to pass the size of the array to the function.

Arrays are automatically passed by reference, i.e. specifying a parameter as an array makes it a reference parameter without the ampersand ( & ). If the function modifies the array, the corresponding argument will also be modified. This can be avoided by declaring the array as a constant reference parameter.

Let's take a larger example:

#include <cstdlib>
#include <iostream>

using namespace std;

const int MAX_NUMBER = 1000;
const int ERROR = -1;
const double END_NUMBER = -1.0;

int readNumbers( double numbers[ ] );
double calculateMean( const double numbers[ ], int how_many );

int main( void )
{
    double numbers[ MAX_NUMBERS ];
    int how_many_read = 0;

    how_many_read = readNumbers( numbers );

    if( how_many_read == ERROR )
    {
        return EXIT_FAILURE;
    }

    cout << "Mean value is: "
         << calculateMean( numbers, how_many_read )
         << endl;

    return EXIT_SUCCESS;
}

int readNumbers( double numbers[ ] )
{
    int how_many = 0;

    //we know that there is room for MAX_NUMBERS
    //amount of space in teh array
    while( how_many < MAX_NUMBERS )
    {
        cout << "Give "
             << how_many + 1
             << ". number: ";

        //The number is read from the input into
        //the array the change modifies the
        //coresponding argument
        cin >> numbers[ how_many ];

        if( numbers[ how_many ] == END_NUMBER )
        {
            return how_many;
        }
        ++how_many;
    }
    //if how_many got too large, and error has occured
    return ERROR;
}

double calculateMean( const double numbers[ ], int how_many )
{
    double sum = 0.0;
    int i = 0;

    if( how_many == 0 )
    {
        return sum;
    }

    //in this function the actual size of
    //the array doesn't matter. It is important
    //to know fo how many numbers the mean is
    //supposed to be calculated from
    while( i < how_many )
    {
        sum = sum + numbers[ i ];
        ++i;
    }
    return sum / how_many;
}


The other alternative woule have been:

int readNumbers( const double numbers[ ], int size )
{
    int how_many = 0;
    //now the size of the array is given as parameter
    while( how_many < size )
    {
        cout << "Give "
             << how_many + 1
             << ". number: ";
        //The number is read from the input
        //into the array the change modifies
        //the corresponding argument
        cin >> numbers[ how_many ];

        if( numbers[ how_many ] == END_NUMBER )
        {
            return how_many;
        }
        ++how_many;
    }
    //if how_many got too large, an error has occured
    return ERROR;
}

It would have been called in main:

how_many_read = readNumbers( numbers, MAX_NUMBERS );

The latter is recommended since the result can be used more widely.


Reference: cplusplus, macs, msdn


Previous post

Next post




Functions: Parameter-passing mechanisms

The simplest parameter-passing mechanism in C++ occurs by default. It is called call-by-value. Value passed using this method are called value parameters. Any modification of a value parameter within the function body has no effect on the value of its corresponding argument:

void divideByTwo( int parameter )
{
    parameter = parameter / 2;
}

int main( void )
{
    int figure = 42;

    divideByTwo( figure );
    cout << figure << endl;

    return EXIT_SUCCESS;
}

prints 42 as a result.

It would be often useful to be able to change the value of the corresponding argument. For example, if the function needs to return more than one value, data could be returned by changing the value of the parameters. There is also call-by-reference mechanism in C++. These parameters are called reference parameters. Reference parameters are aliases of their corresponding arguments, i.e. any change to the value of a reference parameter within the function body changes the value of its corresponding argument. When using call-by-reference, the values are passed by adding an ampersand (&) between the type and the name of the parameter.

The example mentioned before:

void divideByTwo( int& parameter )
{
    parameter = parameter / 2;
}

int main( void )
{
    int figure = 42;

    divideByTwo( figure );
    cout << figure << endl;

    return EXIT_SUCCESS;
}

prints now 21, i.e. function divideByTwo was able to change the actual value of the parameter.


Reference: msdn, comp, brpreiss


Previous post

Next post




Monday, August 24, 2009

Why the function is a programmer's best friend?

Function is a programmer's best friend because at least all these can be achieved with the help of functions:
  • Well-chosen function names make the program more understandable and say something about the functionality
  • Functions save time and effort. Often used actions need to be programmed only once
  • Errors need to be fixed in one place only
  • Changing the functionality of the program is easier when the change needs to be done in only one place
  • Functions are an important tool in structuring the program. The program can have a better manageable structure (divide and conquer) with the help of functions



Reference: blog, ddj, scribd


Previous post

Next post




Sunday, August 23, 2009

Where do little functions come from?

It is rather easy to find potential functions from a carefully planned algorithm:
  • Any part of the algorithm that needs clarification is usually sensible to be implemented as a function
  • Any part of the algorithm that is repeated several times as such in the algorithm
With the help of these simple rules a programmer already gets far. Experience and practice give more perspective. It is good to remember what has been said about the length of functions: preferably no longer than what fits on the screen.

Functions with a return type are found the same way by reading the algorithm carefully. Additionally one must think what kind of information each function needs to give back to its caller (if any).

Often a function can be recognized as an action that is a part of a statement:

    IF discriminant == 0 THEN
or
    print the equivalent fahrenheit temperature to temperature in centigrade
or
    social security number <--- ask for the user's social security number

where potential functions are in italics.

A function can take two or more lines in the algorithm. Be careful!

prompt the user and ask for his/her social security number
read the user's input
WHILE the input is not a legal social security number
    print an error message
    prompt the user and ask for his/her social security number
    read the user's input
social security number <--- user's input

The actions in italics together form a function called askForSocialSecurityNumber()


Previous post

Next post




Function declaration and definition

A function definition includes the program code of the function entirely. For example, the definition of printMultiples:

void printMultiples( int multiplier )
{
    cout << "| " << multiplier << " |";

    int multiplicant = 1;
    while( multiplicant <= 9 )
    {
        cout << setw(3) << multiplier*multiplicant;
        ++multiplicant;
    }

    cout << " |" << endl;
}


A function declaration specifies the characteristics:
  • The name of the function
  • The number of parameters
  • The type of each paramete
  • The return type of the function

Declaration has the form:
return_type Function_name(formal_parameters);

For example:
void printMultiples( int multiplier );

A function declaration is also called the function prototype. The declaration has all the information about the function the compiler needs in order to be able to check whether the function call in the code is legal, i.e. is semanctically correct.

The definition has all the information of the declaration, but it also included the body of the function. In practice:
  • A function must always be defined (only once) somewhere in the program code
  • A function must always be either declared or defined before it is called of the first time so that the compiler can check the code for errors
  • A function cannot be defined within another function definition



Previous post

Next post




Saturday, August 22, 2009

Function that returns a value

Functions seen so far don't have a return value, i.e. their return type is void. They can, however, have any data type as a return type. i.e. the function returns data back to where it was called. A function call evaluates a value that can be used as a parameter for other functions, as an operand of operators etc. A C++ function definition is as follows:

return_type function_name ()
{
     function_body
}

or if the function has parameters:

return_type function_name (formal_parameters)
{
     function_body
}

All the same rules and characteristics apply to function name and formal parameters as for void functions. The return type is in every function definition ( and declaration ) and is the type of the value the function returns. The return type defines where the function can be called. The return_type can be any data type.

The function body can be any sequence of executable statements. For example:

double area( double x, double y )
{
     double result = x*y;
     return result;
}

return result; is called a return statement. It terminates the function execution and indicates the value given as the result of the function to the caller. One return statement must always get executed. The syntax of the return statement:

return return_value;

return immediately terminates the execution of the function and the execution continues from where the function was called. The value of the return_value decides to which value the function evaluates in the expression where it was called. The return_value must be of the same type as the return_type of the function.

There can be more than one return statement on the function body. The execution returns from the function immediately when one of the return statements is executed.

double absoluteValue(double x)
{
     if ( x > 0 )
     {
          return x;
     }
     else
     {
          return -x;
     }
}

Also the execution of a void function can be terminated with return. It is just used without the return_value:

return;

Information is passed only into one direction between the caller and a function (caller -> function) when the function does not return a value. Information is passed into both directions between the caller and a function (caller <==> function) when the function returns a value. A function can return only one value at a time. void is in fact a datatype without a value (an "empty" data type). The same rules apply to the declaration and definition of all kinds of functions.


Previous post

Next post




Function

Functions can be used to structure the program by breaking it into smaller, more manageable units. The goal of using functions is again to break difficult and large problems into smaller and smaller pieces until the pieces are small and simple enough. The program is completed by combining the small pieces to work together.

In C++ a function is defined:

void Function_name ()
{
     The body of the function
}

or if the function has parameters:

void Function_name (formal_parameters)
{
     The body of the function
}

Function name is an identifier that names the function. Function name can be any name that is valid as variable name. It is sensible to choose a name that describes well what the function does. It makes the program more understandable.

The body of the function is a sequence of statements that describe the behavior of the function. Since the idea of functions is to break a large problem into more manageable parts the body shouldn't be too long. A good rule of thumb:

When the function takes more lines than fit the screen think hard how it could be divided into two or more functions that together have the same functionality.

Formal parameters is a list of declarations of the function's parameters, separated by commas. The formal parameters defined in the parameter list function like normal local variables in the function body except that they are automatically assigned the values given when the function is called with actual parameters. So formal parameters are a kind of "dummy" parameters and they are bound to actual parameters only when the function is called. A function can gain access to data and process that data through formal parameters. A function can have several parameters or none depending on the situation. The body of the function is executed by calling the function.

A function call:

The name of the function and then in parentheses expressions
  • int the same order
  • the same amount
  • of the same type


As the formal parameters define (empty parentheses if there are no parameters) and ;

When the function is called, the execution is transferred to the first executable statement in the body. When the last statement in the function has been executed, the program execution returns to the point from which the function was called.


Previous post

Next post