(<--Previous) Back to Index (Next-->)

FB n00b: Tutorial 2

Note: This tutorial is for absolute beginners. If you aren't an absolute beginner and you dislike the tutorial, that's too bad. If you are an absolute beginner and there's something you don't understand, read through the tutorial a second time. If you STILL have difficulties, e-mail me (TheMysteriousStrangerFromMars@yahoo.com) and I'll try to help you out. I do assume you at least have a decent knowledge of how to use your computer - if not, there's not much I can do for you. By the way, you'll need FreeBasic to use this tutorial - you download that at freebasic.net, so be sure to download and install it before doing this tutorial. Now start reading!

Working with variables

In the first FB n00b tutorial, we discussed precisely what programming is all about, and then I gave a very simple example of putting it all together. By now you should know the three crucial elements of any program that every program contains and the only elements any program contains, and you should know what variables are. You also know the most basic input and output commands used by FreeBasic, and how to do calculations with a variable. You also know the simplest way to compile something (and trust me, it is the simplest - there are many other ways to compile, though they all ultimately work the same way). So you must be ready to move into the next part of the tutorial. If not, read tutorial 1 again and do the examples.

In this tutorial we'll be talking more about variables, but very specifically, what we do with these variables. In particular, I mentioned last time how you might want to do operations based on a variable, rather than changing the variable itself. For example, I might ask the user if they want to multiply or divide. The user will type something in and if they type "m" then they want to multiply but if they type "d" then they want to divide. SO here I'm writing a program that can do two different things, but it only does one OR the other. This is called conditional code - it's a block of code that only runs under certain conditions. In this case, we have two blocks of code, one to multiply and one to divide. The multiply block only runs if the user entered "m" and the divide block only runs if the user entered "d." These are the two conditions, and they're very important in our example program.

The most basic conditional is If. That's right, "If." Is this hard? Of course not! This is unbelievably easy! But before I can show you the If conditional, I first have to show you the String variable type. You see, the letters "d" and "m" are not numbers. As I said earlier, they are stored internally as numbers but thanks to the magic of the HLL FreeBasic, we can pretend they aren't numbers. How do we do this? We need to create a variable of the type "String." Now strings are very flexible in FreeBasic. In fact, a string can have one character or many. But right now we're only going to have once character, and there's a special way to make a string that only has one character:

  Dim mychar As String * 1
It's that "* 1" thing. If you leave that out, the string can change size. It can have one character or twenty characters. But if you put the "* 1" it can only have one character. So that's the first thing we define. Now of course you'll want the num1, num2, and result from the last tutorial, since we're doing the same thing only more. So you need those - since we're dividing, Dim them As Single and not As Integer. Why? Because some divisions won't produce integers. For example, 3/2 is 1.5. FreeBasic won't stop you from dividing and putting the result in an integer - but if you do it, the result will be 2, not 1.5. That's why it's best to use a Single in this case.

After declaring the variables, announce to the user that they have two choices - either 'm' or 'd'. This is done, as usual, by the print statement. Then use Input to get the character.

  Print "Enter an 'm' to multiply two numbers or 'd' to divide."
  Input mychar
Then proceed to ask the user to enter the two numbers, as we did in the program we wrote in the first tutorial. But now, instead of multiplying the two numbers together, we use If. Now If is a very useful keyword in FreeBasic, and it actually has several syntaxes (or ways to use). The syntax we use here is the simplest one; we'll actually make two If blocks. Of course, if the user entered any character other than "m" or "d" then the result will be zero, since we don't change result (and all variables start out at zero unless you change them). So here's our code:
  If mychar = "m" Then
    result = num1 * num2
  End If
  If mychar = "d" Then
    result = num1 / num2
  End If
Wasn't that easy? Now you see the If starts with "If" then there's the condition: if the condition is true, then we do whatever is inside the If block. If the condition is not true then we don't do it. After the condition is "Then." That's just to show where the condition stops and where starts the code that is only done if the condition is true. "End If" ends the conditional block, otherwise the entire program would have to fall under the condition. After we do that, we display the result like we did yesterday, then Sleep so the window doesn't disappear right away. The final program is this:
  Dim mychar As String * 1
  Dim As Single num1, num2, result

  Print "Enter an 'm' to multiply two numbers or 'd' to divide."
  Input mychar

  Print "Type two numbers, one after the other.  Press Enter after each one."
  Input num1
  Input num2

  If mychar = "m" Then
    result = num1 * num2
  End If
  If mychar = "d" Then
    result = num1 / num2
  End If

  Print result

  Sleep
Now as I said, if you enter something other than "m" or "d" then result will just be 0. We don't want that, do we? Let's add something right before we ask for the two numbers that checks this. If the character entered is neither "m" nor "d" then we'll quit the program right away with an error message (once again we'll Sleep so it doesn't just disappear). Now if the character for checking if two things are equal is "=" then shouldn't the character for checking if they aren't equal be the non-equal sign? Well yes, but unfortunately most people don't have that symbol on their keyboard. So instead we use "<>" to check. What this means is, if the first thing is greater than or less than the other, then the condition is true. After all, if one number is greater than or less than another, the two numbers can't be equal, right? Incidentally, if you were comparing numbers you could also use ">" or "<" to check if one number is greater than the other, or smaller than the other. You can also use ">=" and "<=" to check if it's greater than or equal, or less than or equal. Of course this doesn't make sense in this case, since we're working with strings, but it is a useful thing to remember. Here's the code we need - put this right after the "Input mychar" line:
  If mychar <> "m" And mychar <> "d" Then
    Print "You didn't enter an 'm' or a 'd'."
    Sleep
    End
  End If
Ah - this has two conditions in the same If block! So we check two things at once. If mychar is neither "m" nor "d" then we know there's a problem. If we can use the word "And" to check this, can we also use the word "Or" to check things? Of course! You can even check two different variables in one If block, or even more than that! But right now, that's the code we need, so type it in and run it again. If you type something other than "m" or "d" then you'll see the error message, and the program will quit.

There's a couple other ways to use If. I won't give examples for these, but I'll show how they're used and give you some programs to write using these variants. The first one is this one:

  If condition Then
    'This block happens if the condition is true
  Else
    'This block happens if the condition is false
  End If
This lets you check if something is NOT true, as well as if it is. Of course, there's another way to do that, if you only need to check if something is not true (and not if it is):
  If Not condition Then
    'This block happens if the condition is false
  End If
Then there's the more complicated form:
  If condition Then
    'This block happens if the condition is true
  ElseIf condition2 Then
    'This block happens if the first condition is false but the second one is true
  End If
In fact, you can put more than one ElseIf and you can even put another Else in there:
  If condition Then
    'This block happens if the condition is true
  ElseIf condition2 Then
    'This happens if the first condition is false but the second is true
  ElseIf condition3 Then
    'And this happens if the first two conditions are false but the third is true
  Else
    'This happens if none of the conditions are true.
  End If
You can use this to check as many different conditions as you want, all in the same If block. However, there is another conditional construct that is shorthand for this and allows you to check a bunch of different possibilities all on the same variable. The one difference is that while If...Else If allows you to check different variables, the other way only lets you check different possible values for the same variable. If that's what you need, you can use Select Case. Otherwise, just use If/Else If.]
  Select Case variable
    Case value1
      'If variable = value1 then this code runs
    Case value2
      'If variable = value2 then this code runs
    Case value3
      'If variable = value3 then this code runs
    Case Else
      'If variable isn't equal to any of those values then this code runs
  End Select
(By the way, your values specified by Case may be ranges (if you use the syntax lower_val To higher_val instead of just a single number. You can also check the regular conditions like <, >, <=, >=, <>, etc by using Case Is some_operator some_value. And you can check if a number is any of a list of numbers using the syntax Case num1, num2, num3, .... For a full list of all the possible options, look at the Select Case page in the wiki manual.)

Wait a minute, this could be used to rewrite our example program!

  Dim mychar   As   String * 1
    Dim   As   Single num1, num2, result

    Print "Enter m, d, a, or s to multiply, divide, add, or subtract."
    Input mychar

    Print "Type two numbers, one after the other.  Press Enter after each one."
    Input num1
    Input num2

    Select Case mychar
      Case "m"
      result = num1 * num2
        Exit Select
      Case "d"
      result = num1 / num2
        Exit Select
      Case "a"
      result = num1 + num2
        Exit Select
      Case "s"
      result = num1 - num2
        Exit Select
      Case Else
        Print "You gave an invalid command."
        Sleep
        End
    End Select

  Print result

  Sleep
As you can see, it's very simple - we just choose something to do (Select) based on the value of the variable (Case). Remember how this works, it's quite important. By the way, you'll notice here I do Exit Select at the end of each one choice. This is optional; if you don't use it, after the code there executes it will keep checking the other possibilities to see if any of the others are also correct. In this case, only one of the options can possibly be correct, so to check the others after we find the first one is a waste of time. In some cases it's possible for more than once choice to be true, and if you want to select all the ones that are true, you would leave Exit Select out. But if you only want to select the first true one you find, then use Exit Select. And if only one of them can possibly be true anyways, you may as well use Exit Select as otherwise you're wasting time (one exception is if an option modifies the variable being checked and you want to continue so the other Case is also selected - in which case of course you wouldn't use it.

Conditionals like If and Select Case are important parts of flow control statements; in the next section, you'll explore the other side of flow control.

Closing up

So you learned conditional code today. That's more important than you think, even though we still haven't made a killer 3d game (that was a joke, you're supposed to laugh.) Conditional coding is one of the cornerstones of every program, because without it every program would do the same thing every time. Every button would do the same thing, because there would be no way to check which one you clicked. Every enemy would do the same thing, because he wouldn't be able to figure out what you're doing. This makes it crucially key that you learn to write conditional code, so your program can make decisions. So once again, if you didn't understand everything the first time around, try reading it again.

That's all for now, but tutorial 3 is coming up. In the next tutorial, you'll be learning about doing the same thing over... and over... and over. It's called looping, and it's yet another key part of programming in any language.

Today's assignment is to write a program that asks for a number and then prints out a different ice cream flavour depending on the number you choose. Write two programs, one using If and one using Select Case - make sure you include an error check in case the number is outside of the possible range of numbers you've set for ice cream flavours!

The third tutorial is here

(<--Previous) Back to Index (Next-->)