fortranfortran95

How to obtain the smallest figure out of five figures using OO Fortran


In what way can I get the smallest figure in a given five digit figure. E.g 23764. How do I get 2 being the smallest.

Taking the figure as a digit such as 456879, in order to obtain the smallest from the digit which is 4, I implemented the following

program findsmallestFigure
implicit none
integer:: figure
integer:: c,smallest,largest

   smallest = 9
   largest = 0
   figure = 23456

 do while(figure .GT. 0 )  
   c = MOD(figure,10)
   largest = max(c,largest)
   smallest = min(c,smallest)
   figure = figure/10
 end do

  print *,'The smallest digit is',smallest
end

How do I achieve the same result using Object Oriented approach in Fortran ?


Solution

  • Create a module with a user-defined type that contains all the results, and the subroutines to fill in the values

    module numstat
    
        ! Holds the statistics of a figure
        type stat
            integer :: smallest, largest, count
        end type
    
        ! Constructor from a figure. Invoke by 'stat(1234)`
        interface stat
            module procedure :: calc_stat
        end interface
    
        contains
    
        ! Fill statistics type from a figure
        function calc_stat(fig) result(s)
        integer, intent(in) :: fig
        type(stat) :: s
        integer :: digit, f
            ! make a copy of the figure because intent(in) arguments
            ! are immutable (cannot change).
            f = fig 
            s%smallest = 9
            s%largest = 0
            s%count = 0
    
            do while(f > 0 )
                s%count = s%count + 1
                digit = mod(f, 10)
                s%largest = max(s%largest, digit)
                s%smallest = min(s%smallest, digit)
                f = f/10
            end do
    
        end function
    
    end module
    

    Then use the module in the main program

    program SONumstat
    use numstat
    implicit none    
    type(stat) :: s
    integer :: figure
    
    figure = 23456
    
    s = stat(figure)
    
    print *,'The number of digits is ', s%count
    print *,'The smallest digit is ',s%smallest
    print *,'The largest digit is ',s%largest
    
    end program SONumstat