views:

10832

answers:

78

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?

+88  A: 

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.

Robin Day
would be better with the following:40 GOTO 30
spender
thanks spender... done :)
Robin Day
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
@saua: You're right, except it says goto 30. Whatever, I think we get the idea.
Mike Dunlavey
+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.
yx
@yx: People do love seeing their own name. It does get them interested.
Mike Dunlavey
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
Should be goto 10 surely so somone else can enter thier name...
Omar Kooheji
You forgot 35 PRINT CHR$(7)
Adam Jaskiewicz
this is how i learnt programming too. Its the best answer imo. +1 to accept this one
Click Upvote
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. :)
Marcus Lindblom
only geeks will get amazed with this.
Francis
+1, and another +1 because I agree with what you say about library calls.
hasen j
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
Shortly after learning this script I learned the value of Ctrl+Break
Mike Robinson
I did this on Commodore64. My first programming experience. ^^
Arnis L.
Get the the screen full with one's name is cool. +1 for 40 goto 30.
Marcus Lindblom
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
+13  A: 

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);
 }
}
Welbog
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
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.
T Pops
+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
+6  A: 

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

Stevo3000
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
+1  A: 

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

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

JPrescottSanders
+34  A: 

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.

Mike Dunlavey
+1 for the insults
Robin Day
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?
Jeff O
@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
@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
+10, I love your reasoning
hasen j
""Computers only do one thing at a time"" --yeah, but have you heard of this multi-core fad? ;-)
foljs
@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
+5  A: 

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)
}
MunkiPhD
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
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.
T Pops
@T Pops: ditto, but with QBasic! Creating physics simulators for projectile motion, collision dynamics, etc really helped me understand the problems much better!
nickf
+5  A: 

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.

ChrisF
+1  A: 

I was blown away by some of the stuff that was shown in the talk Easy AI with Python (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).

David Wolever
+5  A: 

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.

Andrew Sledge
+98  A: 
tharkun
You know what, you could probably roll a manderbolt in the same or less.
Tim Post
For the record, that's a Sierpinski gasket.
chaos
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
really nicely done!
ojblass
@tharkun: I did the same with Java recently unsuccessfully at http://www.java-forums.org/new-java/12357-java-zelda-triangle-problem.html . How would you do the same in Java?
Masi
@Masi: no clue, I'd have to learn Java first.
tharkun
@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. http://pastebin.com/f69c3105b
Jasper Bekkers
works with more than 3 points too.
EvilTeach
For the record, that is not a Sierpinski gasket...It is, in fact, the Triforce. http://en.wikipedia.org/wiki/The_Legend_of_Zelda
jason
Steve Wortham
Jonas Elfström
+3  A: 

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!

Tim Post
+39  A: 

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)
John Topley
ok, but you should give a concrete example u know ..
hasen j
@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.
Masi
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 L.
+1 for the wow-factor... pretty spectacular example :)
fretje
This is awesome. Looks best on photo galeries like flickr!
ypnos
awesome code example!!
knittl
+7  A: 

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()
Bryan Oakley
+4  A: 

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.

Jeff O
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.
Wallacoloo
+52  A: 

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]

Martin Peck
+1: Showing something that they can relate to would be a huge plus.
Jon Tackabury
This is really neat! I wasn't familiar with the SyndicationFeed object - thanks for the code!
Terry Donaghe
Target audience is non-geeks, ergo, they don't give a damn about tweeter?
peufeu
+19  A: 

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.

Ryan Anderson
++ Good entertaining trick.
Mike Dunlavey
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
+76  A: 

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.

Bob Fanger
That looks like an awesome resource.
tomfanning
Neat! Thanks for sharing!
rascher
Woah, that's really cool. I think I'll use this to try to get my niece interested in programming a couple years.
pyrochild
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.
Matt Olenik
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 j
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
@hansen j, thats unfair, everybody has to start someplace.
jfar
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
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
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
::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
+23  A: 

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)
Vinzcent
binary search! :)
Andrioid
More interesting would be to have the user pick the random number, then have the computer guess it.
Erik Forbes
binary solo! :)
MGOwen
Now make these two programs play each other over a socket.
jleedev
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.
Wallacoloo
+12  A: 

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"&gt;&lt;/script&gt;
<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"/&gt;
</body>
</html>
Jon Winstanley
+41  A: 

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()
+9  A: 

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")
meepmeep
++ I'm not sure where it would fit in a lesson plan, but it is cute.
Mike Dunlavey
+6  A: 

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.

Robert S.
That's great for a semester project. I wish I had thought of that back when I was teaching.
Mike Dunlavey
A: 

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'?

igotmumps
-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
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
+8  A: 

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 );
}
Josh Curren
+8  A: 

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" );
Greg
+9  A: 

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

Jeffrey Berthiaume
A: 

I think some cool expiriments in Python with NodeBox 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.

Matt Egan
A: 

hmm, I remember making snowflakes and fire in QBasic 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.

xkcd150
+2  A: 

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 http://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon.

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

torial
+23  A: 

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-83 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 iPod. 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 CS4 (retail price: $2,500; 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 Microsoft Popfly and 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.

Barry Brown
+1 for Alice. That actually looked kinda cool.
Lucas McCoy
+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
-1 Extremely insulting and stereotypical.
Wallacoloo
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: http://www.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
A: 

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

Bedwyr Humphreys
+6  A: 

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'; }
joeytwiddle
+2  A: 

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.

yetanotherdave
+2  A: 

Take a look at these projects:

  • Hackety Hack: specifically aimed at making coding accessible and attractive for non-programmers.
  • Shoes: fun and minimalistic approach to desktop applications
  • Processing: environment and (java-like) language for programming images, animation and more.
benlenarts
A: 

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.

Anthony Brien
A: 

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

I'd go with Opengl - 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, or maybe even a more advanced lesson. it's quite impressive, and not too complicated.

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

Liran Orevi
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 j
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
A: 

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
Rob
A: 

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.

hasen j
+7  A: 
Kronikarz
A: 

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
For the love of god don't show this to your students.
A: 

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();
danio
A: 

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);
    }
}
Stephen Denne
+2  A: 

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) );
}
A: 

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

BenAlabaster
+1  A: 
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')
Paul Harrison
+21  A: 

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.

Bob Mc
That's awesome. This deserves way more upvotes.
Tom Ritter
Thanks Tom. I always thought it was really cool as well.
Bob Mc
I'm accepting this answer because it was one of the biggest hits in the class, but is stagnating by only having a few upvotes. I want to bring a lot more attention to this.
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
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
+134  A: 

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

Espenhh
Wow, that's sick!
MiseryIndex
Awe-inspiring. High score page, here we come.
Thomas L Holaday
"One-liner" is such a misnomer. That's 3 lines, really. Any code can be one line if you want it to be.
DisgruntledGoat
This is actually really cool. I never thought about it.
the_drow
really cool. good way to introduce people to javascript, which a lot of new programmers should find appealing since everyone uses the web.
LoveMeSomeCode
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 http://stackoverflow.com/questions/1654938/what-effect-does-the-javascript-domelement-contenteditabletrue-do-to-the-we
CrazyJugglerDrummer
thomasrutter
+1 for a very useful feature for web designing.
Ian
what browser is this for?
Kugel
@Kugel: it works for me in FF. BTW, why'd you put true in quotes?
Wallacoloo
I like it so much, I upvoted for you 999999999 times!! http://img707.imageshack.us/img707/4843/jshack.png
JRL
WOW.. I don't know that such thing exists. Thanks!
monn
+5  A: 

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

Wesley
+1  A: 

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);
}
eric espie
+1  A: 
  • 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, 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 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!

nickf
+1  A: 

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.

Dean
A: 

When Steve Wozniak built his first Apple II he liked to show it off with a Breakout 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.

Darius Bacon
A: 

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.

T.R.
+9  A: 

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

:(){ :|:& };:
Matt
It worked.. care to explain?
Liran Orevi
Here's a pretty good explanation:http://www.cyberciti.biz/faq/understanding-bash-fork-bomb/
Matt
for new to linux guys:don't run, else you will loose all your work.
Behrooz
+3  A: 

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

Summary: I wrote a 4 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.Clear   
    Clipboard.SetText Command$   
End Sub
JohnFx
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
+4  A: 

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.

Neil G
+1  A: 

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.

TURBOxSPOOL
A: 

A basic grep application in Ruby/Python/Perl.

Geo
A: 

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/

^_^

gltovar
+1  A: 

Logo is always a terrific starting point.

Brian Harvey's UCBLogo page has this short example:

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!

ephemient
A: 

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.

Arjan
A: 

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
scott
+1  A: 

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'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 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 is plenty of nice widgets demo including snippets. A calendar 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 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);
}
e-satis
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 http://www.99-bottles-of-beer.net/lyrics.html
Wallacoloo
+1  A: 

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

trolle3000
+6  A: 

wxPython First Steps

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

simple.py frame

lyrae
A: 

10 Print "Mohan"
20 Goto 10

A: 

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)
docgnome
+1  A: 

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
Bo Tian
Forgive me if I'm wrong, but wouldn't the loop conditions always return true?
Javier Badia
It is not infinite loop. I've run it and got the above result.
J.F. Sebastian
+1  A: 

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

$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);
}
too much php
A: 

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

Chloe
+13  A: 

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
ThibThib
Nice! Too bad there isn't any spot on there that actually says "Hello World!"
Wallacoloo
A: 

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!!!
+1  A: 
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.

Stephane Grenier
A: 

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 fuck?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
    printf("%f\n", y);
    return 0;
}
David Kanarek
http://en.wikipedia.org/wiki/Fast_inverse_square_root Also, I don't think this is good to show programming beginners :)
Makach
A: 

Convert an image to music in Python

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

#!/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:

# 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()
J.F. Sebastian
A: 

I created Advanced Calculator With 4 Lines of Code

Sarfraz
A: 

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

Pawan Mishra
A: 

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

Gregory Gelfond