Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pure function
ascii
communitycreator

How to use Fortran function reverse(string)

Samra Fakhar

The reverse() function in Fortran reverses the order of all characters in the input string. For example, if the input string is "HELLO", then the output will be "OLLEH".

A few more examples are given below:

  • reverse("Fortran"): nartroF

  • reverse("Educative"): evitacudE

Syntax

The following is the function prototype:

reverse (string)

Class

Its class is a pure function. Pure procedures are free of side effects. They cannot change the global state of the program.

Pure is required to give the Fortran processor flexibility in the ordering of the procedure invocations while still having a reasonably deterministic outcome from a particular stretch of code.

Input argument

The input argument for the reverse() function is a string s which is the string to be reversed.

String is an intrinsic character type. String is an intent (in)receives some input from outside of the function and its value will not be changed within the function argument.

widget

Return value

The return value is an intrinsic character type of the same length as the input string.

Code

program demo_reverse
    use stdlib_ascii, only : reverse
    implicit none
    print'(a)', reverse("Hello, World!") ! returns "!dlroW ,olleH"
    print'(a)', reverse("hello") ! returns "olleh"
    print'(a)', reverse("world") ! returns "dlrow"    
    print'(a)', reverse("Educative") ! returns "evitacudE"
    print'(a)', reverse("Fortran") ! returns "nartroF"
    print'(a)', reverse("edpresso") ! returns "osserpde"
end program demo_reverse

Output

!dlrow, olleH

olleh

dlrow

evitacudE

osserpde

In the example above, we invoke the reverse() function for a series of strings. The output can be compared with the original strings to identify that the original strings have been reversed.

Source code

The code below shows the internal working of the reverse(string) function in Fortran.

    pure function reverse(string) result(reverse_string)
        character(len=*), intent(in) :: string
        character(len=len(string)) :: reverse_string
        integer :: i, n

        n = len(string)
        do i = 1, n
            reverse_string(n-i+1:n-i+1) = string(i:i)
        end do

    end function reverse

Variables

It has the following variables:

widget

Explanation

The code above has a simple working. The length of the string is stored in the variable n. A loop runs from i, initially set to 1, to n. For each iteration of the loop, the character at the ithith index of the input string is placed on the (n1+i)th(n - 1 + i)th index of the reversed string.

RELATED TAGS

pure function
ascii
communitycreator
RELATED COURSES

View all Courses

Keep Exploring