Absolute Beginners C++


Lesson 8 - Functions

8.1 Functions of one variable

// ex8-1.cpp - functions of one variable
#include <iostream>
using namespace std;
int treble(int x)
{
    return(3*x);
}
int main()
{
    cout << "Enter a number : ";
    int ival;
    cin >> ival;
    cout << "treble(" << ival << ")=" 
         << treble(ival) << endl;
    return(0);
}
ex8-1
Enter a number : 7
treble(7)=21

Example program ex8-1 introduces the use of simple functions.  Functions are blocks of statements which are given names and parameters to that they can be called by other blocks.  Functions are a fundamental mechanism for dividing up complex programs into simpler components.  In this trivial example, a function called 'treble()' is declared and called from the main function.  The syntax of a function definition is: 

    function-type 
        function-name
            (parameter-list)
    {
        statement;
        statement;
        ...
    }

Every function needs to be given a type, such as integer, double or string.  This defines the type of any value returned by the function.  If a function doesn't return a value (maybe it just prints something) then it can be declared as type 'void'. Every function has a name which identifies it as different to all other functions. Names are alphanumeric sequences starting with an alphabetic character.  Each function can take parameters: variables which are set when the function is called; these allow the function to perform different calculations at different times.  The parameter list comprises a series of variable declarations separated by commas.  In this example the function 'treble()' takes a single parameter, which is called 'x' and which is an integer.  The block of statements inside the braces {} are the instructions executed when the function is called.  When the function is called, a specific value is copied into the parameter variable x, and this value is then used in the statements of the function.  The 'return()' statement performs two functions: it stops the execution of statements in the function and it specifies which particular value should be returned by the function.  In the example, the function treble() returns 3 times the value of x, which is the name of the function parameter. 

The function is called simply by stating its name and parameters: 

    function-name(expression-list)

Where 'expression-list' is a sequence of variables or expressions separated by commas.  In the example, the function is only called once to provide a value to the cout object. In general the function could be called many times, each time with a different value for the parameter x.

8.2 Functions of one variable with floating point result 

// ex8-2.cpp - functions of one variable 
//             with floating point result
#include <iostream>
using namespace std;
double reciprocal(int x)
{
    if (x==0)
        return(0.0);
    else
        return(1.0/x);
}
int main()
{
    cout << "Enter a number : ";
    int ival;
    cin >> ival;
    cout << "reciprocal(" << ival << ")=" 
         << reciprocal(ival) << endl;
    return(0);
}
ex8-2
Enter a number : 4
reciprocal(4)=0.25

Example ex8-2 demonstrates a different simple function.  This function, 'reciprocal()' takes an integer parameter and returns a double value corresponding to the reciprocal of the parameter. Because the reciprocal of 0 is not defined, the reciprocal function traps that particular problem, choosing here to return 0 in that case. The 'if' statement allows the function to choose between the two cases.

8.3 While loop with function

// ex8-3.cpp - While loop with function
#include <iostream>
using namespace std;
int getvalue()
{
    cout << "Enter a number (0 to end) : ";
    int ival;
    cin >> ival;
    return(ival);
}
int main()
{
    int sum=0;
    int ival;
    while ((ival=getvalue()) != 0)
        sum = sum + ival;
    cout << "Sum=" << sum << endl;
    return(0);
}
ex8-3
Enter a number (0 to end) : 3
Enter a number (0 to end) : 4
Enter a number (0 to end) : 5
Enter a number (0 to end) : 0
Sum=12
>

Example ex8-3 shows how a function can be used to provide a value for use in a conditional expression. Here the function 'getvalue()' takes no parameters but returns an integer value. The function prints a prompt to the screen, reads an integer value and returns it to the calling program. In the main program, a variable also incidentally called ival is used to hold the value returned by getvalue(). The fact that there are two variables called ival is not a problem since they are defined inside different functions. The assignment of the return value to ival is made within the conditional expression to save space: this could have been written:

    ival = getvalue();
    while (ival != 0)
        sum = sum + ival;
        ival = getvalue();
    }

You can see that the form chosen in the example is more concise.

8.4 Exercises

a. Write a program (fwhile.cpp) containing a function to perform Fahrenheit to Centigrade conversion. Use the function to report a table of values from 40 degress Fahrenheit to 100 degrees Fahrenheit in steps of 5 degrees, as in:

    fwhile
    Fahr. Cent
      40   4.4
      45   7.2
      50  10.0
    etc
     100  37.8

b. Write a program (stats.cpp) to accept a sequence of values, keeping a record of: 'num' the number of values, 'sum' the sum of the values, and 'sumsq' the sum of the squared values. Then incorporate two function: one to calculate the mean of the sequence (mean=sum/num), and one to calculate the standard deviation of the sequence (stddev=sqrt((sumsq-sum*sum/num)/num)). The function 'sqrt()' (declared in <math.h>) performs a square root function on double types. Use the functions to report the current mean and current standard deviation as the numbers are entered, as in:

    stats
    Enter value (0 to end) : 2.4
    Mean=2.4 +/- 0
    Enter value (0 to end) : 2.6
    Mean=2.5 +/- 0.1
    Enter value (0 to end) : 2.8
    Mean=2.6 +/- 0.163299
    Enter value (0 to end) : 2.3
    Mean=2.525 +/- 0.192029
    Enter value (0 to end) : 0


© 1999 Mark Huckvale University College London