Building a program
[ << ]
With these seven basic things, and their related code, you can build pretty much every program in existence. We just add them together. For example, can you work out which bubble the following code makes? Flick back to the descriptions if you need to. Click on the bubble you think is made.
|
Algorithms and Comments
The usual starting point for a program is an "Algorithm" – an English-language (or other) description of how a program is going to work. Most programs start with the coder writing down a sequence of steps the program will go through to do a job, and this then acts as a recipe for the program to be built around. For example, an algorithm for the above might be:
# When space key pressed
# Set 'x' to 'Hello World' -- make sure you make x first somewhere
# Check this happened ok with an if
# Provided it has, print 'x' three times in a loop.
# Otherwise, print the current year.
The key thing is that an algorithm allows us to logically break down the problem and think whether it will work before we get tied up in coding. Here, for example, we note that we need to set up the 'x' variable in Scratch's variable settings before we try to write this code.
When code is typed, algorithms are quite often added to the code text files as "Comments". Comments are bits of code that
are notes for people looking at the code, rather than for the computer to try to understand. Most languages have
some way of adding notes and signalling that the computer shouldn't compile them. The above algorithm is written as Python comments, for example. The computer
wouldn't try to understand them as Python code; it would ignore them because they start with #
, which shows they are comments.
A lot of languages (like Java) use //
in the same way. With Scratch you can add comments by right-clicking on
blocks or the background area.
Writing the algorithm as comments helps to structure the code before you start building it.
The final thing to say is that code should be written and fixed a line at a time. The secret is to think how you can test each thing you do to make sure it works. This is usually as simple as putting in a few print/say instructions to test things are as you think they are. The code above could just set x up and test it by printing it once, for example. You can always delete testing code once you've checked stuff is working.
If you write one or two lines and test they work, if there is a new bug you know it is in the lines you've just written. If you write a massive amount of code and then try to run it, you'll get a lot of bugs showing. Not only is this very disheartening, but the size of new code makes it hard to find them.
So, given all what we know, we'll now look at some learning resources.