Weve seen how to use loops to make the program do the same thing over and over again, but sometimes we want to carry out the same instructions at a later time, not immediately after theyve just been performed. In this task there are several roads to cross but they are unevenly spaced, so we cant use a simple loop to repeat the instructions. What we need to do is group the instructions for crossing a road together and then tell the compiler at what points that group of instructions needs to be carried out.
We do this with something called a function. A function is a group of instructions that we give a name to. Then just by using that name, we can tell the compiler we want that particular group of instructions to be carried out. When we specify the name of the function and its instructions, we are said to be defining the function. When we give the compiler the name of the function we want to be performed, we are said to be calling the function. A function definition looks like this:
void name()
{
First Instruction
Second Instruction
etc.
}
It might look a little familiar all the programs weve written so far have included a function named void main(). Thats because all programs must have at least one function, and one of those functions must be named main. That way, when the program is run the computer knows whereabouts inside the program to start performing the instructions. Only one function can be named main however, or the computer wouldnt be able to decide which function it was supposed to start at.
The curly brackets might look familiar too. Just like with the if statement, the else statement, and the while statement, the curly brackets group instructions together so the compiler knows they all belong to the same thing.
Once weve defined a function, we can call it from any point within our program. A function call looks like this:
Name();
Its just the name of the function we want to call, followed by some brackets, and then a semicolon so that the compiler knows thats the whole statement.
This program has been written for you and uses functions to guide the frog to safety.
Run the program and watch the order in which the instructions are carried out.
Run the program several times until you understand how it works.