Ch1 - Output . Ch2 - Sequence . Ch3 - Variables . Ch4 - Input
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:
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!
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?"); //nogetInt 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.)
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!
message();note the ()
n = message();
function void anyName() // the 'header' { ....instructions - the 'body' of the function }
Run the following:
Note the results.
Explanation
message("Mike");We say that "Mike" is the actual parameter.
function void message(string person)
We say that person is the formal parameter.
message(3); // error - int, not string - wrong type message(); //error - missing parameter n=message("jim"); //error - no result for us to usethen a compilation error will result.
string name=""; message("John"); name=getString("Type your name:"); message(name);i.e a string in quotes, or a variable.
Do this for every program from now on.
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.
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.
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.)
f = c*9/5 +32;call it with values that you know the answer for. (Here is one: 100c is 212f.)
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.
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.
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#.
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.
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