Ch1 - Output   .   Ch2 - Sequence    .   Ch3 - Variables    .    Ch4 - Input

Ch5 - If decisions    .    Ch6 - While loops   .    Ch7 - Functions

JT Home Page


Chapter 7

Functions

What is a function? It is a section of program which performs a specific task. Most programs are split into into several 'functions', though the benefits of this approach become more apparent in larger programs. Associated with the concept of a function are the concepts of arguments/parameters, local variables, and global variables. So far our programs have consisted of one function, named main.

Here is an extended analogy:


Imagine an organisation. 'main' is the manager, who will call up other workers (functions) to perform subtasks. These workers in turn may call up lower-level workers to do tasks for them, etc. Each worker might need scraps of paper for rough work. Rather than requesting paper from the manager, we assume that they are capable of getting their own. This is the equivalent of local variables, which a function can use and create internally.

Now consider one worker's task - perhaps it is to search a filing cabinet for a document. The search process will be the same, irrespective of the name of the document - but we need to pass the name of the document to the worker. In JT we can pass parameters (data values) into a function for it to make use of.


In other languages, functions are referred to as e.g. procedures, methods, subs, subroutines. Sometimes, parameters are termed arguments. These are all names for similar things.

Functions are used in all programming, and they are one of the hardest concepts you will meet. But there is no way to avoid them!

Built-in functions

Eventually, we will write our own functions. For now, we will look at how we have used the built-in (pre-written) functions, such as print and getInt.

Note the different way we use these:


print("hello");
n = getInt("how big?");

Here are some wrong uses:

n= print("hello");  //no
getInt(How big?");  //no

getInt fetches a number from the user. We must do something with it - such as store it in a variable.

print displays a message - it does not give us a value which we need to deal with. (it is termed a 'void' function.)

Example 1

Here we will code a function that displays a long message. Copy the code and run it.

Note that the message is displayed twice. The key point is the order in which the statements are executed. We can make the program show us the order. We modify the program so that it becomes:

The alerts would not normally be needed - they are there to help us understand. Run the program - you will see 6 alerts, showing you the order of execution - the 'flow' of the program.

We do not show these alerts here - you have to actually run the program!

Explanation

Problems

Write a program which calls a function to display your name and address. Choose a suitable name for the function. Call it twice.

Parameters

Now we will personalise our message function, by prefixing e.g. "hi Jim" or "hi Sue" to the message. We will do this via a parameter. (recall our discussion above of an employee whose task depends on knowing what to search for).

Run the following:

Note the results.

Explanation

A note on code formatting

Soon we will encounter lots of curly brackets. They will be more readable if we shift some of the code to the right of the page , by (e.g.) four spaces. This can be done automatically by clicking the 'Pretty' button, short for 'pretty-print'. It is also useful to place a blank line between functions.

Do this for every program from now on.

Example 2

A program which adds 2 numbers, and prints the result:

Note the indentation.

Firstly, the function declaration. We chose the name add2. There are 2 formal parameters, which we chose to name as a and b.

Note that the type of each formal parameter must be stated, and we use a comma to separate one from another.

In this particular example, the parameters are the same type, but this need not always be the case. The list of parameters can use int, double, or strings.

Now the calls. We have to supply two actual parameters, which must be int. We can use integer numbers, variables, or expressions, as the above example shows.

Problem

Write a function which adds any 3 double items together, and displays the result. Try it out.

Local variables

Look at this program:

Run it. Note the display of the variable names and values, at the top right.

The display shows

main.a
, and
fred.a

Why do you think that the display of names prefixes 'a' with a function name?

The answer: variables can only be used within the function in which they are declared. They are 'local' variables. (This is like saying that U.S. currency can only be used in the U.S.) Now, it might be that each function is written by different people (this is certainly the case for large programs). Coincidentally, they might choose the same name for variables (as i the above example). There is no problem. in the above; main has a variable called 'a', and so does fred.

There are two variables, which do not interfere with each other. When you ran the above, you saw that main's 'a' kept its value of 3, even after fred was called.

Local variables are created when a function is called. They are destoryed (lose their value) when we return from a function.

Incidentally, the same applies to formal parameters - they are treated like local variables.

So - to answer our question - the JT system prefixes each variable with its function, because variable names are not unique - we might have several variables of the same name.

Other languages have 'global' variables as well. They are declared above all the functions , and can be used by any of the functions. They are useful, but need careful use.

return

recall getInt - it passes a value into the program. How can we do this?

Here is an example, showing a function which takes in a number (of inches) and passes back(returns) its cm equivalent. Pretty-print it, then run it:

There are two new things - the absence of void in the header, and the return statement.

When a function needs to pass a value to the caller, we put the type of the value after the word 'function'.

We use 'return' to exit from the function, and to take back a value with it to the caller. Imagine that this value replaces the function name and parameters in the call. Thus the call is:


cm = insToCm(10.0);

We imagine that, after the call, we have:

cm= 25.4;

Because return can pass back the value of an expresssion , we could have written the function like this:

function double insToCm(double inches)
{
return inches * 2.54;
}

Some of you might prefer the more long-winded version - it doesn't really matter (though you should be able to understand either version.)

Problem

Write a function which converts degrees celsius to degrees fahrenheit. It returns a double result, and has one double parameter. The formula is:

f = c*9/5 +32;
call it with values that you know the answer for. (Here is one: 100c is 212f.)

Example 4

Functions can include any code, such as if and while. They can also call other functions themselves. Here is a classic example - a function which returns the bigger of two values:

Note that big returns a result, and we must use it in some way (e.g. print it, or store it somewhere. Here are some correct ways of calling big:


printLine(big(x, y));
x = big(8+x, 66);
x = big(3,4) + big(2,6);   // answer is 10

Now let us do something clever. We will code a function to find the biggest of 3 numbers. Firstly, look at this line:


x= big(big(3,4), 5);

The inner call of big runs first, bringing back 4. imagain that we now have:


x = big(4, 5);

now the outer call runs, returning 5, which goes into x.

Now we will write the big3 function - making use of our existing big function:


function int big3(int a, int b, innt c)
{
    return big(big(a, b), c);
}

we can now use it, as in:

x = big3(22, 5+3, 76);

Add the big3 function to your program, and try it out.

This shows that functions can call functions that can call functions. . In this way, we can break up a large program into manageable parts.

problem.

Write a program which returns the biggest of 4 integers. Make use of big.

Example 5

Now we look at a common function - to validate some input data. If our task is to obtain a positive number from the user, we really need to test that the entered data is in fact positive. If not, we ask for it again.

Of course, the user may type their name instead of a number. JT does not allow this type of checking, but 'real' languages do. In JT, getInt asks you to re-enter a number, but the prompt for this is standard, and cannot be customised.

Here we will code a function that returns with a positive integer (NB - in programming, 0 is usually defined as being positive). AS LONG AS the number entered is negative, we display an error message.

Run the program, and enter negative numbers.

Impossible problem

Write a function which asks a user for their age and height, and returns them to the caller. Name it getAgeAndHeight.

This cannot be done in JT, because return can pass back only one item. In other languages we might use 'pass-by-reference' or global variables (not available in JT) or the passing of an object (not in JT). If you can do all the problems in this chapter, you are definitely ready to move on to e.g Java, C++, C#.

Key Points

Try to sub-divide programs into functions.

Ensure that the number and type of actual parameters in the call match those of the formal parameters in the declaration.

Problems

1. Write a function called 'smaller', which accepts two integers, and which returns the value of the smaller one.

2. Write a function called 'printProd' which has two double inputs and no returned result. It prints the product of the two doubles.

4. Write a function called 'exactly' with two integer arguments, and an integer result. It should return 1 if the two numbers divide exactly, or 0 if they have a remainder. Use the % operator. For example:

 
     x = exactly(3,9);
sets x to 1.


Ch1 - Output   .   Ch2 - Sequence    .   Ch3 - Variables    .    Ch4 - Input

Ch5 - If decisions    .    Ch6 - While loops   .    Ch7 - Functions

JT Home Page