405
votes

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 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, 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 that are easy to understand would be good ideas and I'm going to look into those. Here are some complicated actionscript examples but that's a bit too advanced and I can't teach flash. What other ideas do you have?

6
  • 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
    Commented May 1, 2009 at 12:18
  • 2
    Your one line VBS script doesn't work on my Mac! :-P Good question though. Commented May 1, 2009 at 12:23
  • 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
    Commented May 1, 2009 at 17:05
  • 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... Commented May 1, 2009 at 18:45
  • 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.. :-) Commented May 18, 2009 at 22:17

87 Answers 87

338
votes

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 =)

10
  • 95
    "One-liner" is such a misnomer. That's 3 lines, really. Any code can be one line if you want it to be. Commented Jul 4, 2009 at 20:24
  • 5
    This looks really neat, but is there a way to get the page once it is modified?
    – Sylver
    Commented Aug 23, 2009 at 3:24
  • 1
    @Kugel: it works for me in FF. BTW, why'd you put true in quotes? Commented Feb 27, 2010 at 21:00
  • 4
    This is no longer true in Firefox as javascript: has been disabled. A shame.
    – user18015
    Commented Dec 30, 2011 at 19:52
  • 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
    Commented Dec 31, 2011 at 1:25
200
votes

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.

22
  • 15
    would be better with the following: 40 GOTO 30
    – spender
    Commented May 1, 2009 at 11:51
  • 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 -
    Commented May 1, 2009 at 12:42
  • 13
    Should be goto 10 surely so somone else can enter thier name... Commented May 1, 2009 at 14:39
  • 17
    You forgot 35 PRINT CHR$(7) Commented May 1, 2009 at 16:25
  • 6
    this is how i learnt programming too. Its the best answer imo. +1 to accept this one
    – Ali
    Commented May 2, 2009 at 1:47
180
votes

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

14
  • 25
    For the record, that's a Sierpinski gasket.
    – chaos
    Commented May 1, 2009 at 12:36
  • 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. Commented May 1, 2009 at 12:38
  • 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. Commented May 18, 2009 at 22:44
  • 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
    Commented Jul 19, 2009 at 20:54
  • 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. Commented Sep 15, 2009 at 21:59
105
votes

Microsoft has Small Basic, an IDE for "kids".

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

It is specifically designed to show how cool programming is.

12
  • 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
    Commented May 4, 2009 at 0:27
  • 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
    Commented May 4, 2009 at 1:27
  • 28
    @hansen j, thats unfair, everybody has to start someplace. Commented May 7, 2009 at 7:34
  • 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
    Commented May 19, 2009 at 15:14
  • 29
    Knowing the kids that I've tried to teach, it'd be about ten seconds before they try pic = Flickr.GetRandomPicture("boobs") Commented Dec 20, 2010 at 13:00
83
votes

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]

2
  • This is really neat! I wasn't familiar with the SyndicationFeed object - thanks for the code! Commented May 1, 2009 at 15:40
  • Target audience is non-geeks, ergo, they don't give a damn about tweeter?
    – bobflux
    Commented Nov 22, 2009 at 0:33
80
votes

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()
78
votes

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 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. I have not tested this so cannot verify whether it operates.

9
  • That's awesome. This deserves way more upvotes.
    – Tom Ritter
    Commented Jun 14, 2009 at 19:25
  • Thanks for the recognition Tom. Sucks that I'll get no rep points even if it starts to get upvotes though. :-P
    – Bob Mc
    Commented Dec 16, 2009 at 17:15
  • 32
    This way you can see the paperclip all the time :D
    – Pedery
    Commented Dec 19, 2009 at 17:47
  • 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. Commented Sep 7, 2011 at 23:34
  • 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
    Commented Sep 8, 2011 at 16:48
68
votes

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. 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. Recursion and randomization are key to making beautiful pictures.
  • Storytelling. With an easy-to-use 3D programming environment like Alice, 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.

6
  • 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 Commented Nov 17, 2009 at 11:58
  • 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. Commented Jun 8, 2010 at 4:57
  • 3
    If you're customizing sites, why not then use Greasemonkey?
    – new123456
    Commented Jul 4, 2011 at 0:54
  • 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. Commented Dec 31, 2011 at 2:58
  • @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
    Commented Jan 1, 2012 at 19:16
63
votes

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.

7
  • Modern day computers do a lot more than one thing at a time.
    – dreamlax
    Commented May 1, 2009 at 12:16
  • But, does your code do more than one thing at a time?
    – JeffO
    Commented May 1, 2009 at 12:27
  • 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. Commented May 1, 2009 at 12:33
  • 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? Commented May 1, 2009 at 18:27
  • 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." Commented May 19, 2009 at 0:46
62
votes

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
2
  • 5
    Nice! Too bad there isn't any spot on there that actually says "Hello World!" Commented Feb 27, 2010 at 21:33
  • This is pretty! Mandelbrot model :D
    – Aniket
    Commented Dec 31, 2011 at 13:48
44
votes

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)
7
  • 2
    ok, but you should give a concrete example u know ..
    – hasen
    Commented May 4, 2009 at 0:46
  • 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. Commented May 4, 2009 at 18:06
  • 7
    Well not a very exciting example, but you could do javascript:alert("Hello World"); Commented May 4, 2009 at 21:02
  • I prefer: "javascript: for(var i=0;i>-1;i++)alert('Congratulations, you have pressed enter for '+i+' times!');". (Read that code before running...). ^^ Commented May 24, 2009 at 11:07
  • +1 for the wow-factor... pretty spectacular example :)
    – fretje
    Commented Jun 10, 2009 at 13:23
37
votes

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 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)
5
  • 4
    More interesting would be to have the user pick the random number, then have the computer guess it. Commented Jun 15, 2009 at 22:17
  • 15
    Now make these two programs play each other over a socket.
    – Josh Lee
    Commented Dec 4, 2009 at 9:14
  • 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. Commented Feb 27, 2010 at 21:10
  • 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
    Commented Sep 16, 2011 at 6:13
  • I think you want raw_input. Input is equal to eval(raw_input(prompt)). See input. Commented Dec 31, 2011 at 5:13
26
votes

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.

3
  • 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
    Commented Nov 27, 2009 at 5:02
  • 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
    Commented Apr 28, 2010 at 5:45
  • 2
    That would be an interesting time to teach people to navigate via tab and space. Commented Dec 30, 2011 at 15:55
23
votes

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

:(){ :|:& };:
6
  • 7
    Here's a pretty good explanation: cyberciti.biz/faq/understanding-bash-fork-bomb
    – hodgesmr
    Commented Jun 21, 2009 at 23:52
  • 12
    for new to linux guys:don't run, else you will loose all your work.
    – Behrooz
    Commented Jul 7, 2010 at 16:29
  • @Behrooz, depends on your distro, some have arbitrary thread/fork limits built in. Commented Mar 2, 2011 at 21:20
  • It makes a big bang on SuSE, but makes just nothing on most debian based distros.
    – Behrooz
    Commented Mar 7, 2011 at 19:39
  • That, as well as user limits, how often your disk caches are flushed, your filesystem...
    – new123456
    Commented Jul 4, 2011 at 0:57
22
votes

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

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
  • 5
    How is this supposed to teach anyone anything? On an unrelated note, COOL! HA! Loved it!
    – salezica
    Commented Dec 31, 2011 at 9:38
21
votes

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>
3
  • 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
    Commented Aug 23, 2011 at 17:38
  • 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
    Commented Dec 31, 2011 at 11:35
  • 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
    Commented Dec 31, 2011 at 22:11
20
votes

One thing you might consider is something like Robocode, 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);
 }
}
3
  • 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
    Commented May 1, 2009 at 12:15
  • 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
    Commented May 1, 2009 at 19:34
  • 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 Commented May 2, 2009 at 4:22
18
votes

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 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.

17
votes

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
  • +1 I think processing is a great way to teach algorithmic thinking which is the most important topic beginners need to learn.
    – Nils
    Commented Dec 31, 2011 at 12:37
15
votes

You could use a script written with AutoIt, 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
  • ++ I'm not sure where it would fit in a lesson plan, but it is cute. Commented May 1, 2009 at 18:32
13
votes

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 );
}
13
votes

I think a good place for a student to get started could be Greasemonkey. 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'; }
10
votes

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" );
9
votes

With Tcl 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()
9
votes

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

1
  • 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
    Commented May 1, 2009 at 14:02
8
votes

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.

8
votes

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

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  
6
  • 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. Commented Nov 22, 2009 at 19:59
  • Well, then maybe the shortest program needs to be half its current size...
    – JohnFx
    Commented Nov 23, 2009 at 3:09
  • Really neat. I hate having to type long paths and then wonder if there is a typo
    – Sylver
    Commented Apr 18, 2011 at 4:13
  • 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
    Commented Dec 30, 2011 at 23:13
  • I have Windows 7 and it does NOT do that.
    – JohnFx
    Commented Dec 31, 2011 at 2:46
7
votes

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.

1
  • That's great for a semester project. I wish I had thought of that back when I was teaching. Commented May 2, 2009 at 2:02
7
votes

wxPython First Steps

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

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

6
votes

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.