Code::Blocks simple guide – Using subroutines (I)


When writing length program code, we should strive to organize the code in an orderly manner. For one, it will help us as well as other programmers in understanding the structure of the code. It is also useful to locate errors in the code during debugging process.


We can organize our Fortran code by making use of the subroutine subprogram. The structure of subroutine is very similar to the main code. An example of a subroutine is given here. The main difference here is at the first line of the subroutine subprogram. In the main code, we give a name to the program by using the command “program”. For example, to name a main program as “potential”, we write

program potential


In the subroutine we also provide a unique name to each subroutine but by using the command “subroutine”. Let us say we intend to have a subroutine subprogram to generate a harmonic potential well and to name this subroutine as “harmonic_oscillator”. In that case, our first line in the subroutine will be:

subroutine harmonic_oscillator (input1, input2, output1)


We will shortly discuss what are input1, input2 and output1. Let us start with the input variables first. In order to perform calculations in the subroutine, we need to pass some information from the main program to this subroutine. This is achieved precisely by input1 and input2. Returning to the example of harmonic oscillator potential well above, we need to have at least two information to generate a one-dimensional potential well.


One is the coordinate of the center of the well and let’s refer this as “x_0”. The other is the increment step in the x-axis referred here as “delta_x”. Using these two values, we can generate data points that can be used to draw the harmonic oscillator potential well by defining a range in the x-direction.


Next is the output from the subroutine. We need here the value of y at each point in the x-axis. If we have 20 points in the x-direction, we will have the same amount of data for y. Strictly speaking, we need to use arrays to store all these values in one variable but we shall leave this for later discussion. As for now, we will satisfy ourselves by assuming that we have one value in the y-axis. This corresponds to calculating the y-value for one adjacent point in the x-axis with an increment of “delta_x” away from the center of the well given by “x_0”. We shall declare this output variable as “y_1”.


After all this lengthy discussion, the first line in our subroutine will be the following.

subroutine harmonic_oscillator (x_0, delta_x, y_1)


The output value y1 will then be transferred to the main program for subsequent manipulation either to be used for next calculation or simply to be printed in a file or terminal.