Pages

Showing posts with label variables. Show all posts
Showing posts with label variables. Show all posts

4. Testing the IDE and a Fundamental Set of Instructions - Part 1

Hello World

In the last post we installed the FbEdit IDE, set up various paths, and installed help documentation. Let's now test our IDE installation to ensure it is working correctly.  Starting FbEdit should give you a screen that looks like the following.  The colors on your instance of FbEdit are dependent on the color theme you have in place  (Options - Code Editor).

FbEdit Screen on start up

Select File then New Code File; Ctrl+N will do the same.  The large grey area changes color.  I have stayed with the default color theme so in my case it becomes a pale yellow.  This is where we will enter our code. A tab opens above this area with the filename (Untitled).bas.  The .bas is the extension FreeBASIC uses for its code files.  We haven't given our file a name yet, hence the Untitled. Click into the code area and you will see the cursor blinking and ready to take your input next to a yellow block.


Enter the following, each on a line below on a separate line of the code window (you can cut and paste if you like):
Print "Hello World"
Sleep
End

The first line prints the the text within the quotation marks, Hello World, to the windows console.
Sleep pauses the program and waits for input from the user; pressing any key will allow the program to continue.  Without this line you would see a quick flash as the console opens, prints Hello World, then immediately shuts.  The End word shuts the program cleanly - it is not strictly required here.

The colors of the text you entered change depending on the theme you have applied to FbEdit.  In the default theme you have reddy-brown for commands, red for double quotes, and blue for text.  You will get to recognise most of these as you program further.


Since this is your first time you have saved the file pressing Ctrl+S will bring up the Save As dialog box.  Pressing Ctrl+S after an initial save will save normally, rather than Save As, without asking for a name.  Change the filename to say HelloWorld.bas  The tab above your code now changes to reflect the name change.

In the Make menu we find Compile, Run, and Go options.  These options are also located on the toolbar:
Compile - converts our code into computer readable form.
Run - will run the resulting executable.
Go - does a compile followed by a run.  As this is what we want to do, press the Go option.
Output of Go option
The Go option starts the compiler with your file as its argument. You can see the exact command it uses in the bottom left rectangle of the image above. (The red text has been added to highlight various sections and will not come up when you select Go.)  The command it fires off is ..\FB\fbc -s console "HelloWorld.bas".  If the compiler is successful it responds with 'Make done', meaning that it has created an executable program.  The Go then runs the newly created program. A windows console opens and presents us with our Hello World message. Well done!  To recap: the IDE has been given some FreeBASIC code that has then been compiled into an executable and has run successfully. Remember, you can right click on the console title frame and choose Properties to change the size of the text if the Hello World text is too small.  Pressing any key when the focus is on the windows console will end the program and close the window.

If you exit FbEdit and go to the Projects directory you will find two files:
  1. HelloWorld.bas - containing the code you entered.  If you open this with notepad it will contain only the text you typed.
  2. HelloWorld.exe - this is the compiled code.  If you run this you will get the console program you saw when you chose the Go option.

Change to FbEdit Path Option

A quirk of FbEdit means that using ..\fb as the path option to the compiler causes FbEdit to expect the code files in the root of the Projects folder.  FbEdit will not compile code files in subdirectories of the Projects folder.  To get around this issue change the FbEdit Options - Path Options - Compiler Path to show the full path to the compiler.  In my case that is C:\Apps\Basic\FB .

Fundamental Set of Instructions for a Useful Programming

Since we now have a working compiler and IDE we can get stuck into coding.  Before we do that though, let's consider the minimum amount of a FreeBASIC we need to learn to write useful programs. I am thinking along the lines of the 80:20 rule here. I want to show you the 20 percent of FreeBASIC that you will use 80 percent of the time. This is bit not an exact science, and the selection of instructions is based on my opinion only, but hopefully it helps get to some useful programming as quickly as possible.

One caveat before we begin.  We will start off with Windows Console programming initially; the sort of program we wrote above in HelloWorld.bas.  We will work on Windows programs, with buttons and scroll bars in later lessons. It is important to get a good understanding of the basics.

The list below shows what we will be programming. It is written in English, in a form of programming shorthand that will make programming in FreeBASIC easier. Note that point 5 has an odd word getAge(date) and that word is repeated in the next section preceded by the word function.  From the name you should be able to guess that it has something to do with getting your age.  I will go through all of the following line by line to give you a clear understanding of how all of this works.

Fundamental
  1. ask “what is your name?”
  2. say “hello” name
  3. ask “when were you born” name “?”
  4. age is getAge(date)
  5. say “Hi name, at the end of 2017 you will be “ age “ years old”
  6. write name, dob, age to text file
  7. clear screen
  8. reset name, dob, age
  9. read name, dob, age from text file
  10. print name “was born on” dob “and so is “ age “ years old”
function getAge (date)
  1. calculate age from date
  2. return age

If you have programmed in any other language you will notice that Fundamental covers these programming ideas:
  • request input from screen
  • string variables
  • integer variables
  • function with parameter passing
  • simple arithmetic
  • print to file
  • read from file.

Coding Fundamental

First off go to the Projects directory and create a sub-directory called Fundamental. You may wish to delete the HelloWorld files, we won't need them, or else you can create another sub-directory called HelloWorld and move them there.


Comments

Start FbEdit and create a New Code File (Ctrl+N). Enter the following (cut and paste is fine):

'======================
'Fundamental in FreeBasic
'your name
'today's date
'======================
Replace your name with your actual name and today's date with, you guessed it, today's date.  Look carefully and you will see that each line starts with a single quote.  The FreeBASIC compiler ignores anything on a line that follows a single quote.  In the example above, the === marks along with the text, is totally ignored.  Anything following the single quote is considered a comment and is used to provide an explanation of the code that follows.  In this example, the comments give the name of the program, the language, the author, and the date the program was written. In complex programs comments are used to explain the logic to anyone who may read the program some time later.  If you visit the FreeBASIC forum you will often find posts with snippets of code. Some contain header comments, like the one here.  Others contain additional comments.  You will find a style that suits you.

If you want comments to span several lines you can use /' text '/  where anything between  the /' and '/ is considered a comment.  The example above is equivalent to:
/'
======================
Fundamental in FreeBASIC
your name
today's date
======================
'/
The benefit of using this format is that you can comment blocks of code very easily. For completeness, lines starting with Rem (short for Remark) behave the same as single quotes, however Rem must be the first command on the line. The single quote can appear anywhere on a line.

Before we get any further, press Ctrl+S and save your file in the Fundamental sub-directory. Call the file Fundamental.bas. If you try and compile and run the file you will see the flash of the console and nothing more. Our program doesn't really do anything at this stage; it is only a few lines of comments.

Input and Variables
Let's move onto the first task:
  1. ask “what is your name?”
To do this we need to type:
Input "What is your your name? "
Sleep

You will notice that once you type Input  (FreeBASIC is not case sensitive so you could type input or INPUT, or any combination of upper and lower case,to FreeBASIC it's all considered the same), the editor brings up context sensitive help.  Text within double quotes is called a String - it is a string of characters.  The compiler treats strings as special text that it does not try to interpret.  Leave a space after the question mark and before the closing double quote.

If you try and compile this code you will get an error:
Fundamental.bas(9) error 16: Expected ',' in 'Input "What is your name? "'
Build error(s)

This is basically telling us that the compiler is not happy with line 9, the line starting with Input.  It expects a ','.  Unlike print that displays text, input tells the compiler to display text, get an input from the user, and store that input in to a special location.  That location is known as a variable and is a container that can hold some data.  Our Input line doesn't specify a variable so let's create one.  To create a variable type the following below the comment section and above our Input line.  

Dim as string yourName = ""

Change the input line to say:
Input "What is your name? ", yourName

You can leave blank lines between lines of code to make the program easier to read.  Blank lines are removed from the compiled code so don't affect the way the program runs.  They are used to break up the code into logical units that make reading easier.  My screen looks like this:
Fundamental.bas part 1
The process of creating variables starts with the Dim statement.   This command reserves a memory location to hold our data.  The as is followed by the data type.  In this case we want to hold a string of characters.  Later you will use different data types for holding data such as integers and floating point numbers.

The next word in the line, yourName, is the name we have given the variable for use within our program.  You can use any combination of characters, upper and lowercase (FreeBASIC is not case sensitive, remember?), digits, and the underscore character. Be sure to use names that will make sense when you come back to your code at a later time. Notice that I have used lower case throughout, with the exception of the N of name.  This format is called camel case, and is a format convention used widely for variable names. In camel case the first word is all lower case.  All subsequent words start with a capital letter.  All words are joined with no spaces in between.

The next part of the line, = "", preloads (or initialises) the variable with an empty string.  This is not strictly required but this convention is used in other languages and is used to ensure we start with known contents in our variables.  You can use this same idea to initialise the variable to something else, if necessary.  For instance you could have typed:

Dim as string yourName = "Nobody"

This will create a variable called yourName and put Nobody into it.

In FreeBASIC you could put a comma after the second double quote and create name another variable.  Adding more variables on the same line saves space but can get messy and difficult to read if carried too far.  I avoid this practice because I find it easier to manage variables when they are on their own lines.

If you compile and run the program now you should get no errors.  The console will open and you will be prompted for your name.  Enter your name and press enter. This will store whatever you entered into the yourName variable.  If yourName had contained another string then that string would be replaced with your input.  Press enter a second time to quit through Sleep.

As a final exercise for this post, and line 2 of the pseudo code above, enter the following line after the Input line:
Print "Hello ", yourName

If you now compile and run the program the console will ask you for your name then greet you personally. How easy was that! Next post we will continue expanding on Fundamental by looking at some calculations, functions, and work with text files.
Please feel free to leave a comment and see you in the next post.

5. A Fundamental Set of Instructions Part 2

A Fundamental Set of Instructions Part 2

Recap

In the previous post we started on a short program that promised to show you a set of instructions that you would use in most of your own programs.  The program, called Fundamental, comprises of the following steps:

Fundamental
  1. ask “what is your name?”
  2. say “hello” name
  3. ask “when were you born” name “?”
  4. age is getAge(date)
  5. say “Hi name, at the end of 2017 you will be “ age “ years old”
  6. write name, dob, age to text file
  7. clear screen
  8. reset name, dob, age
  9. read name, dob, age from text file
  10. print name “was born on” dob “and so is “ age “ years old”
function getAge (date)
  1. calculate age from date
  2. return age
In the previous post we covered lines 1 and 2 and we saw how to create a string variable and use that variable to hold some data.

Integer Variable

Line 3 asks for your birth year.  We could go for the full birth date but that is more complicated than I want to tackle in this post, so let's stick to the year only; we'll call the variable yourDob for your date of birth. Add the following line after the first Dim line:

Dim as integer yourDob = 0

As we saw in the previous post, the Dim as prepares a location for our variable.  The integer tells the Dim as that the variable will contain integers (whole numbers).  And, as before, we initialize the variable with a 0 this time.  We don't put the 0 in double quotes as we want the compiler to see it as a number not a character. To be clear 0 and "0" are viewed completely differently, the first is the number zero, the second is the character 0.

String Concatenation

Enter the following line on a new line below the  previous Print line:

Print "What year were you born, " + yourName ;

This new line shows how we add two strings together.  The + symbol concatenates the strings "What year were you born, " with yourName.  You can join multiple strings together on the one line and even assign them to a new string variable.  For instance, you could write the following:

Dim as string a = "Hello "
Dim as string b=  "World "
Dim as string c= ""

c = a + b
print c

to give the familiar Hello World message. The semicolon after yourName tells the compiler not to advance the cursor to the next line but to continue from this point.  You will get the idea when you run the code below.

We have asked for a year of birth but not actually requested any input so let's add the following line after the second print:
Input ; yourDob

The semicolon after the input in this line adds a "?" character and  waits for your input.  So the two new lines, apart from declaring our variable yourDob with the Dim as statement, should look like:

Print "What year were you born, " + yourName ;
Input ; yourDob

You can compile your code now and see what it does.  Have a play with the semicolons to see what effect they have on line breaks and question marks.

Fundamental so far

Function

Often when programming we need to write a block of code that performs a discrete action.  When the block of code simply performs an action and does not return any data that block is known as a procedure.  When the action returns a value then the block of code is known as a function.

To illustrate this concept let's look at our program.  We now have yourDob and want to know how old you will be at the end of 2017.  (I don't know how you feel about it but 2016 has flown past!) This is a simple calculation where you obviously subtract yourDob from 2017.  Let's write it as a function so we get an understanding of how functions work.

Below Sleep add the word End to signify the end of the program.  Now on a new line below that add the following lines:

Function getAge (age as Integer) as Integer
     Dim as integer calcAge = 0
     
     calcAge = 2017 - age

     return calcAge
End Function

Let's work our way through this bit of code.  The word Function and tells the compiler that we are writing a function, (who would have guessed!). The next word getAge is the name of the function.  Functions, as explained earlier, perform a discrete action so often have verbs as names. The brackets surround a new integer variable called age.  When we invoke, also known as calling, the function we will be passing the variable yourDob.  Function getAge will then give age the value in yourDob so it needs to be of the same variable type.  Finally we have, as Integer; this refers to the function getAge and the value it will send back.  Since Functions return values, the compiler needs to know what data type will be returned.

The Dim line should now make sense to you; we are creating an integer variable called calcAge and setting it to 0.  The next line is our calculation, again pretty self explanatory.  The return calcAge line tells the compiler that we need to send back the value of calcAge to the calling line. Note that the data type for calcAge is the same as the that for Function getAge as we have instructed. The last line simply ends the function.


The final line we need to add to our program is one that declares the function to the compiler.  This is placed at the top of the program and above the Dim statements.  It needs to appear before you use the function.  The line is as follows:
Declare Function getAge (age as Integer) as Integer

Fundamental including function


The program compiles and runs normally but you may be surprised to find that the code for Function getAge does not appear to do anything.  That is because we have not called or invoked the function.  To call the function you need to add the following line after yourDob input line:

Print
Print "Hi " + yourName + ",  at the end of 2017 you will be "_
+ Str(getAge(yourDob))+ " years old."

There are a couple of concepts in this line that we need to focus on.  The first Print statement gives us a line break after the previous input so that the input does not run into the text we want to display next.  The start of the next line should be well understood until we get to the  underscore character.  This is used by FreeBASIC to continue long lines onto the next line.  It acts as a continuation command.  The next statement needs you to pay attention - Str(getAge(yourDob)).  Inside the first set of brackets you will see getAge(yourDob).  A function is called by naming it and giving it any parameters it needs.  In this case we pass yourDob to the getAge() function by putting it in the second set of brackets.  The function getAge will then do its arithmetic using yourDob and return calcAge.  If you had entered 1980 for yourDob then the result returned would be 37.  The number 37 is a number and cannot be added to a string. We need to convert the 37 to a string for the concatenation to be work, and that is where the FreeBASIC built in function Str() comes in.  Given a number it returns the number as a string of characters.  We can then use it to complete the sentence we wanted to create.  Go ahead and compile and run the program.

Fundamental program at end of  Post
This is a simple program so we could have written the code within getAge() in line with the rest of our code.  Having a function gives us many benefits, among them:

  1. the main part of the program is shorter and easier to read.
  2. we can reuse the function in any other program that needs to use that calculation.  Simply cut and paste the function.  You need to remember to declare it prior to using it.
  3. finding errors becomes easier.  If the age we get back is incorrect we know we need to check the logic in the function.
  4. programming becomes easier and can be shared within a team of programmers through the use of function and procedure stubs.  Essentially a stub is a simply function that does not contain any logic but returns a value as if it did. It allows us to write our main program, call functions, but not have to worry about the details of how the function works. We'll cover this aspect in a future post.


In this post we continued working on Fundamental.bas.  We know how to ask for input and display text.  We know how to concatenate strings and we know how to convert a number into a string so it can be part of a larger string. We know how to write a function and have it return the result of a calculation.  Next post we will look at reading and writing text files.  

Between posts play around with some of the commands you have been shown.  If you cause errors, find what you changed and understand why the error occurred.  Try writing other programs based on the commands shown here. This sort of experimentation will help you understand what is going on much better than simply reading the text. You cannot learn to play the guitar without practice no matter how many books you read about guitars.
Please feel free to leave a comment and see you in the next post.