Code::Blocks simple guide – simple mathematical operations I


In this discussion, we will look at performing simple mathematical operations using Fortran programming language. We will create a new project for this exercise. You may want to revisit our previous discussion on creating new project in Code::Blocks here.


Before we begin, it is important to highlight the types of variables that we declare at the top section of the code immediately after name of the program. By default, Fortran reserves variable names starting with the alphabet “i” to “n” as integer type, and real type for other remaining alphabets. However, this default setting is negated by the command “implicit none”. It that case, we need to declare the type of each variable that we are going to use. For ease of discussion, we shall limit ourselves here to two types of variables namely integer and real types.


In the code below, you will notice that I introduced two input parameters in which variable names have been arbitrary chosen as “a” and “b”, both having been declared as integers. The section which follows immediately the input parameters are the four different mathematical operations. The first three mathematical operations are easily understood – I think you can easily code these operations as well. The fourth (exponential) might be new to some of you.


Let say we want to ask the code to calculate the square of a value (say 3). We can achieve this by writing:

3**2

Similarly, if we want to calculate 2 to the power of 3/2 we will write

2**(3/2)


Here, I will need to mention about the hierarchy of operation in Fortran.  As in the last example above, the operation inside the parenthesis takes precedence over other operations. That is the code will first execute this operation first before going to the others. In the absence of parenthesis, the hierarchy (from higher to lower priority) would be exponential, multiplication / division and lastly addition / subtraction. Therefore, 2**(3/2) is not the same as 2**3/2 ! You may want to try this on your own to see the outcome of the code.


So here is the code which I have written for this simple exercise.

 


After building the project and compiling the code, you will get the following results on the terminal.


Yeah, we managed to execute the code and we should be happy. But wait for a moment. We need to check if the results are correct. Once you check it properly, you will find that there are, in fact, some mistakes. Can you identify those mistakes and pinpoint the cause of it? Try to identify it on your own and I will discuss about this in my next discussion.