Wednesday 16 March 2011

Quine: Program that prints itself.

A quine is a program which prints its own code. This means that when the program is run, it must print out precisely those instructions which the programmer wrote as part of the program.

The idea behind the code is simple, taking language C, we will initialize a char array with the code itself as per the code format. This array will be the format for the printf statement, as we know its syntax is;

                                    int printf (const char *format [, argument, ...]);

 The printf statement prints until it encounters a control string which is replaced by the value specified in the argument. printf(quine,10,10,34,quine,34,10,10,10,10,9,10,9,10);

Here the format is the array quine, 10,10,34,quine,34,10,10,10,10,9,10,9,10 are all arguments which are suitably replaced with new line(ASCII 10),double quotes (ASCII 34), the array quine itself and tab (ASCII 9).

Quine can be implemented in any language, the basic technique remains the same. Some may find this easier to do with a file but as far as Quine is considered, no file operations are used.

Sample Code in C:


#include <stdio.h>
char*quine="#include%c%cchar*quine=%c%s%c;%c%cint
main()%c{%c%cprintf(quine,10,10,34,quine,34,10,10,10,10,9,10,9,10);%c%creturn 0;%c}";

int main()
{
printf(quine,10,10,34,quine,34,10,10,10,10,9,10,9,10);
return 0;
}

Output:


No comments:

Post a Comment