Friday, May 20, 2011

Beginning Programming with Just BASIC -- Tutorial 4: Loops



Tutorial 4: For Loops and While Loops

Maybe you want to run a piece of code through several times. Instead of using GOTO, here's a snazzy way to accomplish this. There are two types of loops, the FOR loop and the WHILE loop. They are similar but are treated differently.

The FOR loop will run through the code a predetermined number of times, keeping track of how many times it has run through the loop. Here is how you would set up a FOR loop:

for i = 1 to n
    some code
next

For example,

for i = 1 to 1000
    print i
next

This code prints out the numbers 1 through 1000.

You can also have the loop count by an interval other than 1 (the default):

for i = 2 to 1000, step 2
    print i
next

This code prints out all the even numbers from 2 to 1000.

The WHILE loop is treated differently, but it can still function the same way. A WHILE loop will continue to run the code until a certain condition is met. For instance:

x = 1
while x < 1000
     x = 2*x
     print x
wend

As long as the value of x is less than 1000 x will continue to be doubled and print to the screen.

And that is all. There is no secret aspect of loops lurking in the shadows waiting to spring out and surprise you with complexity. What you see is all there is.

That said, let's write a program using loops:

Ever wonder how a computer calculates the square root of a number? Well, read further and you shall be enlightened.

You start with a guess, G, and you loop through this overwrite statement

G = (G + x/G)/2

until G is approximately equal to the square root of x.

Take note, however, that if you actually were going to take the square root of something in everyday programming, you'd use a built in function for that. Or just raise the number to the 1/2 power.

i = 0
print "Square root of what?"
input x
print "To + or - what precision? (%)"
input precision
precision = precision/100
lowerx = (1 - precision)*x
upperx = (1 + precision)*x
print "Guess?"
input G
while G^2 < lowerx and G^2 > upperx
    G = (G + x/G)/2
    i = i + 1
wend
print "The square root of x is "; G; " in "; i; " iterations."
end

This type of calculation is called numerical methods, and the subject is so vast that it has its own field of study.

goto [nextTutorial]

Beginning Programming with Just BASIC -- Tutorial 3: IF Constructs



Tutorial 3: IF Constructs, Boolean Operators and Branch Labels

Sometimes you only want to run a portion of the code if a certain condition is met. This is another basic part of programming, and can be accomplished using IF-constructs. The most basic IF-statement looks like this:

if condition then
    some code
end if

Also, if you have some other code you wish to run, you can issue the ELSE command. As an example,

print "What is x?"
input x
if x = 1 then
    print "x is 1!"
else
    print "x is not 1!"
end if

This is a rather stupid example, because you can always just print the variable. But it's gets the point across, and that's all that matters.

One other thing about if statements that I forgot to mention in the video: suppose you have more than one condition under consideration. If you only care if one or the other condition is true, then you can use the OR Boolean Operator:

if condition1 or condition2 then ...

However, if you want both conditions to be true to run the code, you can use the AND Boolean Operator:

if condition1 and condition2 then ...

I would also like to take the time to show you how to use the GOTO statement, and issue a word of caution regarding this command. The GOTO statement allows you to jump around to different parts of your program called branches. A branch is defined by a branch label, which goes inside square brackets []. This is a very useful thing in programming if you wish to run certain parts of the code more than once.

But watch out! Don't fall snare to the trap of Spaghetti Programming, a problem where beginning programmers overuse the GOTO statement and wrap their codes and their minds in humongous knots and get exceedingly confused. This doesn't tend to be a problem with [branchLabels] so much, but in older versions of BASIC, every line was numbered and you could GOTO any point in your program. Things got a little hairy. Well, there is a way to combat Spaghetti Programming, and it is called for- and while-loops. But I'll save that for a later tutorial.

Anyway, here is an example program that uses everything we have learned so far:

[Start]
    print "Guess a number from 1 to 100!"
    print "You have 7 guesses."
    x = int(100*rnd(1)) + 1
    guesses = 7
[Loop]
    print "Guess number "; 8 - guesses; ":"
    input guess
    if guess = x then goto [youWin]
    if guess < x then print "Too low."
    if guess > x then print "Too high."
    guesses = guesses - 1
    if guesses = 0 then goto [youLose]
    goto [Loop]

[youWin]
    print "You win!"
    goto [playAgain]
[youLose]
    print "You lose!"
    goto [playAgain]
[playAgain]
    print "Play again? (y or n)"
    input answer$
    if answer$ = "y" then goto [Start]
    end

This program is a game that has the user try to guess a randomly generated number from one to one hundred. They win if they can guess it within seven tries, and they lose if they use up all seven guesses. The computer will notify them whether their guess is too high or too low to help them zero in on the correct guess.

A couple of notes about this code:
  1. x is assigned randomly using a few built in functions. You can find a list of all the built in functions in the help files. The rnd(1) function generates a random decimal from 0 to 1. It is then multiplied by 100 because in the game, x can go all the way up to 100. To make it an integer instead of a decimal, we use the int() function to turn it into an integer. Since the int() function rounds down, I added 1 to x so that its range is 1 to 100. You just have to think about it and scratch your head for awhile, and then you'll figure it out.
  2. If you only have one line of code to run if a condition is true, you can have a one-line if-statement. Simply put the code to run after the word THEN.

Thursday, May 19, 2011

Beginning Programming with Just BASIC -- Tutorial 2: Variables



Tutorial 2: Variables and User Input

Now we're going to use variables, which are ubiquitous in programming. Variables are pretty much the meat and potatoes of programming.

A variable is a word or character that holds a value. Just like in algebra, which you may have had in high school, where x = 3, etc. In this case, x is a variable, because it is used in place of the actual value in represents.

In JB there are two types of variables: string variables and number variables. String variables hold text and letters and characters and such. Here is how you define a string variable:

myName$ = "Daniel"

The name of the variable can be anything, but since it is a string variable, it must end in the $-sign so that JB knows it's a string. Everything in the quotation marks following gets stored in the variable. Thus, if your program says

myName$ = "Daniel"
print "Hello "; myName$

The output will be

Hello Daniel.

Number variables hold regular number values, like 6 and 12 and 3.141592654 and -44000000. Defining a number variable is easy, you just say

x = 0.00012
print x

You can also do fancy operations on number variables:

x = 1
print x
x = x + 1 'Read "new x = previous x + 1"
print x
x = 2*x 'Make x twice its previous value
print x
x = x^2 'Square x and put it back in x

(Note, when you put text after a single quotation mark, the compiler skips over it. That's a good way to put comments in your code, or to take out a piece of code that you don't want to actually delete). This has output like this:

1
2
4
16

Now, what good is your program if the user can't control anything? You need to be able to get input from the user. That's really what programming is all about. Input from user, manipulation of input, output back to user. Here's how that's done:

print "What is your name?"
input userName$
print "Hello there, "; userName$
print "Please input a number to square:"
input x
print x " squared is "
x = x^2
print x

This code has output like this:

What is your name?
?Daniel
Hello there, Daniel
Please input a number to square:
?2
2 squared is
4

You now know how to make a basic functional program!

goto [nextTutorial]

Beginning Programming with Just BASIC -- Tutorial 1: Compiling and Running



Tutorial 1: Compiling and Running Your First Program

So you want to try programming.

In these tutorials I assume you are a complete beginner, although you are able to use all the basic functions of your computer already.

I also am assuming you are using Windows. (Sorry Mac-users, JB only works on Windows. Das ist schade. Not to say that the concepts of programming in these tutorials don't apply universally, though).

Introductions aside, let's get started.

The first thing you are going to need is a compiler. A compiler is a program that takes the written commands from the programmer, analyzes it and looks for stuff it doesn't understand, and then turns it into machine language (namely, 1's and 0's). In these tutorials, we will be using a language called Just BASIC, which is a variant of the original BASIC programming language of the 1970's. You can download the compiler here. This language is an excellent choice for beginners because it is
  1. Free
  2. Easy to learn
  3. Offers a wide variety of functions including basic GUI's, graphics commands, sprite programming, and sound effects.
So as you can see, it's great for beginners and yet is complex enough to continue using it even as you get more advanced.

Once you've downloaded the compiler, open it up. It's time to write our first program. Most peoples first programs print the words "Hello, World" on the screen. But if you want your program to be unique, have it write something more creative than that. In the video I use the more informal "Howdy." No matter what you have it say, here is how you have it say it:

print "Howdy, World!"
end

What this does is it tells the computer to display the text "Howdy, World!" in the main window, and then it ends the program. Easy, right?

You're right, it is easy. But in the future, things won't be so easy, so enjoy how easy it is while it lasts.

Congratulations! You've just written your first program. You are now well on your way to becoming an excellent computer coder (if you keep reading, that is).

goto [nextTutorial]

Wednesday, May 18, 2011

Take 2

I originally started this blog on the 10th of May, and then Blogger had that issue on the 11th and my blog disappeared. Eh, not to worry. I'll just re-post what I had written then:

This blog is for exploring the humongous world of computer programming, and other computerish topics. I will likely post tutorials of beginner, intermediate, advanced levels, and talk about interesting anecdotes and stories that I experience in my career as a computer programmer. (I use the word "career" lightly. I'm actually an aerospace engineer).

As of this writing, I am familiar with five programming languages: FORTRAN, JustBASIC, C++, Python, and MatLab. Of these I have been programming in BASIC the longest, and have made many interesting programs on it. I also consider myself an "expert" in FORTRAN, having used it profusely as an aerospace engineer. As for C++ and Python, I'm at the beginner- to intermediate-level, so don't expect anything too highfalutin in that department just yet.

That said, what am I going to post first? Well, I figured I'd post my tutorials on Beginning Programming with Just BASIC. First things first. Learn how to program a computer. I've already made several good video tutorials on my YouTube Channel that would do wonders on this blog.

Thanks for stopping by, and I hope you enjoy your stay!