Tuesday, February 10, 2015

C Program to print its own Source Code as Output

We can print the source code of a program as an output using quine. So first lets understand what quine is?

What is 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".

Also Read: List of Biggest and Popular Programming Contests
Also Read: How to Swap Two Numbers Without Using Temporary Variable or Arithmetic Operators?

Quines are named after the American mathematician and logician Willard Van Orman Quine (1908–2000). The interesting thing about quine is that we are not allowed to use open and then print file of the program.

An example of a quine in C language is given below which produces the source code as an output. It can be written in any other language like java, python, etc.

main(a){printf(a="main(a){printf(a=%c%s%c,34,a,34);}",34,a,34);}

If you will compile and run above code then it will show following output

C Program to print its own Source Code as Output

This program can result in undefined behavior as we have used printf function without including its header file. Also, the return type declaration for main has been left off to reduce the length of the program. Two 34s are used to print double quotes around the string s.

Source: http://www.geeksforgeeks.org/quine-a-self-reproducing-program/and http://en.wikipedia.org/wiki/Quine_(computing)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.