Programming Fundamentals/Conditions/Fortran

conditions.f90 edit

! This program asks the user to select Fahrenheit or Celsius conversion
! and input a given temperature. Then the program converts the given 
! temperature and displays the result.

! References:
!   https://www.tutorialspoint.com/fortran
!   https://en.wikibooks.org/wiki/Fortran

program conditions
    character :: get_choice
    real :: get_temperature, calculate_celsius, calculate_fahrenheit
    character :: choice
    real :: fahrenheit, celsius

    choice = get_choice()
    
    ! if-else approach
    if (choice == "C" .or. choice == "c") then
        temperature = get_temperature("Fahrenheit")
        result = calculate_celsius(temperature)
        call display_result(temperature, "Fahrenheit", result, "Celsius")
    else if (choice == "F" .or. choice == "f") then
        temperature = get_temperature("Celsius")
        result = calculate_fahrenheit(temperature)
        call display_result(temperature, "Celsius", result, "Fahrenheit")
    else
        print ("(a)"), "You must enter C to convert to Celsius or F to convert to Fahrenheit."
    end if
    
    ! select-case approach
    select case (choice)
        case ("C", "c")
            temperature = get_temperature("Fahrenheit")
            result = calculate_celsius(temperature)
            call display_result(temperature, "Fahrenheit", result, "Celsius")
        case ("F", "f")
            temperature = get_temperature("Celsius")
            result = calculate_fahrenheit(temperature)
            call display_result(temperature, "Celsius", result, "Fahrenheit")
        case default
            print *, "You must enter C to convert to Celsius or F to convert to Fahrenheit."
    end select
end program

function get_choice() result (choice)
    character :: choice
    
    print ("(a)"), "Enter C to convert to Celsius or F to convert to Fahrenheit:"
    read *, choice
end function
    
function get_temperature(label) result (temperature)
    character(*) :: label
    real :: temperature

    print ("(a a a)"), "Enter ", label, " temperature:"
    read *, temperature
end function

function calculate_celsius(fahrenheit) result (celsius)
    real :: fahrenheit, celsius

    celsius = (fahrenheit - 32) * 5 / 9
end function

function calculate_fahrenheit(celsius) result (fahrenheit)
    real :: celsius, fahrenheit

    fahrenheit = celsius * 9 / 5 + 32
end function

subroutine display_result(temperature, from_label, result, to_label)
    real :: fahrenheit, celsius
    character(*) :: from_label, to_label
    
    print ("(f5.1 a a a f5.1 a a)"), temperature, "° ", from_label, &
        " is ", result, "° ", to_label
end subroutine

Try It edit

Copy and paste the code above into one of the following free online development environments or use your own Fortran compiler / interpreter / IDE.

See Also edit