share
Stack OverflowWhat is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!
[+406] [87] Tom Ritter
[2009-05-01 11:45:47]
[ language-agnostic ]
[ https://stackoverflow.com/questions/811074/what-is-the-coolest-thing-you-can-do-in-10-lines-of-simple-code-help-me-inspir ]

I'm looking for the coolest thing you can do in a few lines of simple code. I'm sure you can write a Mandelbrot set in Haskell in 15 lines [1] but it's difficult to follow.

My goal is to inspire students that programming is cool.

We know that programming is cool because you can create anything you imagine - it's the ultimate creative outlet. I want to inspire these beginners and get them over as many early-learning humps as I can.

Now, my reasons are selfish. I'm teaching an Intro to Computing course to a group of 60 half-engineering, half business majors; all freshmen. They are the students who came from underprivileged High schools. From my past experience, the group is generally split as follows: a few rock-stars [2], some who try very hard and kind of get it, the few who try very hard and barely get it, and the few who don't care. I want to reach as many of these groups as effectively as I can. Here's an example of how I'd use a computer program to teach:

Here's an example of what I'm looking for: a 1-line VBS script to get your computer to talk to you:

CreateObject("sapi.spvoice").Speak InputBox("Enter your text","Talk it")

I could use this to demonstrate order of operations. I'd show the code, let them play with it, then explain that There's a lot going on in that line, but the computer can make sense of it, because it knows the rules. Then I'd show them something like this:

4(5*5) / 10 + 9(.25 + .75)

And you can see that first I need to do is (5*5). Then I can multiply for 4. And now I've created the Object. Dividing by 10 is the same as calling Speak - I can't Speak before I have an object, and I can't divide before I have 100. Then on the other side I first create an InputBox with some instructions for how to display it. When I hit enter on the input box it evaluates or "returns" whatever I entered. (Hint: 'oooooo' makes a funny sound) So when I say Speak, the right side is what to Speak. And I get that from the InputBox.

So when you do several things on a line, like:

x = 14 + y;

You need to be aware of the order of things. First we add 14 and y. Then we put the result (what it evaluates to, or returns) into x.

That's my goal, to have a bunch of these cool examples to demonstrate and teach the class while they have fun. I tried this example on my roommate and while I may not use this as the first lesson, she liked it and learned something.

Some cool mathematica programs that make beautiful graphs or shapes [3] that are easy to understand would be good ideas and I'm going to look into those. Here are some complicated actionscript examples [4] but that's a bit too advanced and I can't teach flash. What other ideas do you have?

(6) "my goal is to inspire students that programming is cool." I don't think you can tell people programming is cool. Either they like it, or they don't. - Rik
(2) Your one line VBS script doesn't work on my Mac! :-P Good question though. - John Topley
(1) I allways like this kind of stuff, but who you are trying to impress, me the Sierpinski gasket one would do I nice job. For an IT guys may something that creates files, for some people making the computer talk would be impressive, and so on. So what matter is the target audience, then you define whats cool. - Oakcool
(1) @Oakcool: The gasket is impressive, and students are easy to impress. But I taught intro to some 400 students at BC, and I'm doing a little now. The trick is to get THEM to do it, in baby steps, from ground zero up to being able to do something useful. The big lesson I learned is GO... SLOW... - Mike Dunlavey
I think it would be cool if every answerets put an image of the result in their post. I think it would be easier for OP (Tom Ritter) to show it off then to its students. Well , that's my opinion.. :-) - yves Baumes
One interesting thing to try would be to give all your students this test: eis.mdx.ac.uk/research/PhDArea/saeed/test(week-0).doc These guys have found a strong correlation between the results of the test and future programming ability: eis.mdx.ac.uk/research/PhDArea/saeed - parsley72
[+339] [2009-05-08 02:04:23] Espen Herseth Halvorsen

Enter this code in your address bar (in your browser) and press enter. Then you can edit all the content of the webpage!

javascript:document.body.contentEditable='true'; document.designMode='on'; void 0

That is the coolest "one-liner" I know =)


(95) "One-liner" is such a misnomer. That's 3 lines, really. Any code can be one line if you want it to be. - DisgruntledGoat
(5) This looks really neat, but is there a way to get the page once it is modified? - Sylverdrag
@Sylverdrag No, all it does is changes how the page is displayed in teh browser, it doesn't actually change the hTML (I don't think) see stackoverflow.com/questions/1654938/… - Gordon Gustafson
@DisgruntledGoat you could probably make this into a one liner easily enough by replacing those semicolons with other operators. Like && perhaps. But then it'd still be sort of based on 3 separate expressions. - thomasrutter
(1) @Kugel: it works for me in FF. BTW, why'd you put true in quotes? - Ponkadoodle
(1) @Sylverdrag In Firefox select all and then 'View Selection Source' seemed to show the changes. - Phil
@DisgruntledGoat it fits on one standard (StackOverflow) line, so in a most simple and generic way, it is a one-liner. - Mr.Wizard
javascript:document.body.contentEditable = document.designMode = true, void 0 There you go. one line, one statement. - andyortlieb
(4) This is no longer true in Firefox as javascript: has been disabled. A shame. - user18015
(2) @DisgruntledGoat, javascript: and void 0 are boilerplate: the equivalent of int main() { and return 0; } in C. And the other two lines are just different browser APIs that do the same thing: The first is the IE API, the second is the NetScape API. HTML5 uses contentEditable, so unless you care about supporting Firefox 1.5 or something, the actual code amounts to: document.body.contentEditable='true'; - Zarel
1
[+201] [2009-05-01 11:50:14] Robin Day

When I first wrote this.

10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Hello " A$
40 GOTO 30

It blew people away! The computer remembered their name!

EDIT: Just to add to this. If you can convince a new programmer this is the coolest thing they can do, they will become the good programmers. These days, you can do almost anything you want with one line of code to run a library somebody else wrote. I personally get absolutely no satisfaction from doing that and see little benefit in teaching it.


(15) would be better with the following: 40 GOTO 30 - spender
It's an infinite loop that instantly fills the screen. Don't know if that's what you intended. BTW, I used to bring to class a little home-built machine that played a tune on a speaker. It would run 1k times slower than normal & you could hear the speaker click. Then I would unhook a capacitor & the tune would fill the room. - Mike Dunlavey
Mike: it's an infinite loop, but it doesn't fill the screen instantly. It waits for user input each time it reaches line 20. - Joachim Sauer
(2) @saua: You're right, except it says goto 30. Whatever, I think we get the idea. - Mike Dunlavey
(8) +1 for displaying username, people always love seeing their own name displayed. @saua, how is that not an infinite print loop? It goes back to line 30, not line 20. - z -
@yx: People do love seeing their own name. It does get them interested. - Mike Dunlavey
(1) Wow, this is the top answer?! When I was learning, I was bored with this before I'd finished typing. :/ - Peter Boughton
(Just to add, there are some better answers below that help to get people thinking "Hey, I could use this to do ..." - inspiring and useful examples that are going to get people thinking and generate their interest.) - Peter Boughton
(13) Should be goto 10 surely so somone else can enter thier name... - Omar Kooheji
(17) You forgot 35 PRINT CHR$(7) - Adam Jaskiewicz
(6) this is how i learnt programming too. Its the best answer imo. +1 to accept this one - Ali
(1) I did this when I was seven years old, on an old Zilog Z80-powered 16-bit Swedish computer (the ABC80). My friends where in awe too. :) - Macke
(1) only geeks will get amazed with this. - Francis
(1) The intent was to fill the screen. This didn't happen immediately for me, but that's because the computer I wrote this on would have been a Sinclair ZX80, which didn't really do anything instantly! - spender
(1) Shortly after learning this script I learned the value of Ctrl+Break - Mike Robinson
I did this on Commodore64. My first programming experience. ^^ - Arnis Lapsa
Get the the screen full with one's name is cool. +1 for 40 goto 30. - Macke
If you're going to teach them the evil that is GOTO statements don't skimp on the evil. Have them write a BASIC program on their graphing calculators to check their answers for common formulas (quadratic, slopes, y-inverse, etc...). Helped me improve my math test grades overnight. Note: It can be done in just a few lines, believe me, I know. ;) - Evan Plaice
The very first program I ever wrote was a random # guessing game that I built up from something like your example. Keep forgetting how complex software is compared to my beginning 20 years ago. - David
I'm sure this was pretty close to the first program I ever wrote, and I was hooked :) - Kenan Banks
+1 for the "no library" approach. We don't need more fresh blood confusing "easy" with "simple" (see Rich Hickey's Simple Made Easy talk for context). - AshleyF
(1) Ah yes, this was the first program I ever wrote... on a ZX Spectrum+ (Zilog Z80 chip same as @Macke Definitely paved the way for me to get into programming full time, simply because I thought it was really cool. - bluesmoon
2
[+180] [2009-05-01 12:22:34] markus

PHP - the Sierpinski gasket a.k.a the Triforce

OK, it's 15 lines of code but the result is awesome! That's the kind of stuff that made me freak out when I was a child. This is from the PHP manual:

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);
 
$corners[0] = array('x' => 100, 'y' =>  10);
$corners[1] = array('x' =>   0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0); 

for ($i = 0; $i < 100000; $i++) {
  imagesetpixel($gd, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}
 
header('Content-Type: image/png');
imagepng($gd);

sierpinski gasket


You know what, you could probably roll a manderbolt in the same or less. - user50049
(25) For the record, that's a Sierpinski gasket. - chaos
(6) That is awesome, but I think it should come in about the middle of the course, because it builds on a number of concepts, like loops and arrays. - Mike Dunlavey
My TI-86 manual had an example program for doing that in it's own version of basic. I was quite amazed when I first typed it in. - Kibbee
@tharkun: I did the same with Java recently unsuccessfully at java-forums.org/new-java/12357-java-zelda-triangle-problem.h‌​tml . How would you do the same in Java? - Léo Léopold Hertz 준영
@Masi: no clue, I'd have to learn Java first. - markus
(4) @Masi: the general idea is to have three fixed points that are the corners of the triangle, and a "current" point that you keep updating. To make a move, choose one of the corners at random and move the current point half of the way towards that corner. Color in the current point. Then make another move in the same way, and then again a few thousand more times and the pattern will appear. Then try it with a different number of corners, or change the fraction by which the current point jumps toward the corner, to see how it affects the pattern. - Daniel Earwicker
You can easily do a 10 line Sierpinski in PHP. pastebin.com/f69c3105b - Jasper Bekkers
works with more than 3 points too. - EvilTeach
(18) For the record, that is not a Sierpinski gasket... It is, in fact, the Triforce. en.wikipedia.org/wiki/The_Legend_of_Zelda - jason
(2) This code seems weird to me because I normally see this done with recursion (also with very few lines of code). In fact, fractals are a good introduction to recursion in computer science classes. But it looks to me like this code will be quite inefficient, painting & repainting a lot of pixels due to its random approach. - Steve Wortham
(1) I've been implementing the random walk Sierpinski triangle from 68k assembler on the Amiga to in Ruby & Shoes alicebobandmallory.com/articles/2007/11/14/sierpinskis-shoes and recently in JavaScript and HTML5 canvas plea.se/me/leif/canvas_leif.html it's nice and short! - Jonas Elfström
if only you used a better image hosting now we could see the pic - dynamic
@Steve Wortham This algorithm is a very simple example of an Iterated Function System. The same approach can be used to generate fern leafs - jon hanson
3
[+105] [2009-05-01 14:35:14] Bob Fanger

Microsoft has Small Basic [1], an IDE for "kids".

pic = Flickr.GetRandomPicture("beach")
Desktop.SetWallpaper(pic)

It is specifically designed to show how cool programming is.

[1] http://msdn.microsoft.com/en-us/beginner/ff384126.aspx

(2) That looks like an awesome resource. - tomfanning
Woah, that's really cool. I think I'll use this to try to get my niece interested in programming a couple years. - bsneeze
This is excellent because it immediately and constructively shows how a program can be used to create something relevant to an average person's life. It would be simple to extend this example to get a random beach photo from Flicker every 15 minutes and set it as the user's desktop. That's the basic functionality of pay software that cycles desktop images. - Matthew Olenik
(80) This actually sucks, because these library calls seem like magic. You're setting them up to be VB script kiddies. I'm afraid they will never lurk into that "dark magic" area, and stay on the "safe" plumbing area. ... Oh look here's how to make an internet browser in one line! MSIEControl(..blabla whatever...).show() - hasen
(88) I don't think kids are idiots. If you get them excited about the possibilities of programming, they will find out how to do more advanced things on their own. If nothing else, the young testosterone-infected boys would be trying to learn the most arcane, darkmagic things before you even know what happened. - Tim Lin
(28) @hansen j, thats unfair, everybody has to start someplace. - John Farrell
When I was a kid, my parents hired a dude to teach me programming; the stuff we coded in Pascal was so not inspiring that I didn't code at all since before college when private needs pushed me into webprogramming. I think this example is awesome. +1 - zalew
(30) This isn't a CS degree for kids this is a programming toy. Whatever that gateway is to getting kids to see the fun side of programming that's great it doesn't need to be ASM. - Copas
(2) Some of the best programmers I know started out with just "View Source" in internet explorer. And now can do assembly and C++ with the best of them. - Neil N
(2) ::puke:: teaching kids VB is cruel. Unless you want them to be stuck thinking that writing macros in Word makes them 'programmers' or that being a 'DBA' means they can create a DB in 'Access.' If you want to give them a strong base start with Python. If you want them to have fun, make animations in Flash or websites. - Evan Plaice
(29) Knowing the kids that I've tried to teach, it'd be about ten seconds before they try pic = Flickr.GetRandomPicture("boobs") - Iain Galloway
This would be a great sample to show kids, i guess this is a great sample to spark an interest, because they see the impact of the code so quick. - Moulde
4
[+83] [2009-05-01 12:57:38] Martin Peck

I tend to think that people are impressed with stuff that they can relate to or is relevant to their lives. I'd try and base my 10 lines of code around something that they know and understand. Take, for example, Twitter and its API. Why not use this API to build something that's cool. The following 10 lines of code will return the "public timeline" from Twitter and display it in a console application...

using (var xmlr = XmlReader.Create("http://twitter.com/statuses/public_timeline.rss"))
    {
        SyndicationFeed
            .Load(xmlr)
            .GetRss20Formatter()
            .Feed
            .Items        
            .ToList()
            .ForEach( x => Console.WriteLine(x.Title.Text));
    }

My code sample might not be the best for your students. It's written in C# and uses .NET 3.5. So if you're going to teach them PHP, Java, or C++ this won't be useful. However, my point is that by associating your 10 lines of code with something "cool, interesting, and relevant to the students your sample also becomes cool, interesting, and relevant.

Good luck!

[Yes, I know that I've missed out a few lines of using statements and the Main method, but I'm guessing that the 10 lines didn't need to be literally 10 lines]


This is really neat! I wasn't familiar with the SyndicationFeed object - thanks for the code! - Tad Donaghe
Target audience is non-geeks, ergo, they don't give a damn about tweeter? - bobflux
5
[+80] [2009-05-01 15:09:31] user17918

This is a Python telnet server that will ask for the users name and say hello to them. This looks cool because you are communicating with your program from a different computer over the network.

from socket import *
s=socket(AF_INET, SOCK_STREAM)
s.bind(("", 3333))
s.listen(5)
while 1:
   (c, a) = s.accept()
   c.send("What is your name? ")
   name = c.recv(100)
   c.send("Hello "+name)
   c.close()

6
[+78] [2009-05-07 17:55:11] Bob Mc [ACCEPTED]

I got a great response from my kids with a quick VB script to manipulate a Microsoft Agent character. For those that aren't familiar with MS Agent, it's a series of animated onscreen characters that can be manipulated via a COM interface. You can download the code and characters at the Microsoft Agent [1] download page.

The folllowing few lines will make the Merlin character appear on screen, fly around, knock on the screen to get your attention, and say hello.

agentName = "Merlin"
agentPath = "c:\windows\msagent\chars\" & agentName & ".acs"
Set agent = CreateObject("Agent.Control.2")

agent.Connected = TRUE
agent.Characters.Load agentName, agentPath
Set character = agent.Characters.Character(agentName)

character.Show

character.MoveTo 500, 400
character.Play "GetAttention"
character.Speak "Hello, how are you?"
Wscript.Sleep 15000
character.Stop
character.Play "Hide"

There are a great many other commands you can use. Check http://www.microsoft.com/technet/scriptcenter/funzone/agent.mspx for more information.

EDIT 2011-09-02 I recently discovered that Microsoft Agent is not natively installed on Windows 7. However it is offered as a separate download here [2]. I have not tested this so cannot verify whether it operates.

[1] http://www.microsoft.com/downloads/details.aspx?familyid=E11BF712-7862-45BA-826D-44AE3A11836F&displaylang=en
[2] http://www.microsoft.com/products/msagent/main.aspx

That's awesome. This deserves way more upvotes. - Tom Ritter
Thanks for the recognition Tom. Sucks that I'll get no rep points even if it starts to get upvotes though. :-P - Bob Mc
(32) This way you can see the paperclip all the time :D - Pedery
Ouch! Wish you hadn't said that, now I'll get downvoted, lol. :-P - Bob Mc
yuck. teaching beginner programmers VB isn't nice. - Evan Plaice
@Evan - I would agree, but visuals are more persuasive than the console outputing Hello World! - Chris
@Evan & Chris - I code in both C# and VB.Net as the assignment requires, but started with BASIC in college before I moved to C/C++ for many years. Why do you feel that teaching beginners VB is cruel? I have no axe to grind here, just curious. After all, the "B" in "Visual Basic" originally stood for "beginner's". What would you suggest as a language for beginners? Also, there's an interesting VB vs C# debate on StackExchange here: programmers.stackexchange.com/questions/1180/vb-net-vs-c-deb‌​ate. - Bob Mc
(8) @Bob BASIC is a beginners language. VB is not BASIC. VB is the swiss army knife that MS created to fit the need at the time. Nowadays, there are much better (much more specialized) tools to take its place. VB isn't a bad language, it just has a lot of excess baggage. If I were to give one completely unbiased reason why not to use it, it would be because MS is slowly dropping support for VB. It's a dying language. Just wait til Office scripting is done with JavaScript (which is planned in the near future) then the decline of VB will be a sure thing. - Evan Plaice
(3) @Evan - Thanks for the fair answer, rather than some religious screed. Nicely done. Hadn't heard about the Office Javascript move. Will investigate. - Bob Mc
7
[+68] [2009-05-02 04:14:09] Barry Brown

I think it's tough to be a computer educator these days. I am. We face an increasingly steep uphill battle. Our students are incredibly sophisticated users and it takes a lot to impress them. They have so many tools accessible to them that do amazing things.

A simple calculator in 10 lines of code? Why? I've got a TI-86 for that.

A script that applies special effects to an image? That's what Photoshop is for. And Photoshop blows away anything you can do in 10 lines.

How about ripping a CD and converting the file to MP3? Uhh, I already have 50,000 songs I got from BitTorrent. They're already in MP3 format. I play them on my iPhone. Who buys CDs anyway?

To introduce savvy users to programming, you're going to have to find something that's:

a) applicable to something they find interesting and cool, and b) does something they can't already do.

Assume your students already have access to the most expensive software. Many of them do have the full version of Adobe CS5.5 (retail price: $2,600; actual price: free) and can easily get any application that would normally break your department's budget.

But the vast majority of them have no idea how any of this "computer stuff" actually works.

They are an incredibly creative bunch: they like to create things. They just want to be able to do or make something that their friends can't. They want something to brag about.

Here are some things that I've found to resonate with my students:

  • HTML and CSS. From those they learn how MySpace themes work and can customize them.
  • Mashups. They've all seen them, but don't know how to create them. Check out Yahoo! Pipes [1]. There are lots of teachable moments, such as RSS, XML, text filtering, mapping, and visualization. The completed mashup widgets can be embedded in web pages.
  • Artwork. Look at Context-Free Art [2]. Recursion and randomization are key to making beautiful pictures.
  • Storytelling. With an easy-to-use 3D programming environment like Alice [3], it's easy to create high-quality, engaging stories using nothing more than drag-and-drop.

None of these involve any programming in the traditional sense. But they do leverage powerful libraries. I think of them as a different kind of programming.

[1] http://pipes.yahoo.com
[2] http://contextfreeart.org
[3] http://alice.org

(11) +1 I loved how you described kids these days who have 50,000 songs from bittorrent and Adobe CS4 for nothing, it is of course reality - thomasrutter
Write a simple binary search algorithm in python. Tear a phone book in half multiple times to describe how it works. It's the simple-yet-powerful aspects of programming that experienced programmers often overlook and novices look @ in awe. most people don't realize that their monitors refresh at least half of the pixels on their monitor 60-120/sec. do human vs computer speed races. fun stuff. see this for more ideas: academicearth.org/courses/introduction-to-computer-science-i‌​: and, whatever you do... do not teach them ANSI C as their first language. I've been there, it sucked. - Evan Plaice
(3) If you're customizing sites, why not then use Greasemonkey? - new123456
Just a few thoughts on your examples: re photoshop, you just need to point out the obvious -- with photoshop you can change 1 image, with scripting you can change hundreds of thousands. And re MP3s, you're right nobody downloads CDs any more, but you could (if it weren't for the legality) explain that they could write a program to automatically download the latest music straight to their ipod. - Jeff Welling
@JeffWelling well with Photoshop you can make Batches and Actions to do those changes to any number of files as well. It is amazing how much is taken for granted these days with computers though. - John
"Many of them do have the full version of Adobe CS4 (retail price: $2,500; actual price: free) and can easily get any application that would normally break your department's budget." Well said. - Xonatron
8
[+63] [2009-05-01 11:57:37] Mike Dunlavey

I've found a big favorite (in GWBASIC) is:

10 input "What is your name ";N$
20 i = int(rnd * 2)
30 if i = 0 print "Hello ";N$;". You are a <fill in insult number 1>"
40 if i = 1 print "Hello ";N$;". You are a <fill in insult number 2>"

I've found beginning students have a few conceptions that need to be fixed.

  • Computers don't read your mind.
  • Computers only do one thing at a time, even if they do it so fast they seem to do it all at once.
  • Computers are just stupid machines and only do what they are told.
  • Computers only recognize certain things and these are like building blocks.
  • A key concept is that a variable is something that contains a value and its name is different from that value.
  • The distinction between the time at which you edit the program and the time at which it runs.

Good luck with your class. I'm sure you'll do well.

P.S. I'm sure you understand that, along with material and skill, you're also teaching an attitude, and that is just as important.


Modern day computers do a lot more than one thing at a time. - dreamlax
But, does your code do more than one thing at a time? - JeffO
(5) @dreamlax: You're right, of course, but let's not split hairs. We're talking about introducing computers to kids and giving them the basic mental building blocks. Parallelism can come later. - Mike Dunlavey
@John Topley: Thanks for fixing my typo. I know what's "correct" but I don't always type it. - Mike Dunlavey
(1) @Ben S: Did you by any chance remove the space in front of line 10? I had put that in because it seems the SO formatter seems to un-dent the first line by 1 space. I wonder if there's a better way to make the code line up? - Mike Dunlavey
""Computers only do one thing at a time"" --yeah, but have you heard of this multi-core fad? ;-) - Hejazzman
(2) @foljs: Gosh! Really? :-) dreamlax made the same point. The thing is, when you're working with people who know nothing about computers, it looks to them as if everything happens at once, so we gotta get over that, without splitting hairs. So a really basic concept is "First it does A, then it does B, and so on." - Mike Dunlavey
9
[+62] [2009-08-11 20:05:49] ThibThib

This C-code is maybe be obfuscated, but I found it very powerful

#include <unistd.h>
float o=0.075,h=1.5,T,r,O,l,I;int _,L=80,s=3200;main(){for(;s%L||
(h-=o,T= -2),s;4 -(r=O*O)<(l=I*I)|++ _==L&&write(1,(--s%L?_<L?--_
%6:6:7)+"World! \n",1)&&(O=I=l=_=r=0,T+=o /2))O=I*2*O+h,I=l+T-r;}

And here is the result... In only 3 lines... A kind of fractal Hello World...

WWWWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWooooooooooooooooorrrrrrrrrrrrrrrrrrrrroooooooooooooooooooooooooooo
WWWWWWWWWWWoooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooo
WWWWWWWWWWooooooooorrrrrrrrrrrrrrrrrrrrrrrllllld!!ddllllrrrrrrooooooooooooooooo
WWWWWWWWoooooooorrrrrrrrrrrrrrrrrrrrrrllllllldd!oWW!!dllllllrrrrroooooooooooooo
WWWWWWWoooooorrrrrrrrrrrrrrrrrrrrrrlllllllldddd!orro!o!dllllllrrrrrrooooooooooo
WWWWWWooooorrrrrrrrrrrrrrrrrrrrrllllllllldddd!WorddddoW!ddllllllrrrrrrooooooooo
WWWWWoooorrrrrrrrrrrrrrrrrrrrrlllllllllddd!!!o!!!   !dWW!ddddllllrrrrrrrooooooo
WWWWooorrrrrrrrrrrrrrrrrrrrllllllllldd!!!!WWWoo      WloW!!!ddddllrrrrrrrrooooo
WWWWoorrrrrrrrrrrrrrrrrrrlllllllddddWldolrrlo!Wl     r!dlooWWWoW!dllrrrrrrroooo
WWWoorrrrrrrrrrrrrrrrrlllllddddddd!!Wdo  l!               rdo!l!r!dlrrrrrrrrooo
WWoorrrrrrrrrrrrrrrlllddddddddd!!!!oolWW                       lW!ddlrrrrrrrroo
WWorrrrrrrrrrrrllld!!!!!dddd!!!!WWrd !                        rlW!ddllrrrrrrrro
Worrrrrrrllllllddd!oooWWWoloWWWWoodr                           drrWdlllrrrrrrrr
Worrrlllllllldddd!WolWrr!!dWWWlrrldr                            ro!dlllrrrrrrrr
Wrrllllllllddddd!WWolWr        oWoo                              r!dllllrrrrrrr
Wlllllllldddd!!odrrdW            o                              lWddllllrrrrrrr
Wlddddd!!!!!WWordlWrd                                          oW!ddllllrrrrrrr
olddddd!!!!!WWordlWrd                                          oW!ddllllrrrrrrr
Wlllllllldddd!!odrrdW            o                              lWddllllrrrrrrr
Wrrllllllllddddd!WWolWr        oWoo                              r!dllllrrrrrrr
Worrrlllllllldddd!WolWrr!!dWWWlrrldr                            ro!dlllrrrrrrrr
Worrrrrrrllllllddd!oooWWWoloWWWWoodr                           droWdlllrrrrrrrr
WWorrrrrrrrrrrrllld!!!!!dddd!!!!WWrd !                        rlW!ddllrrrrrrrro
WWoorrrrrrrrrrrrrrrlllddddddddd!!!!oolWW                       lW!ddlrrrrrrrroo
WWWoorrrrrrrrrrrrrrrrrlllllddddddd!!Wdo  l!               rdo!l!r!dlrrrrrrrrooo
WWWWoorrrrrrrrrrrrrrrrrrrlllllllddddWldolrrlo!Wl     r!dlooWWWoW!dllrrrrrrroooo
WWWWooorrrrrrrrrrrrrrrrrrrrllllllllldd!!!!WWWoo      WloW!!!ddddllrrrrrrrrooooo
WWWWWoooorrrrrrrrrrrrrrrrrrrrrlllllllllddd!!!o!!!   WdWW!ddddllllrrrrrrrooooooo
WWWWWWooooorrrrrrrrrrrrrrrrrrrrrllllllllldddd!WorddddoW!ddllllllrrrrrrooooooooo
WWWWWWWoooooorrrrrrrrrrrrrrrrrrrrrrlllllllldddd!orro!o!dllllllrrrrrrooooooooooo
WWWWWWWWoooooooorrrrrrrrrrrrrrrrrrrrrrllllllldd!oWW!!dllllllrrrrroooooooooooooo
WWWWWWWWWWooooooooorrrrrrrrrrrrrrrrrrrrrrrllllld!!ddllllrrrrrrooooooooooooooooo
WWWWWWWWWWWoooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooo
WWWWWWWWWWWWWooooooooooooooooorrrrrrrrrrrrrrrrrrrrroooooooooooooooooooooooooooo
WWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWWWWoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
WWWWWWWWWWWWWWWWWWWWWoooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

(5) Nice! Too bad there isn't any spot on there that actually says "Hello World!" - Ponkadoodle
This is pretty! Mandelbrot model :D - Aniket
10
[+44] [2009-05-01 12:26:38] John Topley

How about showing that you can take any web browser and enter JavaScript into the address bar and get code to execute?

EDIT: Go to a page with lots of images and try this in the address bar:

javascript:R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200; DI=document.images; DIL=DI.length; function A(){for(i=0; i<DIL; i++){DIS=DI[ i ].style; DIS.position='absolute'; DIS.left=Math.sin(R*x1+i*x2+x3)*x4+x5; DIS.top=Math.cos(R*y1+i*y2+y3)*y4+y5}R++ }setInterval('A()',5); void(0)

(2) ok, but you should give a concrete example u know .. - hasen
(1) @John: Please, give a concrete example. I have only used JS in my server by exporting the JS file. I have never put the code to my address bar. - Léo Léopold Hertz 준영
(7) Well not a very exciting example, but you could do javascript:alert("Hello World"); - John Topley
I prefer: "javascript: for(var i=0;i>-1;i++)alert('Congratulations, you have pressed enter for '+i+' times!');". (Read that code before running...). ^^ - Arnis Lapsa
+1 for the wow-factor... pretty spectacular example :) - fretje
This is awesome. Looks best on photo galeries like flickr! - ypnos
Whatever that js is supposed to do... ...sometimes it doesn't! I suppose that is a good lesson in and of itself, though. - Kzqai
11
[+37] [2009-05-01 14:59:15] Vinzcent

You could make an application that picks a random number. And you have to guess it. If you are wrong it says: higher or lower. And if you guessed it, a nice message.

It's cool to play for the students.

Simple Python version without proper error checking:

import random

while input('Want to play higher/lower? ').lower().startswith('y'):
    n = random.randint(1, 100)
    g = int(input('Guess: '))

    while g != n:
        print('  %ser!' % (g > n and 'low' or 'high'))
        g = int(input('Guess: '))

    print('  Correct! Congratulations!')

Erik [1] suggests that the computer should guess the number. This can be done within 10 lines of code as well (though now the lack of proper error checking is even more serious: valid numbers outside the range cause an infinite loop):

while input('Want to let the pc play higher/lower? ').lower().startswith('y'):
    n = int(input('Give a number between 1 and 100: '))
    lo, hi, guess, tries = 1, 100, 50, 1

    while guess != n:
        tries += 1
        lo, hi = (guess + 1, hi) if guess < n else (lo, guess - 1)
        guess = (lo + hi) // 2

    print('Computer guessed number in %d tries' % tries)
[1] https://stackoverflow.com/users/16942/erik

(4) More interesting would be to have the user pick the random number, then have the computer guess it. - Erik Forbes
(15) Now make these two programs play each other over a socket. - Josh Lee
(3) It'd be better if the computer wasn't given the number directly. You should tell the user to "pick a number between 1 and 100". Then output "I guess 50", and ask for input ("higher", "lower", or "correct") and refine your guess. - Ponkadoodle
I've done this with my son (9) and it also has the benefit of getting into algorithmic thinking, what is the best strategy for finding the correct number in the shortest number of guesses. - mbesso
I think you want raw_input. Input is equal to eval(raw_input(prompt)). See input. - Jeff Kaufman
12
[+26] [2009-05-01 14:18:24] Ryan Anderson

Back in computer class in high school, myself and a couple of friends taught the class how to program with Delphi. The class was mostly focused on programming with Pascal, so Delphi was a good next step. We demonstrated the event driven nature of Delphi and its RAD capabilities. At the end of the lesson we showed the class a sample application and asked them to reproduce it. The application asked "Are you drunk?" with two buttons Yes and No. ...I think you know what is coming next...the No button changed locations on mouse over and was almost impossible to click.

The students and teacher got a good kick out of it.

The program only required a few lines of user-written code with a simple equation to calculate where to move the button. I don't think any of the other students figured it out, but a few were close.


(7) Not only entertaining, but a coworker of mine once did that in some software, only it was the "OK" button on a message box. It was an internally used app so it wasn't frowned upon. It only did this once in a blue moon. Of course they'd call him and he would say he needed to see it happen if he was going to believe it. So he'd wander over and of course it wouldn't happen when he was there... - Jason D
I recall something like this.. but it was in flash.. and the question was "Are you gay?".. and the button clicking set of a fireworks event. - glasnt
(2) That would be an interesting time to teach people to navigate via tab and space. - davidahines
13
[+23] [2009-05-15 17:26:17] hodgesmr

When I first figured out the bash forkbomb, I thought it was really sweet. So simple, yet neat in what it can do:

:(){ :|:& };:

(7) Here's a pretty good explanation: cyberciti.biz/faq/understanding-bash-fork-bomb - hodgesmr
(12) for new to linux guys:don't run, else you will loose all your work. - Behrooz
@Behrooz, depends on your distro, some have arbitrary thread/fork limits built in. - Razor Storm
It makes a big bang on SuSE, but makes just nothing on most debian based distros. - Behrooz
That, as well as user limits, how often your disk caches are flushed, your filesystem... - new123456
tried it on debian, it froze quickly. - sqram
14
[+22] [2009-05-04 01:23:32] GhassanPL

This is cheating, and not even remotely simple, but I once wrote a shoot'em up in 20 lines of C++, using the Allegro graphics library. No real criteria for what a line was, but it was a bit ago, and it was made purely for fun. It even had crude sound effects.

Here's what it looked like:

20 Lines http://img227.imageshack.us/img227/8770/20linesxx0.png [1]

And here's the code (should compile):

bool inside(int x, int y, int x2, int y2) { return (x>x2&&x<x2+20&&y>y2&&y<y2+10); }
int main() {
  BITMAP* buffer;
  float px,shotx,shoty,monstars[8],first,rnd,pressed,points = 0, maxp = 0;
  unsigned char midi[5] = {0xC0,127,0x90,25,0x54}, plgfx[] = {0,0,0,10,3,10,3,5,6,5,6,10,8,12,10,10,10,5,13,5,13,10,16,10,16,0,13,0,13,2,3,2,3,0,0,0}, mongfx[] = {0,0, 10,5, 20,0, 17,8, 15,6, 10,16, 5,6, 3,8, 0,0};
  allegro_init(), set_color_depth(32), set_gfx_mode(GFX_AUTODETECT_WINDOWED,320,240,0,0), install_timer(), install_keyboard(),  install_mouse(), buffer = create_bitmap(320,240),srand(time(NULL)),install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT,""),clear_to_color(buffer,makecol32(100,100,255));
    while ((pressed=(!key[KEY_Z]&&pressed)?0:pressed)?1:1&&(((shoty=key[KEY_Z]&&shoty<0&&pressed==0?(pressed=1?200:200):first==0?-1:shoty)==200?shotx=px+9:0)==9999?1:1) && 1+(px += key[KEY_LEFT]?-0.1:0 + key[KEY_RIGHT]?0.1:0) && 1+int(px=(px<0?0:(px>228?228:px))) && !key[KEY_ESC]) {
    rectfill(buffer,0,0,244,240,makecol32(0,0,0));
    for(int i=0;i<8;i++) if (inside(shotx,shoty,i*32,monstars[i])) midi_out(midi,5);
        for (int i=0; i<8; monstars[i] += first++>8?(monstars[i]==-100?0:0.02):-100, points = monstars[i]>240?points-1:points, monstars[i]=monstars[i]>240?-100:monstars[i], points = inside(shotx,shoty,i*32,monstars[i])?points+1:points, (monstars[i] = inside(shotx,shoty,i*32,monstars[i])?shoty=-1?-100:-100:monstars[i]), maxp = maxp>points?maxp:points, i++) for (int j=1; j<9; j++) line(buffer,i*32+mongfx[j*2 - 2],monstars[i]+mongfx[j*2-1],i*32+mongfx[j*2],monstars[i]+mongfx[j*2+1],makecol32(255,0,0));
    if (int(first)%2000 == 0 && int(rnd=float(rand()%8))) monstars[int(rnd)] = monstars[int(rnd)]==-100?-20:monstars[int(rnd)]; // randomowe pojawianie potworkow
    if (shoty>0) rectfill(buffer,shotx,shoty-=0.1,shotx+2,shoty+2,makecol32(0,255,255)); // rysowanie strzalu
    for (int i=1; i<18; i++) line(buffer,px+plgfx[i*2 - 2],200-plgfx[i*2-1],px+plgfx[i*2],200-plgfx[i*2+1],makecol32(255,255,0));
    textprintf_ex(buffer,font,250,10,makecol32(255,255,255),makecol32(100,100,255),"$: %i   ",int(points)*10);
    textprintf_ex(buffer,font,250,20,makecol32(255,255,255),makecol32(100,100,255),"$$ %i   ",int(maxp)*10);
    blit(buffer, screen, 0, 0, 0, 0, 320,240);
  }
} END_OF_MAIN()
[1] http://img227.imageshack.us/img227/8770/20linesxx0.png

(5) How is this supposed to teach anyone anything? On an unrelated note, COOL! HA! Loved it! - salezica
15
[+21] [2009-05-01 15:06:05] Jon Winstanley

In this day and age, JavaScript is an excellent way to show how you can program using some really basic tools e.g. notepad.

jQuery effects are great starting point for anyone wanting to wow their friends!

In this one, just click the white space of the page.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document.body).click(function () {
  if ($("#pic").is(":hidden")) {
    $("#pic").slideDown("slow");
  } else {
    $("#pic").slideUp();
  }
});
</script>
</head>
<body><img id="pic" src="http://www.smidgy.com/smidgy/images/2007/07/26/lol_cat_icanhascheezburger.jpg"/>
</body>
</html>

(1) I would agree. You can open notepad and start coding away with java script and then open a browser and I'm sure your students will be impressed. These are tools everyone has and they can look up a lot of different effects and stuff that can be done like Jon's example. - Jeff Reddy
(1) I don't think it's a good idea to teach someone the base of a fairly simple language using a library. You can easily do this without using jQuery, and for a beginner, you should. Libraries are not a replacement to the actual language. - Some Guy
In the case of javascript, jQuery isn't a replacement for javascript, it's a replacement for the (highly variable) doms. Which is a great thing to be able to sidestep, for anyone. - Kzqai
16
[+20] [2009-05-01 11:55:25] Welbog

One thing you might consider is something like Robocode [1], in which a lot of coding is abstracted away and you basically just tell a robot what to do. A simple 10-line function can make the robot do a great deal, and has a very visual and easy-to-follow result.

Perhaps Robocode itself isn't suited to the task, but this kind of thing is a good way to relate written code to visual actions on the computer, plus it's fun to watch for when you need to give examples.

public class MyFirstJuniorRobot extends JuniorRobot {
 public void run() {
  setColors(green, black, blue);
  // Seesaw forever
  while (true) {
   ahead(100); // Move ahead 100
   turnGunRight(360); // Spin gun around
   back(100); // Move back 100
   turnGunRight(360); // Spin gun around
  }
 }
 public void onScannedRobot() {
  turnGunTo(scannedAngle);
  fire(1);
 }
 public void onHitByBullet() {
  turnAheadLeft(100, 90 - hitByBulletBearing);
 }
}
[1] http://robocode.sourceforge.net/

(6) Don't know about robocode, but I got into coding after using Logo. Being able to draw a house using forward, backward, left, right, etc. It gets you into the mindset of simple instructions performing huge tasks. - Robin Day
(1) Yeah I learned Logo in computer lab in elementary school. I was one of the kids who, beyond thinking it was cool, wanted to know more. - Travis
(1) +1 For RoboCode! I love robocode, and we used to do competitions between ourselves to see who would come up with the best algorithms - Andreas Grech
17
[+18] [2009-05-11 06:07:25] Wesley

So one day, I decided that I'd had enough. I would learn piano. Seeing people like Elton John command such mastery of the keyboard assured me that this was what I wanted to do.

Actually learning piano was a huge letdown. Even after completing eight grades of piano lessons, I was still not impressed with how my mental image of playing piano was so different from my original vision of enjoying the activity.

However, what I thoroughly enjoyed was my mere three grades of rudiments of music theory. I learned about the construction of music. I was finally able to step from the world of performing written music to writing my own music. Subsequently, I was able to start playing what I wanted to play.


Don't try to dazzle new programmers, especially young programmers. The whole notion of "less than ten lines of simple code" seems to elicit a mood of "Show me something clever".

You can show a new programmer something clever. You can then teach that same programmer how to replicate this "performance". But this is not what gets them hooked on programming. Teach them the rudiments, and let them synthesize their own clever ten lines of code.

I would show a new programmer the following Python code:

input = open("input.txt", "r")
output = open("output.txt", "w")

for line in input:
    edited_line = line
    edited_line = edited_line.replace("EDTA", "ethylenediaminetetraacetic acid")
    edited_line = edited_line.replace("ATP", "adenosine triphosphate")
    output.write(edited_line)

I realize that I don't need to assign line to edited_line. However, that's just to keep things clear, and to show that I'm not editing the original document.

In less than ten lines, I've verbosified a document. Of course, also be sure to show the new programmer all the string methods [1] that are available. More importantly, I've showed three fundamentally interesting things I can do: variable assignment, a loop, file IO, and use of the standard library.

I think you'll agree that this code doesn't dazzle. In fact, it's a little boring. No - actually, it's very boring. But show that code to a new programmer and see if that programmer can't repurpose every part of that script to something much more interesting within the week, if not the day. Sure, it'll be distasteful to you (maybe using this script to make a simple HTML parser), but everything else just takes time and experience.

[1] http://docs.python.org/library/stdtypes.html#string-methods

18
[+17] [2009-05-01 20:50:05] Jeffrey Berthiaume

Like most of the other commenters, I started out writing code to solve math problems (or to create graphics for really terrible games that I would design -- things like Indiana Jones versus Zombies).

What really started me (on both math and programming) was going from text based, choose your own adventure style games...to more graphics-based games. I started out coloring graph paper and plotting pixels, until I got into geometry...and discovered how to use equations to plot curves and lines, boxes, etc.

My point is, I could have really gotten into something like processing ( http://processing.org/ ) where a typical program looks something like this:

void setup() 
{
  size(200, 200); 
  noStroke();
  rectMode(CENTER);
}

void draw() 
{   
  background(51); 
  fill(255, 204);
  rect(mouseX, height/2, mouseY/2+10, mouseY/2+10);
  fill(255, 204);
  int inverseX = width-mouseX;
  int inverseY = height-mouseY;
  rect(inverseX, height/2, (inverseY/2)+10, (inverseY/2)+10);
}

To me, this is the "Logo" of the future.

There are easy "hello world" examples that can quickly get someone drawing and changing code and seeing how things break and what weird "accidents" can be created...all the way to more advanced interaction and fractal creation...


+1 I think processing is a great way to teach algorithmic thinking which is the most important topic beginners need to learn. - Nils
19
[+15] [2009-05-01 16:01:38] meepmeep

You could use a script written with AutoIt [1], which blurs the line between using a traditional application and programming.

E.g. a script which opens notepad and makes their own computer insult them in it and via a message box, and then leaves no trace of its actions:

Run("notepad.exe")
WinWaitActive("Untitled - Notepad")
Send("You smell of human.")
Sleep(10000)
MsgBox(0, "Humans smell bad", "Yuck!")
WinClose("Untitled - Notepad")
WinWaitActive("Notepad", "Do you want to save")
Send("!n")
[1] http://www.autoitscript.com/autoit3/index.shtml

++ I'm not sure where it would fit in a lesson plan, but it is cute. - Mike Dunlavey
20
[+13] [2009-05-01 19:27:37] Josh Curren

I remember when I first started coding loops always impressed me. You write 5 - 10 lines of code (or less) and hundreds (or however many you specify) lines print out. (I learned first in PHP and Java).

for( int i = 0; i < 200; i++ )
{
   System.out.println( i );
}

21
[+13] [2009-05-02 08:06:40] joeytwiddle

I think a good place for a student to get started could be Greasemonkey [1]. There are thousands of example scripts on userscripts.org, very good reading material, some of which are very small. Greasemonkey scripts affect web-pages, which the students will already be familiar with using, if not manipulating. Greasemonkey itself offers a very easy way to edit and enable/disable scripts while testing.

As an example, here is the "Google Two Columns" script:

result2 = '<table width="100%" align="center" cellpadding="10" style="font-size:12px">';
gEntry = document.evaluate("//li[@class='g'] | //div[@class='g'] | //li[@class='g w0'] | //li[@class='g s w0']",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < gEntry.snapshotLength; i++) {
  if (i==0) { var sDiv = gEntry.snapshotItem(i).parentNode.parentNode; }
  if(i%2 == 0) { result2 += '<tr><td width="50%" valign="top">'+gEntry.snapshotItem(i).innerHTML+'</td>'; }
  if(i%2 == 1) { result2 += '<td width="50%" valign="top">'+gEntry.snapshotItem(i).innerHTML+'</td></tr>'; }
}
sDiv.innerHTML = result2+'</table>';

if (document.getElementById('mbEnd') !== null) { document.getElementById('mbEnd').style.display = 'none'; }
[1] http://en.wikipedia.org/wiki/Greasemonkey

22
[+10] [2009-05-01 20:41:40] Greg

This is a very rudimentary text-based c# program that simulates the spinning action of a slot machine. It doesn't include different odds of winning or cash payouts, but that could be a nice exercise for the students.

Sorry that it is more than 10 lines.

string[] symbols = new[] { "#", "?", "~" }; // The symbols on the reel
Random rand = new Random();

do
{
    string a="",b="",c="";

    for( int i = 0; i < 20; i++ )
    {
        Thread.Sleep( 50 + 25 * i ); // slow down more the longer the loop runs

        if( i < 10 )
            a = symbols[rand.Next( 0, symbols.Length )];

        if( i < 15 )
            b = symbols[rand.Next( 0, symbols.Length )];

        c = symbols[rand.Next( 0, symbols.Length )];

        Console.Clear();
        Console.WriteLine( "Spin: " + a + b + c );
    }

    if( a == b && b == c )
        Console.WriteLine( "You win. Press enter to play again or type \"exit\" to exit" );
    else
        Console.WriteLine( "You lose. Press enter to play again or type \"exit\" to exit" );
}
while( Console.ReadLine() != "exit" );

23
[+9] [2009-05-01 11:55:30] stevehipwell

How about a bookmarklet? It would show them how to manipulate something that they use every day (the Internet) without requiring any development tools.


I'd like this suggestion, but it'd would be better with an example and what can be taught from it. Such as the example given in the question: [code] javascript:alert(4(5*5) / 10 + 9(.25 + .75)); [/code] to show the order of operation. - tylermac
24
[+9] [2009-05-01 12:36:16] Bryan Oakley

With Tcl [1] you have a simple text editor with a save button in about 12 lines of code (but no open, that would take another 8 lines). It works across all standard platforms:

pack [frame .toolbar] -side top -fill x
pack [button .save -text save -command save] -in .toolbar -side left
pack [scrollbar .vsb -orient vertical -command [list .text yview]] -side right -fill y
pack [text .text -wrap word -yscrollcommand [list .vsb set]] -side left -fill both -expand true
proc save {} {
    set filename [tk_getSaveFile]
    if {$filename ne ""} {
        set f [open $filename w]
        puts $f [.text get 1.0 end-1c]
        close $f
    }
}

I realize the goal was 10 lines, so if you want the to stick to 10 lines or less, a simple text editor without load or save is only two lines. That's not too shabby.

pack [scrollbar .vsb -orient vertical -command [list .text yview]] -side left -fill y
pack [text .text -wrap word -yscrollcommand [list .vsb set]] -side left -fill both -expand true

Execute either of the above blocks of code with "wish filename" on the platform of your choice. Wish comes with most *nix's and the mac but you'll have to install it manually for windows.

To go a step further, that two line script can also be written in python, though it takes eight lines, still under the 10 line goal:

from Tkinter import *
root=Tk()
text = Text(wrap="word")
sb = Scrollbar(orient="vertical", command=text.yview)
text.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)
root.mainloop()
[1] http://en.wikipedia.org/wiki/Tcl

25
[+8] [2009-05-01 12:21:48] Andrew Sledge

If you can afford the hardware, using an Arduino board + processing will produce some pretty cool things, though it may be a little advanced for people that may not be interested at all in programming.


26
[+8] [2009-05-15 17:44:29] JohnFx

I wrote about this recently in an article "The Shortest, most useful program I have ever written." [1]

Summary: I wrote a 3 line VB6 app back in 1996 that I still use every single day. Once the exe is dropped in the "Send-to" folder. It lets you right click on a file in explorer and send the full path of that file to the clipboard.

Public Sub Main()   
    Clipboard.SetText Command$   
End Sub  
[1] http://softwareplusplus.wordpress.com/2009/05/04/the-shortest-most-useful-program-that-i-have-ever-written/

Why the Clipboard.Clear? It removes all content from the clipboard, even non-text data (e.g. image data). This is generally not what you want at all. - Konrad Rudolph
Well, then maybe the shortest program needs to be half its current size... - JohnFx
Really neat. I hate having to type long paths and then wonder if there is a typo - Sylverdrag
AFAIK in "modern" windows versions that is exactly what it does when you copy the file (Ctrl + C)... Just copying the filename. Can someone try this (as I have no windows)? - opatut
I have Windows 7 and it does NOT do that. - JohnFx
Well.. No, Ctrl + C doesn't. But Shift + Rightclick offers 'copy as path' (at least in Windows 7, not sure if that was added in Vista already). Which seems to do the same thing, no? - Benjamin Podszun
27
[+7] [2009-05-01 16:43:26] Robert S.

It's interesting that you mention the Mandelbrot set, as creating fractals with GW-BASIC is what sparked my love of programming back in high school (around 1993). Before we started learning about fractals, we wrote boring standard deviation applications and I still planned to go into journalism.

But once I saw that long, difficult-to-write BASIC program generate "fractal terrain," I was hooked and I never looked back. It changed the way I thought about math, science, computers, and the way I learn.

I hope you find the program that has the same affect on your students.


That's great for a semester project. I wish I had thought of that back when I was teaching. - Mike Dunlavey
28
[+7] [2009-06-15 23:09:46] sqram

wxPython First Steps [1]

import wx
app = wx.App()
wx.Frame(None, -1, 'simple.py').Show()
app.MainLoop()

simple.py frame http://zetcode.com/wxpython/images/simple.jpg [2]

[1] http://zetcode.com/wxpython/firststeps/
[2] http://zetcode.com/wxpython/images/simple.jpg

29
[+6] [2009-05-01 12:14:13] MunkiPhD

As a supplement to whatever ideas you come up with, I say you should just show them how to do some basic math. Present it as

"now you might think this is easy or complicated... but have you ever been stuck on your math homework?"

Then just pull out an example from someone's book. Most math problems can be solved in 10 lines as it will likely be a simple problem. Then show them how spending 10 minutes to figure it out might be worth the A they might get. It's a long stretch, but you might catch a few who want to spend little to no time doing homework.

This mostly stems from me having wished I had thought of writing a software program back in chemistry... all those quizzes and homeworks would have been 100s...

Edit: To respond to Peter's comment:

Say something like what is the derivative of 3a2. So you could just show a simple function that they can call from the command line:

public int SimpleDerivative(int r, int exponent){
    r = r * exponent
    exponent =- 1
    return (String "{0}a^{1}" where {0} = r, {1} = exponent)
}

Maybe this could benefit from a quick example? Definitely good to have a "here's how programming can be useful to use" perspective. - Peter Boughton
Gah, can't edit/delete above comment - should be "...useful to you" - Peter Boughton
(1) Very true. I added a simple example in the edit. Granted it's very low level, but it really depends on what level the students are and what classes they are taking. To do something in 10 lines of code, it might need to be something that's actually rather lengthy underneath the hood. For example, having a button turn a light bulb on or off. It'd have that "oh wow" factor -- but in reality there's quite a bit of groundwork behind it -- but it might be that spark to get certain students very interested especially knowing that they too can accomplish these technological 'feats' if you will. - MunkiPhD
I'm sure a lot of you were like me. I used to do a lot of my math homework by creating a simple form in VB6 (that performed a mathematical function) and then inputting the differing values from the worksheet. - Travis
@T Pops: ditto, but with QBasic! Creating physics simulators for projectile motion, collision dynamics, etc really helped me understand the problems much better! - nickf
Shouldn't it be exponent -= 1, and not =-? - Petrus Theron
30
[+6] [2009-05-01 12:19:47] ChrisF

I'm sure it'd turn into more than 10 lines of code, but have you considered a form based app where pressing the buttons does things like changing the colour of the background or changes the size of the text? This would show them how interactive programs work. It would also show them that they, as programmer, are in complete control of what the computer (program) does.

Hopefully it would lead them to make suggestions for other things they could change and then onto other things they might want to do.


31
[+5] [2009-05-18 22:03:38] Neil G

Many people find gambling exciting and motivating. You could build a blackjack dealer class yourself, exposing an interface. Then, have the kids build a blackjack player class.

You can build a graph for each student's solution showing money versus time to motivate the task.

The beauty of this system is that you can produce incremental solutions over weeks:

The naive solution is to always hit below a certain level. That's maybe 5 lines of code.

A better solution is to look at what the dealer has exposed and adjust your hitting for that.

An even better solution takes into account the actual cards you have-- not just the sum of their values.

The ultimate solution is probably keeping track of the dealt cards over many hands. (The dealer object could make a DealerIsShuffling(int numberofdecks) call on the player object telling the player how many decks there are.)

Another direction this could go is to make the game competitive-- instead of winning money against a dealer, you play against other people's solutions. Of course, you have to rotate who starts hitting first to make things fair.


32
[+5] [2011-11-25 13:59:15] ibrahim

This bash code lock down your computer. It's called Fork bomb.

:(){ :|:& };:

WARNING: don't run it!

more info: http://en.wikipedia.org/wiki/Fork_bomb


33
[+4] [2009-05-01 12:41:34] JeffO

I taught a class for students with learning disabilities, ages 11-12. We were using Hypercard and they discovered they could record the position of an object (image, box, etc.) as they moved it and play it back (animation). Although this is not coding, they wanted to do more like: delete one of the moves without recording it all over again. I told them they would have to go to the code and change it.

You could see who had a knack for computers/programming when they prefered to do it with code because they had more control.

Doing a complex macro in Excel and then learning what the code is doing could be a gateway to VBA.

Depending on the age group or level of interest, it could be tough to jump straight into code, but it is the end that counts.


Thats really cool man. And the fact that they were taking their own initiative makes it even more rewarding. - Egg
I remember discovering how to record macros in PowerPoint. I learned how to code them and from then on through the year, every PowerPoint I made had at least 1 particle effect in it :D Sadly, I think Microsoft removed this feature in the newest version of PowerPoint. - Ponkadoodle
34
[+3] [2009-05-01 12:24:10] user50049

I don't have code for this, however it could be abstracted in 10 lines or less. Make the mouse draw a box .. however you move it. when you click (left) the box vanishes, when you click (right) the box changes color.

Students want something practical, something they can hack and customize, something that says this "is not your typical boring class".

Xen's mini-os kernel does this now, but it would require additional abstraction to fit your needs.

You could also try plotting a manderbolt (julia) set while getting the paramaters of the quadratic plane from ambient noise (if the machines have a microphone and sound card) .. their voice generates a fractal. Again, its going to be tricky to do this in 10 lines (in the actual function they edit), but not impossible.

In the real world, you are going to use existing libraries. So I think, 10 lines in main() (or whatever language you use) is more practical. We make what exists work for us, while writing what does not exist or does not work for us. You may as well introduce that concept at the beginning.

Also, lines? int main(void) { unsigned int i; for (i=0; i < 10; i++); return 0; } Perhaps, 10 function calls would be a more realistic goal? This is not an obfuscated code contest.

Good luck!


35
[+3] [2009-05-07 07:20:45] Paul Harrison
import sys
for y in range(80):
    for x in range(80):
        c = complex(x-40.0,y-40.0) / 20.0
        z = 0.0
        for i in range(100):
            z = z*z+c
        sys.stdout.write('#' if abs(z) < 2.0 else ' ')
    sys.stdout.write('\n')

36
[+3] [2009-07-02 03:51:22] segfault

C program to compute the value of pi:

#include <stdlib.h>  
#include <stdio.h>  

long a=10000,b,c=2800,d,e,f[2801],g;  

int main()  
{  
    for(;b-c;)  
        f[b++]=a/5;  
    for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)  
        for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);  
}  

Output:

31415926535897932384626433832795028841971693993751058209749445923078164062862089
98628034825342117067982148086513282306647093844609550582231725359408128481117450
28410270193852110555964462294895493038196442881097566593344612847564823378678316
52712019091456485669234603486104543266482133936072602491412737245870066063155881
74881520920962829254091715364367892590360011330530548820466521384146951941511609
43305727036575959195309218611738193261179310511854807446237996274956735188575272
48912279381830119491298336733624406566430860213949463952247371907021798609437027
70539217176293176752384674818467669405132000568127145263560827785771342757789609
17363717872146844090122495343014654958537105079227968925892354201995611212902196
0864034418159813629774771309960518707211349999998372978049951059731732816096318

Forgive me if I'm wrong, but wouldn't the loop conditions always return true? - Javier
It is not infinite loop. I've run it and got the above result. - jfs
37
[+3] [2011-01-25 22:19:40] Anynomous Coward
Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub JohnDenverAnniesSong(): Const E4# = 329.6276: Dim Note&, Frequencies$, Durations$: Frequencies = "iiihfihfffhidadddfhihfffhihiiihfihffihfdadddfhihffhiki": Durations = "aabbbfjaabbbbnaabbbfjaabcapaabbbfjaabbbbnaabbbfjaabcap": For Note = 1 To Len(Frequencies): Beep CLng(E4 * 2 ^ ((AscW(Mid$(Frequencies, Note, 1)) - 96) / 12)), CLng((Asc(Mid$(Durations, Note, 1)) - 96) * 200 - 10): Sleep 10: DoEvents: Next: End Sub

Dump in Excel to run:D


38
[+2] [2009-05-02 02:28:07] torial

Maybe this is dumb, but I think kids would intuitively grasp it -- the cartoon that started off the whole "What’s your favorite “programmer” cartoon?" at What's your favorite "programmer" cartoon? [1].

E.g. Jason Fox of Foxtrot writes code on the board that does a loop.

Possible point of interest: programming might help you out of trouble some time...

[1] https://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon

39
[+2] [2009-05-02 10:37:15] yetanotherdave

It has been fun reading the answers to this question. Once you've achieved the 'wow' factor from the students, illustrate the daisy-chaining affect of the results of one becoming the input of another. Learning how input and output works will illustrate the idea of building blocks and how software grows from lots of little things solving specific problems to larger applications solving bigger problems. If a few 10 line programs can be cool, how cool would it be to then put a bunch of them together? That is non-linear cool.


40
[+2] [2009-05-02 16:22:59] benlenarts

Take a look at these projects:

  • Hackety Hack [1]: specifically aimed at making coding accessible and attractive for non-programmers.
  • Shoes [2]: fun and minimalistic approach to desktop applications
  • Processing [3]: environment and (java-like) language for programming images, animation and more.
[1] http://hacketyhack.net/
[2] http://shoooes.net/
[3] http://processing.org/

41
[+2] [2009-05-05 13:27:05] OEP

Processing is always fun to play with and it creates things that are impressive to all types of people. For instance, a Brownian tree:

int xf = (int) random(width);
int yf = (int) random(height);
int x = (int) random(width);
int y = (int) random(height);

background(0xFF);
while(x != xf || y != yf) {
  set(x,y,color(0,0,0));
  x = max(0, min(x + -1 + (int) random(3), width - 1) );
  y = max(0, min(y + -1 + (int) random(3), height - 1) );
}

42
[+2] [2009-11-27 18:52:03] Stephane Grenier
10 PRINT "HELLO"
20 GOTO 10

But I was just a kid then. That's also why it was the coolest thing. I don't think you can ever get that same rush from the very first time you programmed a computer. Even if it's as simple as printing "HELLO" to the console infinitely.


43
[+1] [2009-05-01 11:55:40] JPrescottSanders

You could have your students go to the codeplex IronPython silverlight sample site which includes a < 10 line demonstration of altering a canvas and interacting with the mouse. You can find the silverlight example here [1]

Just seeing code written in a web browser and then executing an altering a small WPF might be intoxicating for some.

[1] http://ironpython.codeplex.com/Wiki/View.aspx?title=SilverlightInteractiveSession

44
[+1] [2009-05-01 12:20:28] David Wolever

I was blown away by some of the stuff that was shown in the talk Easy AI with Python [1] (video and PDF). For example, teaching a computer how to play Mastermind, solve eight queens, alphametics (those puzzles which are like "9567 + 1085 == 10652" and infer relationships in data. All in the order of 10 lines (possibly with 20 or 30 lines of "behind the scenes" code).

[1] http://us.pycon.org/2009/conference/schedule/event/71/

45
[+1] [2009-05-11 07:24:29] eric espie

Fibonacci numbers is a cool example to learn recursivity. It shows that recursivity can be simple to write and can be costly to execute. The negative entries case can be introduced later.

int fiboNumber(int index)
{
  if (index <= 1)
  {
    return index;
  }
  return fiboNumber(index - 1) + fiboNumber(index - 2);
}

46
[+1] [2009-05-11 13:29:54] nickf
  • Choose any language (or framework) where drawing a dot, line, box or circle to the screen is trivial. Designing games is where a lot of programmers first find their passion [1], and graphical output is fundamental to this.
  • Choose a language which lets them easily show off their work to friends. If they need to get their friends to install runtime frameworks and follow complicated instructions to show off, then they won't be getting the necessary kudos and comments they need. Don't underestimate the value of a peer saying "Hey, that's cool!"

Perhaps given these two criteria, Javascript with Processing.js [2] or Flash might be a good start point, though Flash obviously has the downside of requiring.. er... Flash.

Tangential thought: Flash is actually a really great way to teach OOP, since it's much easier to grasp the concepts of objects and classes when you can actually see them!

[1] http://www.codinghorror.com/blog/archives/000669.html
[2] http://processingjs.org/

47
[+1] [2009-05-13 02:23:30] Dean Rather

I remember finding simple loops amazing. Each time I learn a new language I usually throw something like this together:

<?php
$numberOfBottles = 99;
print("<h1>$numberOfBottles Bottles of Beer on the Wall</h1>");
print("$numberOfBottles bottles of beer on the wall,<br />");
print("$numberOfBottles bottles of beer!<br />");
print("Take one down, pass it around,<br />");
for($numberOfBottles--; $numberOfBottles>1; $numberOfBottles--)
{
    print("$numberOfBottles bottles of beer on the wall!<br />");
    print("<br />");
    print("$numberOfBottles  bottles of beer on the wall,<br />");
    print("$numberOfBottles  bottles of beer!<br />");
    print("Take one down, pass it around,<br />");
}
print("One last bottle of beer on the wall!");
?>

Maybe some variations with while or foreach loops would be easy too.


48
[+1] [2009-05-13 03:04:49] Darius Bacon

When Steve Wozniak [1] built his first Apple II he liked to show it off with a Breakout [2] game in Apple Basic, typed in on the spot. I think it actually was around 10 lines; I wish I had it to paste in here. You could probably also do it in a system like Processing [3].

[1] http://en.wikipedia.org/wiki/Steve_Wozniak
[2] http://en.wikipedia.org/wiki/Breakout_%28video_game%29
[3] http://en.wikipedia.org/wiki/Processing_%28programming_language%29

49
[+1] [2009-05-13 03:07:12] T.R.

If you're teaching engineers, this bit of Prolog might get their attention:

d(x,x,1).
d(C,x,0):-number(C).
d(C*x,x,C):-number(C).
d(-U, X, -DU) :- d(U, X, DU).
d( U + V, x, RU + RV ):-d(U,x,RU), d(V,x,RV).
d( U - V, x, RU - RV ):-d(U,x,RU), d(V,x,RV).
d(U * V,x, U * DV + V * DU):- d(U,x,DU), d(V,x,DV).
d(U^N, x, N*U^(N-1)*DU) :- integer(N), d(U, x, DU).

Just write down the rules, and you have a program that can do all of first semester calculus, in 8 lines of code.


50
[+1] [2009-05-18 22:26:52] Mr. Shickadance

I think any sort of shell script which can do something useful is a great way to show someone the power of programming. Being able to spend 10-20 minutes on a small script that will automate another task and save you countless hours is very impressive, imo.

For example, I once wrote a simple Perl script to convert mp3 files in one directory to another format and them burn them to a cd. You invoke the script with the path to a directory of MP3's and it burns the cd. At least I was impressed at the time.


51
[+1] [2009-06-02 22:22:29] ephemient

Logo [1] is always a terrific starting point.

Brian Harvey's UCBLogo page has this short example [2]:

Here is a short but complete program in Berkeley Logo:

to choices :menu [:sofar []]
if emptyp :menu [print :sofar stop]
foreach first :menu [(choices butfirst :menu sentence :sofar ?)]
end

And here's how you use it. You type

choices [[small medium large]
         [vanilla [ultra chocolate] lychee [rum raisin] ginger]
         [cone cup]]

and Logo replies

small vanilla cone
small vanilla cup
small ultra chocolate cone
small ultra chocolate cup
small lychee cone
small lychee cup
small rum raisin cone
small rum raisin cup
small ginger cone
small ginger cup
medium vanilla cone
medium vanilla cup
medium ultra chocolate cone
medium ultra chocolate cup
medium lychee cone
medium lychee cup
medium rum raisin cone
medium rum raisin cup
medium ginger cone
medium ginger cup
large vanilla cone
large vanilla cup
large ultra chocolate cone
large ultra chocolate cup
large lychee cone
large lychee cup
large rum raisin cone
large rum raisin cup
large ginger cone
large ginger cup

The program doesn't have anything about the size of the menu built in. You can use any number of categories, and any number of possibilities in each category. Let's see you do that in four lines of Java!

[1] http://en.wikipedia.org/wiki/Logo_%28programming_language%29
[2] http://www.eecs.berkeley.edu/~bh/logo-sample.html

+1 for LOGO. That was my first programming language, but at the time I didn't think of it as programming. - CoffeeRain
52
[+1] [2009-06-14 10:27:16] Bite code

I think this question is really good idea. I had a lot of sucky teachers, and the best one where obviously the guys with the will to show off a little bit.

There are plenty of code you can show them. The first that comes to my mind is Ed Felten [1]'s TinyP2P source code :

  import sys, os, SimpleXMLRPCServer, xmlrpclib, re, hmac # (C) 2004, E.W. Felten

  ar,pw,res = (sys.argv,lambda u:hmac.new(sys.argv[1],u).hexdigest(),re.search)

  pxy,xs = (xmlrpclib.ServerProxy,SimpleXMLRPCServer.SimpleXMLRPCServer)

  def ls(p=""):return filter(lambda n:(p=="")or res(p,n),os.listdir(os.getcwd()))

  if ar[2]!="client": # license: http://creativecommons.org/licenses/by-nc-sa/2.0

    myU,prs,srv = ("http://"+ar[3]+":"+ar[4], ar[5:],lambda x:x.serve_forever())

    def pr(x=[]): return ([(y in prs) or prs.append(y) for y in x] or 1) and prs

    def c(n): return ((lambda f: (f.read(), f.close()))(file(n)))[0]

    f=lambda p,n,a:(p==pw(myU))and(((n==0)and pr(a))or((n==1)and [ls(a)])or c(a))

    def aug(u): return ((u==myU) and pr()) or pr(pxy(u).f(pw(u),0,pr([myU])))

    pr() and [aug(s) for s in aug(pr()[0])]
    (lambda sv:sv.register_function(f,"f") or srv(sv))(xs((ar[3],int(ar[4]))))

  for url in pxy(ar[3]).f(pw(ar[3]),0,[]):
    for fn in filter(lambda n:not n in ls(), (pxy(url).f(pw(url),1,ar[4]))[0]):
      (lambda fi:fi.write(pxy(url).f(pw(url),2,fn)) or fi.close())(file(fn,"wc"))

Ok, it's 5 lines more than you "ten" limit, but still a fully functionnal Peer 2 Peer app, thansk to Python.

TinyP2P can be run as a server:

python tinyp2p.py password server hostname portnum [otherurl]

and a client:

python tinyp2p.py password client serverurl pattern

Then of course, story telling is very important. For such a purpose, 99 bottles of beer [2] is a really good start.

You can then pick up several example of funcky code like :

  • the famous Python one-liner :

    print("".join(map(lambda x: x and "%s%d bottle%s of beer on the wall, %d bottle%s of beer...\nTake one down, pass it around.\n"%(x<99 and "%d bottles of beer on the wall.\n\n"%x or "\n", x, x>1 and "s" or " ", x, x>1 and "s" or " ";) or "No bottles of beer on the wall.\n\nNo more bottles of beer...\nGo to the store and buy some more...\n99 bottles of beer.", range(99,-1,-1))))

  • the cheaty Python version (cool for student cause it shows network features) :

    import re, urllib print re.sub('</p>', '', re.sub('<br>|<p>|<br/> |<br/>','\n', re.sub('No', '\nNo', urllib.URLopener().open('http://www.99-bottles-of-beer.net/lyrics.html').read()[3516:16297])))

Eventually I'll follow previous advices and show some Javascript because it's very visual. The jQuery UI Demo web site [3] is plenty of nice widgets demo including snippets. A calendar [4] in few lines :

<script type="text/javascript">
    $(function() {
        $("#datepicker").datepicker();
    });
    </script>

<div class="demo">

<p>Date: <input id="datepicker" type="text"></p>

</div>

Bookmarklets have a lot of sex appeal too. Readibility [5] is quite interesting :

function() {
    readStyle='style-newspaper';readSize='size-large';
    readMargin='margin-wide';
    _readability_script=document.createElement('SCRIPT');
    _readability_script.type='text/javascript';
    _readability_script.src='http://lab.arc90.com/experiments/readability/js/readability.js?x='+(Math.random());
    document.getElementsByTagName('head')[0].appendChild(_readability_script);
    _readability_css=document.createElement('LINK');
    _readability_css.rel='stylesheet';
    _readability_css.href='http://lab.arc90.com/experiments/readability/css/readability.css';
    _readability_css.type='text/css';_readability_css.media='screen';
    document.getElementsByTagName('head')[0].appendChild(_readability_css);
    _readability_print_css=document.createElement('LINK');
    _readability_print_css.rel='stylesheet';_readability_print_css.href='http://lab.arc90.com/experiments/readability/css/readability-print.css';
    _readability_print_css.media='print';
    _readability_print_css.type='text/css';
    document.getElementsByTagName('head')[0].appendChild(_readability_print_css);
}
[1] http://www.freedom-to-tinker.com/
[2] http://www.99-bottles-of-beer.net/
[3] http://jqueryui.com/demos/
[4] http://jqueryui.com/demos/datepicker/
[5] http://lab.arc90.com/experiments/readability/

Here's my Python 2.6 solution. 292 characters: print"".join(("%s%s on the wall, %s.\n"+(i>0 and"Take 1 down and pass it around, "or"Go to the store and buy some more, 99 bottles of beer on the wall."))%(i<99 and"%s on the wall.\n\n"or"","%s","%s")%((2+(i<99))*("%s bottle%s of beer"%(i or"No more",i!=1 and"s"or""),))for i in range(99,-1,-1)) Note that this follows the format given at 99-bottles-of-beer.net/lyrics.html - Ponkadoodle
53
[+1] [2009-06-15 22:08:38] trolle3000

Try having your students program a Magic 8ball. A basic 8ball answering "yes" or "no" could probably be programmed in less than 10 lines of code, and it can be expanded incrementally in any number of ways:

  1. First, make it simple: input something like "s" for shake into a CLI; 8ball answers "yes" or "no"
  2. Next, input a question, display the question along with the answer
  3. Then expand the possible answers.... Loads of options, the students who are quick to catch on can have some fun ("Look, the computer says dirty words!!"), while you help the others
  4. Implement a timer, so you can't ask the same question again right away, in case you don't like the answer
  5. Group possible answers into variants of "yes", "no" and "hazy" or something; first RNG decides type of answer, second RNG decides the specific answer
  6. Reconfigure the timer; you can ask again right away if the answer is hazy
  7. Make a frame of *'s around the text
  8. And so on....

A magic 8ball is something most people can relate to, and it's an introduction to basic strings, floats/ints, IO, CLI, boolean and RNG's, using only the simplest tools. And it's simple, (somewhat) fun, and can easily be expanded. Depending on you're approach, you could make the programming object-oriented at once, with class 8ball(), class YesAnswer() and whatnot.

Good luck ;-)


54
[+1] [2009-07-02 04:17:20] too much php

This PHP code only works on a Mac through the command-line, but it's very useful when everyone wants to play Twister [1]

$lr = array('left', 'right');
$hf = array('hand', 'foot');
$colour = array('red', 'yellow', 'blue', 'green');
while(true) {
    $a = $lr[array_rand($lr)];
    $b = $hf[array_rand($hf)];
    $c = $colour[array_rand($colour)];
    system("say $a $b $c");
    sleep(5);
}
[1] http://en.wikipedia.org/wiki/Twister_(game)

55
[+1] [2010-04-23 18:31:46] Gregory Gelfond

Here is a program in the language of A-Prolog that computes the N coloring of a graph ("c" denotes colors, "v" denotes vertices, and "e" denotes edges).

c(1..n).                                           
1 {color(X,I) : c(I)} 1 :- v(X).             
:- color(X,I), color(Y,I), e(X,Y), c(I).

On a side note, the way I got my students excited last semester was to tell them a story. It went something along the lines of: "Picture a triangle. It's a purely mathematical object, no real triangles exists. We can reason about them, discover their properties, and then apply those properties towards real world solutions. An algorithm is also a purely mathematical object. Programming is a form of magic however. We can take a mathematical object, describe it a language, and lo and behold it can manipulate the physical world. Programming is a unique discipline that bridges these two worlds."


56
[+1] [2011-12-31 05:39:39] pageman

from Andrew Cooke's Malbolge: Hello World [1]

let them try this in Malbolge:

(=<`$9]7<5YXz7wT.3,+O/o'K%$H"'~D|#z@b=`{^Lx8%$Xmrkpohm-kNi;gsedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543s+O<oLm

that's "Hello World" in the most difficult programming language in the whole world that took two years to find :)

They can go to Lou Scheffer's Malbolge page after [2] :)

of course you can go the No. 1 (!!!) 99 Bottles of Beer Program in the World by Hisashi Iizawa (it's a ONE LINER!) [3] and here's a pdf by Masahiko Sakai on Malbolge [4]

[1] http://acooke.org/malbolge.html
[2] http://www.lscheffer.com/malbolge.shtml
[3] http://99-bottles-of-beer.net/language-malbolge-995.html
[4] http://www.coltech.vnu.edu.vn/~hoangta/jvse2010/Sakai-JVSE2010.pdf

57
[0] [2009-05-01 18:47:21] igotmumps

Most of these answers use an API of some kind, which sort of breaks the 10 lines of code requirement. Each API call can be hundred of lines of code. The original question says to use 'Simple Code'. This to me means no API calls. What kind of answers can we come up with that just uses this definition of 'simple code'?


(3) -1 Yeah, I'm sure the real intent was actually to start the class coding in assembly. If API calls were out of the question, why wasn't a language specified? After all, many functionalities that are supported by various higher-level languages require importing standard libraries in some but are built-ins in another. We could make all the examples in php, just to disguise all our API calls as built-in functions. - David Berger
(1) I was more getting at solving complex problems using the practice of computer science than just calling cool API's to draw stuff on the screen. What about using recursion or functional programming or other practices that might be taught in computer science. With ten lines of code, you could do alot of cool stuff. - igotmumps
58
[0] [2009-05-02 01:40:40] Matt Egan

I think some cool expiriments in Python with NodeBox [1] would be a cool start. It has functions to draw things from squares to complex paths. It can even take in images from the Mac iSight/ Webcam and manipulate it by scaling, rotating and applying filters.

Sadly, it's only for Mac OS X, so I don't think it would be of much use to teach it, but as an example (if you have a Mac yourself) for what's possible with a little bit of code, it would be pretty nifty.

[1] http://www.nodebox.net

59
[0] [2009-05-02 01:53:54] xkcd150

hmm, I remember making snowflakes and fire in QBasic [1] when a friend came by and showed me how to do a rotating 3D cube and totally blew my mind.

And then I modified my fire onto the cube and it was good times.

Have to see if I can find those old scripts somewhere, they weren't very lengthy.

[1] http://en.wikipedia.org/wiki/QBasic

60
[0] [2009-05-02 06:50:05] blank

When I was a kid this was the coolest thing ever:

10 PRINT "BEDWYR "
20 GOTO 10

I guess it won't cut it much these days ;)


61
[0] [2009-05-02 22:17:32] Anthony Brien

In WPF, you can write a fully functional Thumbnail View in a few XAML lines:

<ListBox ItemsSource={Binding MyItems}
         ScrollViewer.HorizontalScrollBarVisibility="Hidden">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source={Binding FullPath} Width="50" />
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

This is, assuming you have a MyItems collection of items that contain a FullPath property that points to image files.

The magic comes from the ItemTemplate that transforms each list box item into an image, and the ItemsPanelTemplate that changes the default vertical stack panel to a wrap panel.


62
[0] [2009-05-03 23:49:07] Liran Orevi

First To get maximum attention at minimum time, you'll want to use a high-level language. probably you'll want to show 3D [1].

I'd go with Opengl [2] - I'd start by showing a short scene from a 3d computer game, then explaining, that this was done by dividing the big program into smaller parts, and then showing them how a little part may look like. something like lesson 05 on nehe.gamedev.net [3], or maybe even a more advanced lesson. it's quite impressive, and not too complicated.

Also you may want to check Alice [4] which contains 3d and was designed to teach..

[1] http://en.wikipedia.org/wiki/File:Glasses_800_edit.png
[2] http://en.wikipedia.org/wiki/OpenGL
[3] http://nehe.gamedev.net/lesson.asp?index=01
[4] http://www.alice.org/

OpenGL has so many boring low level details. It always bore me when I Was trying to learn it. Specially when the tutorial is based in Win32 API, which is even more boring!!!! - hasen
There is a difference between learning something to the tiniest details, and giving a short demo followed by a brief overview of the big idea. - Liran Orevi
63
[0] [2009-05-04 00:42:36] Rob

Something like ...

10 rem twelve times table

20 For x = 1 to 12

30  For y = 1 to 12

40     print using"####";x*y;

50  next y

60  print 

70 next x

80 end

64
[0] [2009-05-04 00:59:43] hasen

When I was a little kid, I had a keen interest in computers (MSX back then), and consequently programming (all there was, was a variant of Basic). I lost that after I grew up, but I got back to it when I learned that Counter-Strike was just a mod made by some fans by modifying Half-Life code. That made me really interested in programming all over again!

It's not 10 lines of code, but if you show people the source code for some game, and then modify that and make it do something different, and demonstrate it to them live, it's reaaaaally gonna blow them away. Wow, this actually is not dark magic! You can do it!

Now a days, there are quite a few games you can do this with. I think the source code for all the Quake series (atleast I through III) is released. I know for a fact that you can create mods for Half-Life and Half-Life2, I'm sure other games like Unreal and FarCry also offer a similar ability.

Some simple things that could spark grate motivation:

  • Make a weapon super powerful (e.g., infinite ammo, higher damage, auto-aim .. etc.
  • Add an Anime-style movement (flying, dashing really fast, etc).

The modification itself shouldn't take too many lines of code, but the fact that it works is just amazing.


65
[0] [2009-05-05 08:25:55] OEP

I wrote this for a forum game -- writing the ROT13 algorithm in as few lines as possible. So, how about this in C?

rot13(char*s)
{
    int i=-1;
    do{
        i++;
        s[i] = (s[i] >= 65 && s[i] <=90 || s[i] >= 97 &&s [i] <= 122) ?
            ((s[i] < 97) ? 65 : 97) + (((s[i] - ((s[i] < 97) ? 65 : 97)) + 13) % 26) :
            s[i];
    } while(s[i] > 0);
}

I think the ternary operator is pretty neat, though I hear it is slower than if constructs. I have yet to time it for myself...


The ternary operator is useful if not overused, but I don't see how this code will do anything but confuse students. - danio
(4) For the love of god don't show this to your students. - OEP
Did you mean 'many' instead of 'few'? hea-www.harvard.edu/~fine/Tech/rot13.html - sigfpe
66
[0] [2009-05-05 09:04:17] danio

Inspired by Robin Day and John Topley's answers, get them to paste the following into the address bar oftheir browser:

javascript:var name=prompt("What is your name?", "");var msg='Hello '+name+'<br>';newwindow=window.open();newdocument=newwindow.document;for (var i=0;i<100;i++){newdocument.write(msg);}newdocument.close();

Or more readably:

var name=prompt("What is your name?", "");
var msg='Hello '+name+'<br>';
newwindow=window.open();
newdocument=newwindow.document;
for (var i=0;i<100;i++)
{
    newdocument.write(msg);
}
newdocument.close();

67
[0] [2009-05-05 10:32:23] Stephen Denne

The Mandelbrot Set can be presented in a way that isn't terribly complex, for example in Java below:

public class MiniMandelbrot {
    public static void main(String[] args) {
        int[] rgbArray = new int[256 * 256];
        for (int y=0; y<256; y++) {
            for (int x=0; x<256; x++) {
                double cReal=x/64.0-2.0, cImaginary=y/64.0-2.0;
                double zReal=0.0, zImaginary=0.0, zRealSquared=0.0, zImaginarySquared=0.0;
                int i;
                for (i = 0; (i < 63) && (zRealSquared + zImaginarySquared < 4.0); i++) {
                    zImaginary = (zReal * zImaginary) + (zReal * zImaginary) + cImaginary;
                    zReal = zRealSquared - zImaginarySquared - cReal;
                    zImaginarySquared = zImaginary * zImaginary;
                    zRealSquared = zReal * zReal;
                }
                rgbArray[x+y*256] = i * 0x040404;
            }
        }
        java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage(256, 256, 1);
        bufferedImage.setRGB(0, 0, 256, 256, rgbArray, 0, 256);
        javax.swing.JOptionPane.showMessageDialog(null, new javax.swing.ImageIcon(bufferedImage), "The Mandelbrot Set", -1);
    }
}

68
[0] [2009-05-05 13:32:09] BenAlabaster

This is by far the coolest thing I've seen... and when broken down, it's actually pretty simple:

http://blogs.msdn.com/lukeh/archive/2007/04/03/a-ray-tracer-in-c-3-0.aspx


69
[0] [2009-05-24 11:00:22] Geo

A basic grep application in Ruby/Python/Perl.


70
[0] [2009-05-25 04:53:29] gltovar

A bit off topic but you can check out this tweet coding which used as3 code that was less than 140 characters:

http://gskinner.com/playpen/tweetcoding_0/

^_^


71
[0] [2009-06-14 09:04:35] Arjan

Recursion can also be used to solve a maze. Just like the Sierpinski triangle and other art, for me this is much more fun than solving some mathematical problem.


72
[0] [2009-06-14 09:22:26] scott

Building on top of the SAPI example you provided, I use this to read files out loud to myself (just drag and drop a text file onto it's icon or run it from the command line)

speakfile.vbs:

strFileName = Wscript.Arguments(0)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, 1)
strText = objFile.ReadAll
Set objVoice = CreateObject("SAPI.SpVoice")
objVoice.Speak strText

73
[0] [2009-07-02 02:23:23] Mohan Narayanaswamy

10 Print "Mohan"
20 Goto 10


74
[0] [2009-07-02 03:26:08] baudtack

I've always liked the Tower of Hanoi. In Scheme

(define (hanoi x from to spare)
  (if (= x 1)
    (begin
      (display "move ")(display from)(display " to ")(display to)(display "\n"))
  (begin
    (hanoi (- x 1) from spare to)
    (hanoi 1 from to spare)
    (hanoi (- x 1) spare to from))))

Example output

gosh> (hanoi 3 'start 'dest 'spare)
move start to dest
move start to spare
move dest to spare
move start to dest
move spare to start
move spare to dest
move start to dest
#<undef>

Also in Python (though this can't do 1000 discs like the Scheme version can)

def hanoi(x, source, dest, spare):
  if x == 1:
    print "%s to %s" % (source, dest)
  else:
    hanoi(x - 1, source, spare, dest)
    hanoi(1, source, dest, spare)
    hanoi(x - 1, spare, dest, source)

75
[0] [2009-08-03 11:42:41] Chloe

How about Processing for JavaScript? I don't know Processing, but the code always seems rather small for what it can do, it's very visual, and you can run it in a browser.
http://processingjs.org/exhibition


76
[0] [2010-03-26 00:34:00] jfs

Convert an image to music in Python

From my answer [1] to How do I loop through every 4th pixel in every 4th row, using Python? [2]:

#!/usr/bin/env python
import easygui # http://easygui.sourceforge.net/
import Image   # http://www.pythonware.com/products/pil/
import numpy   # http://numpy.scipy.org/

filename = easygui.fileopenbox() # pick a file
im = Image.open(filename) # make picture
im.show() # show picture
ar = numpy.asarray(im) # get all pixels
N = 4
pixels = ar[::N,::4]  # every 4th pixel in every N-th row
notes = pixels.sum(axis=2) / 9 + 24 # compute notes [0, 52]
print "number of notes to play:", notes.size

Notes can correspond to different tones. I use here equal tempered scale [3]:

# play the notes
import audiere # http://pyaudiere.org/
import time

d = audiere.open_device()
# Notes in equal tempered scale 
f0, a = 440, 2**(1/12.)
tones = [d.create_tone(f0*a**n) for n in range(-26, 27)] # 53

for y, row in enumerate(notes):
    print N*y # print original row number
    for t in (tones[note] for note in row):
        t.volume = 1.0 # maximum volume
        t.play()
        time.sleep(0.1) # wait around 100 milliseconds
        t.stop()
[1] https://stackoverflow.com/questions/2376505/how-do-i-loop-through-every-4th-pixel-in-every-4th-row-using-python/2377061#2377061
[2] https://stackoverflow.com/questions/2376505/how-do-i-loop-through-every-4th-pixel-in-every-4th-row-using-python
[3] http://www.phy.mtu.edu/~suits/NoteFreqCalcs.html

77
[0] [2010-04-01 06:08:28] Sarfraz

I created Advanced Calculator With 4 Lines of Code [1]

[1] http://sarfraznawaz.wordpress.com/2010/02/28/creating-advanced-calculator-with-4-lines-of-code/

78
[0] [2010-04-01 08:17:40] Pawan Mishra

You can use jQuery(Write Less,Do More) library to achieve splendid visual effect in HTML webforms with minimal coding. Otherwise functional languages like F# too can do lots of stuff with few lines of codes . Following is solution for problem number 8 of Project euler :-

data :- string of numbers in 50 * 20 grid

let data = txt |> Seq.toList |> List.filter System.Char.IsDigit |> List.map System.Char.GetNumericValue

let rec partition_5 l = match l with | x1::(x2::x3::x4::x5::_ as t) -> [x1;x2;x3;x4;x5]::(partition_5 t) | _ -> []

let euler_8 = List.map (fun x -> List.fold (*) 1.0 x) (partition_5 data) |> List.max


79
[0] [2011-08-16 18:57:32] ockin

My first program is somewhat similar to one already mentioned here [1], but my is one line shorter and much more polite:

10 PRINT "What is your name?"
20 INPUT A$
30 PRINT "Thanks"
[1] https://stackoverflow.com/questions/811074/what-is-the-coolest-thing-you-can-do-in-10-lines-of-simple-code-help-me-inspire/811081#811081

80
[0] [2011-08-27 17:38:05] DaveFar

At http://www.youtube.com/watch?v=a9xAKttWgP4 you can watch Conway's Game Of Life programmed (and simultaneously verbally commented) in about 5 lines of APL (A Programming Language).

It's fun to watch and can inspire students that programming is cool, and math, and mathematical, concise programming languages :)

BTW, Uncle Bob Martin mentioned this youtube video on a hanselminutes podcast.


I'm not absolutely sure APL is the first language you want to introduce beginners to. :) - ShdNx
81
[0] [2011-12-30 14:24:03] Zhen

Squeak is a good tool for inspire

E.g: http://squeakland.jp/school/drive_a_car/html/Drivecar12.html


82
[0] [2011-12-30 16:22:32] Paul

Here's my 10 line web spider. Technically it's 11 including the perl shell declaration but I hope that's forgivable!

I wanted to get it to identify certain file types and support relative paths, but ran out of lines!

To run:

perl spider.pl http://yahoo.com/search?q=test

Note that Google doesn't allow LWP Simple without a user agent so searching Google won't work. No room for that either! Anyway, where's the code:

#!/usr/bin/perl -w
use LWP::Simple;
my @queue = ($ARGV[0]);
my %visited = ();
while (my $url = pop(@queue)) {
    next if $visited{$url};
    $visited{$url} = 1;
    my $html = get($url) or next;
    print "Spidering $url\n";
    push(@queue, $html =~ m/(http:\/\/[^'"]*)/g);
}

83
[0] [2011-12-31 09:54:12] salezica

Use games! Not coding games, but coding competitions. Think of the Google AI challenge, and dumb it down.

Let me give an example. I once made a little contest with my friends: one of us set up a framework for a simulation, and the rest coded an AI ranging from the simple to the heavily analitic, and we fired a hundred runs to see which AI performed best.

The framework? Basic I/O: the simulation control was executed by a process that spawned one child per competing AI, and each round of the simulation wrote data to the standard input pipes, and read the outputs. This way, we could write our AIs in whatever language we wanted, just by following a very simple protocol.

The rules were terribly simple, yet the thing was challenging: we had two villages, A and B, which distributed money equally among the families that lived there. A had 800 coins to give, and B had 500. Each round, all of the AIs were asked to chose a village to live in (printing 'A' or 'B' to stdout), and then got back the totals for each village during that period (by reading numbers from stdin). The goal was to have the most money after a hundred rounds.

Some of the AIs we created had really complex mechanisms to try and guess what village to settle in -- though they weren't really good, for the winner was a strategy that simply always picked the village that gave the least money to each family last round (assuming most would move out to the other village the next time).

I think this is engaging, encourages research and is a healthy way of competition. There are thousands of games that could be played, and it only requires basic programming knowledge (standard I/O!) for the players to interact.


84
[0] [2011-12-31 15:31:54] Sparky

Here is something fun using javascript

function checkLove(love)
{
    if (love)
        alert("He he he, cool!");
    else
    {
        if(love != undefined) alert("Sorry, you must love me.");
        checkLove(confirm("Do you love me?"));
    }
}
checkLove();

It's kindof only 10 lines! You can either include it it a webpage or just copy paste the below code in your browser's url bar and hit enter

javascript:function checkLove(love){if (love)alert("He he he, cool!");else{if(love != undefined) alert("Sorry, you must love me.");checkLove(confirm("Do you love me?"));}}checkLove();

Fun, right?


85
[-1] [2009-11-22 00:06:08] user58670

Messing around with cookies.

Its cookies! Kids loooovvve cookies!

  1. Find a site that relies on cookies for something.
  2. Use firefox addon to edit the cookie.
  3. ????
  4. Learning!!!

86
[-1] [2009-12-03 07:44:09] David Kanarek

From Quake 3 I believe, a very fast 1/sqrt(x):

#include <stdio.h>
#include <stdlib.h>
int main (int argc, char const* argv[])
{
    if (argc != 2) {
        printf("Need a number!\n");
        return 0;
    }
    float number = atof(argv[1]);
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;  // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 ); // what the?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
    printf("%f\n", y);
    return 0;
}

(6) en.wikipedia.org/wiki/Fast_inverse_square_root Also, I don't think this is good to show programming beginners :) - Makach
87