Code::Blocks simple guide – Requesting input from user


When running the code, we need to inputs for the calculations.  This will be provided by the user. There are two ways in which input values can be passed on to the code. One is to store the relevant input values in a file and to read those values. The second option is to write a short print statement to request inputs from user over the terminal.  We will look at the latter option here. In any case, both options make use of the read statement.


Lets say we want to store the value provided by the user into a variable named as “mass’. We will first print a statement to request user to provide a value for mass by:

print*, “Provide a value for mass (in unit of kilogram).”

 

In the subsequent line, we will use the read statement such as:

read*, mass


and the value provided by the user will be stored in a variable called “mass”.


In the example of code provided here, I have make use of the read statement to obtain input values for mass and velocity, and use these values to calculate momentum. You may want to practice this to compute any other values. After the momentum has been calculated, the result is then printed on the terminal using a formatted print statement. A short discussion on formatted print (also applicable to write) statement can be found here.


Another example of a Fortran code that makes use of the techniques discussed earlier is included here for calculating the kinetic energy of an object.