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]

1 comment: