“10 PRINT CHR” in C#

Remco Ros
Remco Ros
May 31, 2016 · 2 min read

So I was watching some random TED videos the other day, when the following book was referenced: 10print.org

This book takes a single line of code, breaks it down and goes into a lot of IT related subjects like computer history, programming, cryptography, random number generators, graphics and art.

This line of code (in Commodore 64 BASIC) prints the following output (an endless maze):

10 PRINT CHR$(205.5+RND(1)); : GOTO 10

Image for post
Image for post

So I wondered if this could be done as elegant with C# and the console.

Doing a quick search on google and github didn’t yield any (elegant) results, so I thought I’d give it a try.

This is what I came up with in c#:

Console.OutputEncoding = Encoding.Unicode;
var r = new Random();
l10: Console.Write((char)(9585 + r.Next(2))); goto l10;

It’s actually 3 lines, the first two lines are necessary initializations for it to work because of the framework. The third line is the actual loop mimicking the BASIC version.

You can run this from ‘csi’ (roslyn command line repl, if you have .net 4.6 sdk installed).
Also, you’ll have to set the font of your console window to ‘Consolas’. Other fonts don’t have the box characters.

Image for post
Image for post

It looks even nicer in full-screen :-).

What this does is print an endless loop of random diagonal line characters, effectively drawing a maze.

This is how it works:

#1 set console output encoding to unicode (required for the special box characters).
#2 initialize a new randomizer
#3 I’ll brake this line down:
“l10:” this is a label (c# feature)
“Console.Write” write to the console
“(char)(9585 + r.Next(2))” this takes 9585 and adds random number between (exclusive) 0 and 2. So you end up with either 9585 or 9586. These two numbers are the decimal representations of the ‘/’ and ‘\’ characters (diagonal lines) in the unicode box character set (2571 / 2572 in hex).
“goto l10” instructs to go to the label “l10”, making this into an endless loop.

How elegant and beautiful, yet so simple is that.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store