Wednesday, January 12, 2011

Basic Programming 101: Session I

Let's write two programs: sum two numbers and hello, world.

Summing two numbers in BASIC

10 input a
20 input b
30 print a+b

Run that and the computer asks for two numbers and prints their sum. However, it's not very informative because the "? " doesn't really tell you what the computer wants. Try adding the following line then run it:

5 print "Give me a number";

That's better, but it still isn't quite there. Try one more change:

20 input "Give me another number? ", b
30 print "The sum of your two numbers is " (a+b)

That's it. Two questions with explicit instructions and an informative answer. Here's the whole program (list):

5 print "Give me a number";
10 input a
20 input "Give me another number? ",b
30 print "The sum of your two numbers is "(a+b)

Save that and clear out the old program (del 1-), so we can write hello world.

Hello, world!

Run the following:

10 input "What is your name? ", name$
20 print "Hello, " name$

Notice how this program, like the other one, displays everything on the console.

Now, add these lines and run again:

30 greeting$ = "Hello, " + name$
50 graphics window 100,100,400,200
60 graphics 0
70 graphics moveto 10,100
80 graphics drawtext greeting$

It took a little more work, but this displays your text in a graphics window.

Finally, for the coup de grace, add this line and run it.

90 say greeting$

Remember to save your work!

No comments:

Post a Comment