Using functions to simplify tasks

Functions are a useful means of encapsulating specific tasks in ways that can be easily used from elsewhere in a program. We'll see many examples over the next few weeks. Here we just present simple templates in C/C++ and python, using the "sum" example discussed last time. As written, the function will compute the sum of all integers between m and n inclusive. To invoke it in either language, just say
        s = sum(m, n)
(followed by a semicolon in C/C++).

In C or C++, the function looks like:

int sum(int m, int n)           // function sum takes two integer arguments,
                                // called m and n, and returns an integer
{
    int s = 0;                  // accumulator, local to the function
    int i;                      // counter, local to the function

    for (i = m; i <= n; i++)
        s += i;                 // add i into the running sum

    return s;                   // return value
}

The python syntax is similar:

def sum(m, n):                  # function sum takes two arguments,
                                # called m and n, of unspecified type

    s = 0                       # accumulator, local to the function

    for i in range(m, n+1):
        s += i                  # add i into the running sum

    return s                    # return value

As a general rule, any repeatedly used block of code should be rewritten as a function. It will make your program easier to write, easier to read, and much easier to debug and maintain.