Wednesday 25 March 2009

Program to print itself

I came across this interesting program that can print itself. I have modified it from C to C++ and added few comments. Its worth exploring.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Challenge program to self print itself
//Original from http://www.cprogramming.com/challenges/solutions/self_print.html
#include<iostream>
char *program = "#include <iostream>%cchar *program = %c%s%c;%cint main()%c{%c printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c return 0;%c}%c";
int
main()
{

printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);
return
0;
}

//Note the trick
//In ASCII, 10 = LF or new line feed
//In ASCII, 34 = double quotes or "
//%c is printing charachter. 10 for new line and 34 for double quotes
//%s is printing the string




The output is as follows. Note that the aim is for the program to print itself and not the comments. Also the output is wrapped around.

No comments:

Post a Comment