Program that prints itself (quine)

Here is a Fortran version of a quine that I came up with:

program quine
character(1), parameter :: quote = achar(34)
character(*), parameter :: s(*) = [character(len=80) :: &
    "program quine", &
    "character(1), parameter :: quote = achar(34)", &
    "character(*), parameter :: s(*) = [character(len=80) :: &", &
    "    '']", &
    "integer :: i", &
    "do i = 1, 3", &
    "    print '(a)', trim(s(i))", &
    "end do", &
    "do i = 1, size(s)-1", &
    "    print '(5a)', '    ', quote, trim(s(i)), quote, ', &'", &
    "end do", &
    "do i = 4, size(s)-1", &
    "    print '(a)', trim(s(i))", &
    "end do", &
    "end program", &
    '']
integer :: i
do i = 1, 3
    print '(a)', trim(s(i))
end do
do i = 1, size(s)-1
    print '(5a)', '    ', quote, trim(s(i)), quote, ', &'
end do
do i = 4, size(s)-1
    print '(a)', trim(s(i))
end do
end program

Here is how to use it:

$ gfortran quine.f90 && ./a.out > new.f90
$ diff new.f90 quine.f90 
$ 

Is there a way to make it shorter / simpler?

Found a very short version here: Quine - Rosetta Code, except it didn’t work. But with a minor fix it works:

character*60::s='("character*60::s=",3a,";print s,achar(39),s,achar(39);end")';print s,achar(39),s,achar(39);end

That’s probably the shortest.

It is a codegolf problem Quine

and I change the code to Hollerith constant version, LEGACY

character*42::s=42H("character*42::s=42H",a,";print s,s;end");print s,s;end

1 Like

Thanks. The wikipedia article Quine (computing) discusses several ways to take this to extremes.

1 Like

I tried @Euler-37’s program: gfortran compikled and ran it with 2 warnings but ifort gave 2 error messages. The first was

error #6964: This is an illegal octal, hexadecimal, or binary character; or, the value of the constant is too large or too small.   [42H("character*42::s=42H",a,";print s,s;end]
character*42::s=42H("character*42::s=42H",a,";print s,s;end");print s,s;end
----------------^

There may be an ifort option I don’t know about to make the program work.

1 Like