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


In the previous note, I have mentioned that the overall structure of a subroutine is similar to the main program. The only difference is at the first line appearing in the subroutine program. In this discussion, we will look at a simple example on how subroutines are used.


Say that we want to calculate kinetic energy and momentum of an object. To do this, we need two input values namely the mass and velocity. We shall ask the user to provide these values by using the print and read command as shown below.


We can then proceed to write the subroutine programs, one for kinetic energy calculation and the other for momentum. For the kinetic energy calculation, we need two input and one output variables. The input variables are mass (variable named mass) and velocity (variable named vel) while the output variable is the kinetic energy (variable named kinetic). The subroutines to calculate kinetic energy and momentum are shown below.
Note to remember: Subroutines are written after the end statement of the main program!


In the main program, we call these subroutines by using the command

call [name of subroutine](variable 1, variable 2, variable 3, …)


In the current example, I used a vivid name for the subroutine namely calc_kinetic and calc_momentum. The command to call the subroutine in the main program are then

call calc_kinetic(mass,vel,kinetic)

call calc_momentum(mass,vel,momentum)


After the subroutines are executed, the results i.e. the output variables will be passed to the main program for further action. In this example, we will just print the results on the terminal using the formatted print statements. The codes can be found in the following file.