Programs that print themselves. A puzzle in self-reference.
A quine is a program that outputs its own source code, without reading itself from disk. It seems impossible at first—how can a program contain a complete copy of itself?
Your first instinct might be:
print("print(...)")But wait—what goes in the ...? You need to print the entire program, including the print statement itself. So you try:
print("print(\"print(...)\")")Now you need another level of nesting. And another. Infinite regress.
Use one piece of data twice.
The data does double duty: it gets printed literally AND used as a template.
Here's the simplest Python quine:
s = 's = %r\nprint(s %% s)'
print(s % s)Let's trace what happens:
s contains the template: 's = %r\nprint(s %% s)'s % s substitutes s into itself using %r (which adds quotes):s = 's = %r\nprint(s %% s)'print(s % s)(f=_=>`(f=${f})()`)()Uses template literals and arrow functions. The function f returns a string containing itself.
s="s=%p;puts s%%s";puts s%sSimilar structure to Python. %p is Ruby's "inspect" formatter.
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}Uses ASCII 34 (double quote) since C can't easily escape quotes in strings.
Program A prints program B. Program B prints program A. A cycle of self-reference.
A single source file that's valid in multiple languages—and outputs itself when run in ANY of them.
Quines that still work even if you delete any single character. Requires redundancy and error correction.
Quines aren't just party tricks. They connect to real things:
Fixed points — A quine is f(x) = x. The program IS its output. No transformation, just identity.
Gödel — Self-referential statements ("this statement is unprovable") use the same structural trick. Encode the system within itself.
Bootstrapping — Compilers that compile themselves. The first version has to come from somewhere.
Replication — DNA, memes, viruses. Patterns that encode their own reproduction.