Can a program output a copy of itself
This is indeed a classic question!
Beyond the existence of specific quines, an important result in computability theory is that for any function you might want to compute, there exists a program that "knows its own program text", i.e. that could print itself if desired. This theorem is called Kleene's second recursion theorem.
Yes. A programme that can make a copy of itself is called a "quine".
The basic idea of most quines is:
You write code that takes a string literal
s
and prints it, while replacing occurrences (or the occurrence) of a special substring foo ins
by the value ofs
itself.You take the entire source code of the program so far and use it as the definition for
s
. but you exclude the definition ofs
from the string, instead replacing it by foo.
That's the general idea. The rest is string formatting details, really.
This is called a Quine:
A quine is a computer program which takes no input and produces a copy of its own source code as its only output. The standard terms for these programs in the computability theory and computer science literature are self-replicating programs, self-reproducing programs, and self-copying programs.
A quine is a fixed point of an execution environment, when the execution environment is viewed as a function. Quines are possible in any Turing complete programming language, as a direct consequence of Kleene's recursion theorem. For amusement, programmers sometimes attempt to develop the shortest possible quine in any given programming language.
Source: Wikipedia
It's called a quine, and there's a site that collects them.