24

I think this might be a classic question but I am not aware of an answer. Can a program output a copy of itself, and, if so, is there a short program that does this?

I do not accept the "empty program" as an answer, and I do not accept programs that have access to there own source code. Rather, I am thinking something like this:

int main(int argc, char** argv){ printf("int main(argc, char** argv){ printf...

but I do not know how to continue...

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
ragnarius
  • 5,642
  • 10
  • 47
  • 68
  • 5
    Ragnarius - You might want to read "Godel, Escher and Bach" By Douglas Hoffstader. His book describes other forms of algorithms and the nature of algorithms that is similar to your interest in quines. I would consider this "Classic" computer science text that has a huge relation to your question. – Shaun Sep 25 '09 at 21:19
  • 2
    Try this search: http://stackoverflow.com/search?q=quine – dmckee --- ex-moderator kitten Sep 25 '09 at 21:34

11 Answers11

38

It's called a quine, and there's a site that collects them.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
18

Yes. A programme that can make a copy of itself is called a "quine".

The basic idea of most quines is:

  1. You write code that takes a string literal s and prints it, while replacing occurrences (or the occurrence) of a special substring foo in s by the value of s itself.

  2. You take the entire source code of the program so far and use it as the definition for s. but you exclude the definition of s from the string, instead replacing it by foo.

That's the general idea. The rest is string formatting details, really.

Richard Hulse
  • 10,383
  • 2
  • 33
  • 37
Joren
  • 14,472
  • 3
  • 50
  • 54
6

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

Gordon
  • 312,688
  • 75
  • 539
  • 559
sdcvvc
  • 25,343
  • 4
  • 66
  • 102
4

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.

Martin B
  • 23,670
  • 6
  • 53
  • 72
3

Yes. Here's a C program that does it that I wrote about 20 years ago.

http://womencht.reocities.com/Athens/8994/repeat.html

elbillaf
  • 1,952
  • 10
  • 37
  • 73
1

If you write a quine, be careful that the copies don't also write copies of themselves ad infinitum and end up taking over the world.

Buggieboy
  • 4,636
  • 4
  • 55
  • 79
1

In the language invented by Jon Skeet the following operator prints "Hello, world!\n".

h

I can make a modification of this language so that the following program prints "Hello, world!\n":

Hello, world!

So that's the program that prints itself.

Oh, you feel something strange about it, while it has a precise and correct mathematical definition? That's your problem. "I won't accept..." ha! Mathematics does accept, and she's the mistress I serve, so I post this answer.

Community
  • 1
  • 1
P Shved
  • 96,026
  • 17
  • 121
  • 165
  • 3
    Yes, and when I think of it I could also imagine a language where the operator h actually outputs h. – ragnarius Sep 25 '09 at 21:19
  • This, like using only `H` for Hello World has already been documented in HQ9+, in which `Q` is a command that prints the source code of the program. Also `9` prints the lyrics of '99 bottles of beer on a wall' and `+` increments the accumulator. Coincidentally I used to have a fully functional HQ9+ interpreter on my graphing calculator. :) – Joren Sep 25 '09 at 21:53
  • You know, the following program is actually a quine in quite a few programming languages: – SamB Apr 11 '10 at 20:25
  • @SamB, true. Perl, Python, Ruby etc. But the OP had something against empty programs, so... :-) – P Shved Apr 11 '10 at 20:31
1

I assume you allow interpreted languages. (At some level, all languages are interpreted.) Somebody writes the interpreter, and if you are writing it, you can add to it any built-in functions you like, such as a (lispy) function (foo) that does nothing except print "(foo)".

Or you can add a more complex macro-type function (printMeAndMyArgs ...).

So the trick is in how you define the problem.

Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135
0
// save it as file.cpp

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    system("cat file.cpp"); 
    return 0;
}
Amit
  • 680
  • 3
  • 10
0

Michael Sipser’s “Introduction to the Theory of Computation” explains in one of the chapters how to construct a quine. I have recently written a Java program based on that idea and posted it at : http://bornagainprogrammer.net/2009/11/07/hello-world-from-the-tm-self/

I'd suggest you get hold of that book and try implementing the program yourself in your favorite language. There are lot of other fun theorems in that book.

-kiran

kiran
  • 1
-1

It is possible in Java, but with some constraints.

I have written a simple code in java which prints itself. You can use literals of C/C++ to use the same program. You can add anything you want inside this program, it will print itself completely.

Conditions

  1. Java file should not be inside any package

  2. Folder structure should not contain any folders with spaces in its name

  3. Compilation target should be default or same folder where java file resides

    import java.io.FileInputStream;
    import java.net.URL;
    
    
    public class PrintYourself {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            URL location = PrintYourself.class.getProtectionDomain().getCodeSource().getLocation();
            String path=location.getFile();
            path=path.replace("/bin", "/src");
            System.out.println(path);
    
            try{
                FileInputStream st=new FileInputStream(path+"PrintYourself.java");
                int i=0;
                while((i=st.read())!=-1){
                    System.out.print((char)i);
                }
                st.close();
            }
            catch(Exception e){
                System.out.println(e);
            }
    
        }
    }
    
Pang
  • 9,564
  • 146
  • 81
  • 122
Arun M S
  • 29
  • 2