


This immediately poses a problem – what if we want the subroutine to do calculations for us that we can use in the main program? The following program uses arguments to do just that.Įxample: a program that calculates the difference in volume between 2 spheres. This can be useful – we can write a subroutine using any variable names we wish and we know that they will not interfere with anything we have already set up in the main program. Also, the main program knows nothing about the variables used in the subroutine. It is independent of the main program – it knows nothing about the variables used in the main program. The subroutine can be thought of as a separate program which we can call on whenever we wish to do a specific task. We have seen that subroutines are very useful where we need to execute the same bit of code repeatedly.

This makes the program more maintainable. If we ever need to change the code which prompts the user to continue, we will only ever need to change it once.

All the code for prompting is in one place. The program is much easier to understand now. Then executes each line of the code it finds in the subroutine until it reaches the line end subroutine promptĪnd then returns to the main program and carries on where it left off. The program jumps to the line subroutine prompt() Subroutine prompt() !prompts for a keypress implicit none character answer*1 print *, 'type y to continue or any other key to finish' read *, answer if (answer /= 'y') stop end subroutine promptĮxamine the code, each time we use type call prompt() Simple enough – but look at the amount of code! Most of it is the same – wouldn't it be nice to re-use the code and cut down on the typing? The answer is to use subroutines. Notice that the three bolded parts of the code are identical. At three stages in the program (bolded), it asks whether it should continue it stops if the answer is not 'y'. The program sets up some arrays and then outputs them. Print *, 'type y to continue or any other key to finish' read *, answer if (answer /= 'y') stop Understand the use of subroutines and functions to make your code more efficient and easier to read.By the end of this worksheet you will be able to:
