Thinking in Programming

Basic Recipes and Examples

Jose María Alvarez-Rodríguez
Carlos III University of Madrid

josemaria.alvarez@uc3m.es

Contents

  • Programming in a nutshell
    • Algorithms
  • The FORTRAN programming language
    • Compiling and executing
    • Basic source code snippets
    • Datatypes and Variable declarations
    • Flow sentences
    • Arrays
    • User-defined datatypes
    • Functions and procedures
  • What's next and References

How to think in programs?

  • Analyze and understand the problem
  • Design a solution
    • Is there any formal/mathematical model?
  • Code the formal model in the programming language
    • Use the capabilities of the programming language
  • Test and refactor


All the examples can be executed in a Linux machine using the Gfortran compiler.

Recipe 1

  • Name: Install the compiler in Windows
  • Steps
  1. Download the compiler
  2. Install the IDE+compiler
  3. Open the IDE
  4. Check with a simple program
  • Result:

    Recipe 2

  • Name: Compile the first program (Ctrl+F9)
  • Steps
      1. Write a program
      2. Run->Compile (or Ctrl+F9)
      3. Check the results
  • Result:
  • Recipe 3

  • Name: Run the program
  • Steps
      1. Compile the program (Ctrl+F9)
      2. Run the program (F9)
  • Known Problems:
  • The console appears but we cannot see the result
    1. Configure the IDE to (not) minimize after running
    2. Create an executable file and run in console
    3. Create a bat file and run in console
    4. Include a final read sentence
    5.  Program Hello
        Print *, "Hello World!"
        read *,
       End Program Hello

    Recipe 3 (Result)

  • Result:


  • Recipe 4

  • Name: Declare and use variables
  • Steps
      1. Select datatype
      2. Declare variable
      3. Read and print out
  • Result:
  •  Program variables
          integer i1,i2
          read *,i1,i2
          print *,i1,i2
          read *,
     end program variables

    Tip 1

    • Name: Set datatypes FORTRAN
    • Datatypes
      • Intrinsic types
        • Numeric types
          • Boolean
          • Integer
          • Real
          • Comples
        • Non-numeric types
          • Logical
          • Character
          • Pointer
      • User-defined datatypes
        • Registers
        • ...

    Exercise 1

    "Create a program and declare variables of different datatypes"
     Program simpleDatatypes
          integer :: i1 = 0
          real :: r1 = 1.0
          character :: char1 = 'c'
          complex :: c1
          logical :: l1 = .true.
          c1 = CMPLX(2, 4)
          print *,i1, r1, char1, c1, logical
          read *,
     end program simpleDatatypes

    Recipe 4

  • Name: Use of arithmetic expressions
  • Steps
      1. Create an arithmetic expression
      2. Print out result
  • Result:
  •  Program arithmeticOperators
          print *, (5+2)
          print *, (5-2)
          print *, (5*2)
          print *, (5/2)
          print *, (5**2)
          read *,
     end Program arithmeticOperators

    Tip 2

  • Name: Priority of operators and module
  • Priority: * / + -
  • MOD(A,P)  computes the remainder of the division of A by P. 
    • Recipe 5

    • Name: Use of logical expressions and comparison/relational operators
    • Steps
        1. Create logical expressions and combine with operators
        2. Print out result
    • Result:
    •  Program logicalOperators
            print *, (.NOT. .TRUE.)
            print *, (.TRUE. .AND. .TRUE.)
            print *, (.TRUE. .OR. .FALSE.)
            print *, (1 < 2)
            print *, (1 > 2)
            print *, (1 < 2)
            print *, (1 >= 2)
            print *, (1 <= 2)
            read *,
       end Program logicalOperators

      Exercise 2

      "Create a program and combine all type of operator: arithmetic, logical and relational. Assign values to different variables"

      Recipe 6

      • Name: Use of the IF sentence
      • Steps:
        • When a restriction must be checked...include and IF sentence
        • If a number is greater than 5 then print "It is greater than 5"
      • Result:
      Program basicIF
            integer :: top = 5
            integer :: number = 0
            read *, number
            IF (number > top) then
               print *, "It is greater than ", top
            END IF
            read *,
      end Program basicIF

      Recipe 7

      • Name: Use of the IF-ELSE sentence
      • Steps:
        • When a restriction must be checked...include and IF sentence

        • If a number is greater than 5 then print "It is greater than 5" otherwise print "It is less than 5"
      • Result:
            Program basicIFElse
            integer :: top = 5
            integer :: number = 0
            read *, number
            IF (number > top) then
               print *, "It is greater than ", top
            ELSE
              print *, "It is less than ", top
            END IF
            read *,
            end Program basicIFElse

      Tip 3

    • Name: IF-ELSE syntax template 
    • IF (logical-expression-1) THEN
         statements-1
      ELSE IF (logical-expression-2) THEN
         statements-2
      ELSE IF (logical-expression-3) THEN
         statement-3
      ELSE IF (.....) THEN
         ...........
      ELSE
         statements-ELSE
      END IF    
      
      IF (a < b .AND. a < c) THEN
         Result = a
      ELSE IF (b < a .AND. b < c) THEN
         Result = b
      ELSE
         Result = c
      END IF
      

      Select Sentence?

       SELECT CASE (selector)
         CASE (label-list-1)
            statements-1
         CASE (label-list-2)
            statements-2
         CASE (label-list-3)
            statements-3
           .............
         CASE (label-list-n)
            statements-n
         CASE DEFAULT
            statements-DEFAULT
      END SELECT
      INTEGER :: year SELECT CASE (year) CASE (1) WRITE(*,*) 'Freshman' CASE (2) WRITE(*,*) 'Sophomore' CASE (3) WRITE(*,*) 'Junior' CASE (4) WRITE(*,*) 'Senior' CASE DEFAULT WRITE(*,*) "Unknown" END SELECT

      Recipe 8

      • Name: I need to repeat some sentence(s) n times
      • Steps:
        • Use a loop
        • Init all variables that are going to be used in the loop
        • Set the stop condition
        • Select the adequate loop
        • Write a program to show the first 20 natural numbers (descending and using different loops).
      • Result:
      program desc20
        integer :: a
      
        do a = 20, 0, -1
         print*,a
        end do
      
        a = 20
        do while (a >= 0) 
         print*,a
         a = a - 1
        end do
      end program desc20


      Tip 4

      • Name: General Do-loop with exit
      • Template:

       DO
         statements-1
         IF (logical-expression)  EXIT
         statements-2
      END DO
      
      
      DO
         statements-1
         IF (logical-expression) THEN
            statements-THEN
            EXIT
         END IF
         statements-2
      END DO
      Remarks: 

      • The use of the EXIT is not recommended

      Exercise 3

      What happened in the next DO loops?


       INTEGER :: i
      DO
         IF (i <= 3)  EXIT
         WRITE(*,*)  i
         i = i - 1
      END DO
      INTEGER  :: i
      i = 5
      DO
         IF (i < -2)  EXIT
         WRITE(*,*)  i
      END DO
       INTEGER :: i = 1, j = 5
      DO
         IF (j < 0)  EXIT
         WRITE(*,*)  i
         i = i + 1
      END DO

      Tip 5

      • Name: Count DO-loop
      • Template:
       DO control-var = initial-value, final-value, [step-size]
         statements
      END DO
      INTEGER :: Counter, Init, Final, Step READ(*,*) Init, Final, Step DO Counter = Init, Final, Step ..... END DO

      Meaning of the count DO Loop

      • Before the DO-loop starts, the values of initial-valuefinal-value and step-size are computed exactly once
      • step-size cannot be zero.
      • If the value of step-size is positive (i.e., counting up):
        1. The control-var receives the value of initial-value
        2. If the value of control-var is less than or equal to the value of final-value, the statements part is executed. Then, the value of step-size is added to the value of control-var. Go back and compare the values of control-var and final-value.
        3. If the value of control-var is greater than the value of final-value, the DO-loop completes and the statement following END DO is executed.
      • If the value of step-size is negative (i.e., counting down):
        1. The control-var receives the value of initial-value
        2. If the value of control-var is greater than or equal to the value of final-value, the statements part is executed. Then, the value of step-size is added to the value of control-var. Go back and compare the values of control-var and final-value.
        3. If the value of control-var is less than the value of final-value, the DO-loop completes and the statement following END DO is executed.

      Example count DO loop

      INTEGER  :: Count
      
      DO Count = -3, 4, 2
         WRITE(*,*)  Count, Count*Count, Count*Count*Count
      END DO
      INTEGER, PARAMETER :: Init = 3, Final = 5 INTEGER :: Iteration DO Iteration = Init, Final WRITE(*,*) 'Iteration ', Iteration END DO

      INTEGER :: a, b, c INTEGER :: List READ(*,*) a, b, c DO List = MAX(a, b, c), MIN(a, b, c), -2 WRITE(*,*) List END DO

      Recipe 9

      • Name: I want to  add up n numbers
      • Steps:
        • Use a DO loop
        • Configure the loop
        • Add the business logic
      • Result:
      INTEGER :: Count, Number, Sum, Input
      
      Sum = 0
      DO Count = 1, Number
         READ(*,*)  Input
         Sum = Sum + Input
      END DOINTEGER :: Count, Number, Sum, Input
      REAL    :: Average
      
      Sum = 0
      DO Count = 1, Number
         READ(*,*)  Input
         Sum = Sum + Input
      END DO
      Average = REAL(Sum) / Number

      Tip 6

      Name:  
        • The step size cannot be zero
        • It is not a good practice

      INTEGER :: count
      
      DO count = -3, 4, 0
         ...
      END DO


      Tip 7

      Name:  
      • Do not change the value of the control var

       INTEGER :: a, b, c
      
      DO a = b, c, 3
         READ(*,*)  a ! the value of a is changed
         a = b-c      ! the value of a is changed
      END DO

      Tip 8

      Name
        • Do not change the value of any variable involved in initial-value, final-value and step-size.
       INTEGER :: a, b, c, d, e
      
      DO a = b+c, c*d, (b+c)/e
         READ(*,*) b          ! initial-value is changed
         d = 5                ! final-value is changed
         e = -3               ! step-size is changed
      END DO

      Tip 9

      Name

      • When you have a count-down loop, make sure the step-size is negative.
       INTEGER :: i
      
      DO i = 10, -10
         .....
      END DO

      Exercise 4 

      Given a set of integer input values, write a program to count the number of positive and negative values and compute their sums.

      Exercise 5

      Write a program to calculate the exponential function
      See http://en.wikipedia.org/wiki/Exponential_function


      The program reads in an initial value Begin, a final value End and a step size Step, and computes the exponential function value at Begin, Begin+Step, Begin+2*Step, ...

      Exercise 6

      Write a program to determine the number of input data items, excluding the negative one at the end, and compute the minimum and the maximum.

      Exercise 7

      Write a program to calculate the GCD using the Euclid's algorithm.

      • Compute the remainder c of dividing a by b.
      • If the remainder c is zero, b is the greatest common divisor.
      • If c is not zero, replace a with b and b with the remainder c. 
      • Go back to step (1).

      Recipe 10

      • Name: I need to store and process n items of the same datatype
      • Steps:
        • Declare an array for n items
        • Init the values
        • Perform some operation
      • Remark:
        • The value of the integer-expression used as an index or subscript for an array element must be in the range of the extent used to declare the array.
      • Result:
      type, DIMENSION( extent ) :: name-1, name-2, ..., name-nREAL, DIMENSION(-1:1)     :: a, Sum
      INTEGER, DIMENSION(0:100) :: InputData

      INTEGER, PARAMETER :: max = 100 LOGICAL, DIMENSION(1:max ) :: InputData

      Exercise 8

      Declare an array of 100 integers and load even positions with 0 and odd positions with the own value.
      program array
       INTEGER, DIMENSION(1:100) :: x
       DO i = 1, 100
       IF (MOD(i,2) == 0) THEN
         x(i) = 0
       ELSE
         x(i) = i
       ENDIF
      END DO
      end program array

      Exercise 9

      Generate an identity matrix.
        program matrix
             INTEGER, DIMENSION(10, 10) :: x
             DO i = 1, 10
              DO j = 1, 10
                x(i,j) = 0
              END DO
              x(i,i)= 1
             END DO
       end program matrix

      Exercise 10

      Swapping the lower and upper diagonal parts (transpose of a matrix)
         program transpose
             INTEGER, DIMENSION(10, 10) :: x
             INTEGER :: t
              DO i = 1, 10
               DO j = i+1, 10
                t = x(i,j)
                x(i,j) = x(j,i)
                x(j,i) = t
              END DO
             END DO
        end program transpose!Another way...RESULT = TRANSPOSE(MATRIX) 

      Exercise 11

      Multiply 2 matrix. Improve the source code...
      m
      c_i_k = ∑ a_i_k * b_k_i
      k=1
      program multiply INTEGER, DIMENSION(10, 10) :: a INTEGER, DIMENSION(10, 10) :: b INTEGER, DIMENSION(10, 10) :: c  DO i = 1, 10   DO j = 1, 10   c(i,j) = c(i,j) + a(i,j) * b(j,i)  END DO END DO end program multiply 
      MATMUL(A,B)-->FORTRAN FUNCTION

      Recipe 11 

      • Name: I need to repeat some operation n times
      • Steps:
        • Create a function
        • Define the signature
        • Call the function
        • Use FORTRAN syntax (Functions and Subroutines)
      • Result:
       SUBROUTINE  subroutine-name (arg1, arg2, ..., argn)
         IMPLICIT  NONE
         [specification part]
         [execution part]
         [subprogram part]
      END SUBROUTINE  subroutine-name

      Exercise 12

      Write a function to calculate the average of 3 numbers.

      PROGRAM avgFunction REAL A,B,C REAL RESULT READ *, A,B,C RESULT = MyAVG(A,B,C) PRINT *, RESULT READ *, END PROGRAM avgFunction REAL FUNCTION MyAVG(X,Y,Z)  REAL X,Y,Z,SUM SUM = X + Y + Z  MyAVG = SUM / 3 RETURN END 

      What's is still missing...

      • More syntax in FORTRAN
        • Variable declaration...
        • Loops...
        • Array declaration...
        • Functions...
      • Functions and Subroutines
      • Modules
      • Input/Output
      • FORTRAN API
      • Pointers
      • Programming techniques
        • Recursion...
      • ...

      References

      End of this seminar...


      Thinking in Programming

      By Jose María Alvarez

      Thinking in Programming

      This is a brief introduction to programming with the FORTRAN programming language

      • 2,450