PROGRAMMING

By David A. Cooper

Computer processors don't understand anything about programming languages: they only know how to handle raw machine code numbers. If you tell a machine to take 2 away from 3, the string of machine code instructions which reaches the processor might be something like 177, 2, 176, 3, 42, 193. The 177 is an instruction which tells the processor to store the 2 in a "register" called "c" (registers are special little bits of computer memory inside the processor used to hold the few bytes of data that are being worked on at that moment). The 176 then tells the processor to store the 3 in a register called "a". The 42 tells the processor to subtract, and the 193 tells it to work with the values stored in registers "a" and "c" and to put the answer in "a". A further instruction such as 162, 0, 128, 11, 0 would send the answer out into the machine's memory at the address 0 11 128 0 (which is actually a byte of screen memory, so this could make a symbol appear in the top left corner of the screen). I write almost all my programs directly in machine code, but most people use programming languages instead, so their programs need to be converted into machine code before they will run (or else they have to be interpreted by another program which itself runs in machine code). There are advantages and disadvantages to both methods, but programs written directly in machine code are much more compact and can usually be designed to be faster running, though you need to keep up with all the developments in processor design to ensure that your code will actually run as fast as you intend.
indentThe recent innovation of indexing machine code has made machine code programming relatively easy, but in the past it was a very different story. The early programmers found machine code too hard to handle: every time they modified their programs it would cause chunks of program code to shift into new memory locations, and that meant that countless addresses in the code had to be changed manually to point at the new locations of the subroutines or variables which they were meant to link up with. They found a way round this problem by creating a slightly easier programming method called assembler, a system of programming which allowed them to write instructions using letters instead of numbers and names instead of numerical memory addresses. The six numbers of machine code we saw a moment ago can now be generated from the following: ldc 2; lda 3; sub a,c (you can see the 2, the 3 and the "sub" which means "subtract", and once you know that "ld" means "load", you should be able to work out the rest). These assembly instructions would then be converted by the assembler program into the machine code numbers 177, 2, 176, 3, 42, 193, and any names of variables or subroutines in the code would be converted into numerical addresses: this meant that programmers no longer needed to learn anything about any of the machine code numbers, and they didn't need to worry about where any of their code actually sat in the machine's memory.
indentAssembler made some things easier, but it also introduced a plethora of unnecessary complexities which simply didn't exist in machine code, and the process of converting a program into machine code was so clunky in its design that it made debugging and testing new program code extremely time-consuming. The next development in programming was the programming language: this made programming appear a little more natural, and it hid from the programmers all the registers in the processor so that they didn't need to learn how to use them. The task of taking 2 away from 3 could now simply be written as n=3-2, and this would then be converted behind the scenes into a form which the processor could understand.
indentProgramming languages come in two main types: interpreters and compilers. Compilers convert program code into machine code for a specific kind of processor, and the code they produce will run directly through the processor at full speed: the entire program is converted into machine code before it is run, and if you buy such a program you will be given the compiled machine code version of it rather than the source code written by the programmer, so you won't be able to tell which programming language was used to write it. Interpreters are much more indirect and run code a great deal more slowly: the program code is never converted into machine code, but is processed instead by an interpreter program (which does run in machine code). The interpreter has to work out what to do with each line of program code as it encounters it while the code is being run, and every time it runs the same line of code it has to interpret it from scratch, running different bits of its own program code in order to handle whatever it meets in the line of code it is interpreting. Most programming languages are now compilers, but there is still room for interpreters in programming for the Internet, and the main one you will see used there is JavaScript. Although it is relatively slow running, JavaScript is now unquestionably the programming language you should learn first: being able to write interactive Web pages is an extremely useful skill, and it's easy to switch to using another programming language later on if you need to (they're all much the same - it's possible to copy and paste massive chunks of JavaScript programs into a C++ compiler where they'll work with very little modification). If you use the Opera browser, the JavaScript on that is actually very fast: four times faster than the next fastest browser, Chrome, and only 3.5 times slower than the machine code equivalent programs generated by a C++ compiler.


LEARN TO PROGRAM IN JAVASCRIPT

[This is still being written and will probably be redesigned substantially soon. It isn't really ready to go on public show, but by making it visible it'll force me to get a move on with putting it right.]

The best way to learn to program is to look at lots of little programs and to try to work out how they function. You can then make your own little modifications to those programs and see what happens when you run them (BUT MAKE SURE YOU HAVE LEARNED HOW TO READ AND WRITE HTML DOCUMENTS FIRST: click here for a quick course). The following link will take you to the first example program which introduces the idea of the variable and shows you how to do some simple arithmetic: Program 0 (in programming it is common to start naming things using numbers starting with zero rather than from one, so you should get used to the idea now).

That program wasn't particularly useful because the numbers used in it were all chosen in advance. A more useful program would let the user choose their own values by using a prompt. Program 1 allows some interaction with the user. Don't worry about understanding everything in these example programs: just read through the comments and try to get a feel for what's going on so that when you start writing your own programs you will be able to return to the programs here to check how the different instructions are meant to be used.

An alternative way it collect input is to use a form. Program 2 shows you how to collect input and give output through a form instead of using prompts and alerts. JavaScript connects to the data in a form's input box by using a document.formname.datacellname.value type construction. It also shows you how to post results into a non-input box in a form using the datacellname.innerHTML construction. You may be able to imagine how you could build an entire calculator program using these methods. Program 2a shows a third method of displaying output: it is possible to name a paragraph and to change the entire text of that paragraph using JavaScript. Program 2b is the same as 2a, but it also posts in HTML codings to change the style of the text. An alternative to .innerHTML which you may encounter in other people's programs is .innerText, but it only works with Internet Explorer and it cannot post HTML in along with text, so you should never use it in your own programs.

Program 2 could be improved by using buttons for number input, and a choice of arithmetical function could also be offered via buttons. Program 3 takes the calculator idea a stage further. It introduces the if(x==y){do something} else{do something else} construction. Note the double equals used in comparisons: it is meant to avoid confusion between comparisons and assigning values to variables, but it causes problems on the many occasions when a programmer forgets to double the equals sign. I still haven't got the hang of it and it wastes a lot of my time: daft constructions like this are the reason I hate having to use programming languages. Anyway, (x==y) looks to see if x equals y; but (x!=y) looks to see if x is not equal to y. If you are keen, you might like to try to create a fully functional calculator of your own with all the usual functions and with multiple memories (though you would do well to explore Program 11 first as it shows you how to take direct keyboard input, and that will make your calculator much easier to use).

Program 4 puts the methods used in Program 3 to a rather different purpose. There is a popular television programme which has a game involving numbers: the Countdown Numbers Game. Program 4 lets you enter six numbers which are to be multiplied, added, divided or subtracted from each other with the intention of getting an answer equal or as close as possible to a three-digit target number. It introduces the while(x==y){do something} construction and the idea of the variable array. Program 4 stops after collecting the initial seven values from you so that you can study its code without the mass of the main program confusing you. The working version is actually Program 15 - we will explore this program later on to examine how it works. This program goes through every order and combination of the six numbers and the four mathematical functions to see how many solutions there are to the problem - it takes an hour on a high-quality machine using Explorer. Firefox takes about 40 minutes to do the same job, and Google's browser Chrome can do it in under half an hour, but Opera is lightning fast, taking only seven minutes, which is remarkable given that a machine code version of exactly the same program (written in C++) takes two minutes. [If you want to try the machine code version, it's available from here as an exe file which runs under Windows without needing to be installed - you should right click on the link and look for one of the following options: "save link as"; "save target as"; or "save linked content as" (different browsers use different wording for this). It can't display colours, so the order in which you should process the displayed results is indicated by numbers attached to the +-x/ signs, in the order 0, 1, 2, 3 and 4.]
indentWhile program 15 is capable of finding all possible solutions, it certainly isn't the fastest way to reach a solution, and if you look closely at the results it produces you'll notice that there are many duplicate solutions which are merely written in different orders, so a more intelligent algorithm could slash the time taken to check for all possible solutions (and on paper I've worked out an algorithm which should enable all possible solutions to be found in under 2 seconds, though I won't know for certain until I've actually written the program code - the key to it is 60 x 40 x 24 x 12 x 4 (maximum values) rather than 720 x 1024 x 120, but I'll leave you to work out what all that means for yourself). To write a JavaScript version of the program capable of reaching a solution as quickly as possible would be an interesting challenge: you would want to program the machine to tackle the problem like a human, and this would be an excellent project to take on if you are interested in artificial intelligence. The same applies to chess: a program which thinks like a human would be far more interesting than any normal chess-playing program, and bear in mind that no machine has ever genuinely beaten the best human player of the game: Kasparov beat Deep Blue with white and drew with black, so when he was playing at his best, he was clearly better than the machine (which always played at its best). A simple home computer programmed more intelligently could probably wipe the floor with Deep Blue, though it won't get the chance: Deep Blue was deliberately destroyed after its match with Kasparov, perhaps to hide evidence of cheating.

Program 5 shows you how to access the content of string variables, isolating particular letters or words within a piece of text which has been stored in a variable. If x is a variable holding the string of characters "abcdefghijklm", then x.slice(0,1) would select the "a" and x.slice(12,13) would select "m". If the second number is left out, as in x.slice(0), then everything from the first position stated up to the end of the string is selected ("abcdefghijklm"); x.slice(10) selects "klm". This program also shows how to get the length of a string by using x.length. We can use these methods to identify specific words in a sentence and could potentially write a program to translate text from one language to another, though this would require a massive word list to be stored in an array, and it would be hard to get it to produce high-quality output due to the enormous complexity of languages. Let's have a go though anyway, just to see what might be involved:-

Program 6 translates into a simple language from the dawn of time: Translating from English to Neanderthal. This program introduces the idea of the subroutine (where one function calls another). Note that this program can only cope with English words made from one or two components. It also fails to consider the possibility that the same word might have more than one meaning. Also be aware that the translations are literal and do not produce good Neanderthal: the word order in this particular dialect of Neanderthal is quite different from English in some aspects: for example. while we would say "in a cave", they would say "cave-in", and while we would say "I went home", they would say "I went home-to". To resolve these issues and countless others would require an immense amount of extra program code, and no-one has ever managed to write a satisfactory translation program for any natural language. This situation will only change when artificial intelligence reaches the point where the meaning of the text being translated is fully understood by the machine. It is, however, well worthwhile to write programs which produce literal translations without attempting to change the word order at all: such programs are a great help to people trying to learn languages because the fastest way to make progress is to compare texts in the language you want to learn with their direct literal translations.

There are a number of systems for using JavaScript programs to control graphics in your Web pages, but I'm going to restrict myself to showing you the simplest one. If you want to do anything more fancy you will need to learn SVG or VML (Flash is more commonly used, but it uses its own programming language instead of JavaScript and it costs money to buy the software to use it). Most of the time these systems are overkill, so the basic stuff I'm going to show you here may be all you'll ever need. If you just want a static diagram then you can obviously just put a .gif or .jpg file into the page, whereas if you want a diagram with moving parts you might use an animated gif. The problem with animated .gif files is that they can take up a lot of bytes and make your Web site more expensive to run - if it has lots of visitors you may have to pay more for your pages to be uploaded to them. It may be better to make bits of your diagram from lots of tiny .jpg or .gif files and then to move them about the screen under the control of a JavaScript program. It may also be possible to make your diagrams out of letters and symbols instead: this program here uses nothing more fancy than 400 giant full stops to make a program that draws out letters!

Even so, there is an alternative way of doing very simple block graphics which bypasses all these systems and works with all browsers, so we will begin by looking at that. The trick is to create a document made up entirely out of non-breaking spaces (&nbsp;) and to manipulate their background colours to make them behave like large pixels. Program 7 shows you the kind of thing that can be done (but don't worry too much about understanding how it all works at this stage - I just want you to see what can be done). With most browsers you can use the Return key or space bar to repeat the action of clicking on a button, and holding the Return key down repeats the action over and over again without you having to press it repeatedly. One particularly important thing for you to note in Program 7 is the html code onload="function()" which you can find in the <body> tag. This triggers a function to run as soon as the Web page is loaded.

Program 8 adds a timer to the mix, enabling a block to be bounced around the arena like a ball. If you are using an old machine it may run very slowly: it is set to move the cursor a hundred times a second, but it actually struggles to do a it ten times a second on the laptop I'm using because the function doing the work takes so long to run that it can't respond to all the calls made to it from the timer. Part of the problem is that the size of the massive string containing all the blocks is huge, and it takes a lot of time to write this into the document repeatedly. I notice that Internet Explorer copes with this task massively better than Firefox. Pay careful attention to the code for the timer: window.setInterval("function()",1000) would call the function every one thousand milliseconds (which means once every second). There is an irritating problem with using the timer which I will discuss later.

Program 9 is faster than program 8 because it uses 26 big strings (one for each row of 47 blocks) instead of one huge string (containing all 26 rows and all 1222 blocks): now it only needs to update two of these big strings for each move of the ball. Firefox performs much better now, nearly keeping up with Explorer, though it does fail to catch the start of the action, so a delay should really be written into the program to hold the first move back for a second or two. This program takes advantage of the eval(variable) instruction used to run lines of program code stored in variables: this allows you to write programs which modify themselves while they are running, and that's useful because you can often avoid writing out masses of near-identical code by storing one version of it in a variable, running the variable's code with eval, and then changing the code in the variable so that it will behave differently the next time. This can not only save you from writing out lots of repetitive code, but it also keeps your Web pages much smaller. Again don't worry if you find the program too hard to understand: you can come back to it later and try again. Often it takes many visits before a program begins to make sense. Just remember for now that there is an eval instruction which allows you to run the content of strings as program code: many of your programs will benefit from using it.

Program 10 shows how powerful the evaluate instruction is: every move of the square on the screen now puts it into a different tagged zone in the document. This requires 1222 named locations in the HTML part of the document to be created: one for each square. All the bulky HTML for this is generated by using JavaScript and self-modifying code, so most of the Web page is only created when the set-up program runs. This makes it hard to see what is going on when you look at the source code (don't even try unless you're really keen), because masses of vital code appears to be missing, but it's all hidden somewhere in the program. Firefox now moves the "ball" faster than Explorer, but it jumps much more often. Explorer moves the ball at different speeds depending on how high or low it is on the screen, moving faster and jumping more often when it is at the bottom. Look at what happens when you click on a colour button and then hold down the return key, and compare what happens using different browsers: Opera is the slowest, but it does the job flawlessly. In this next example I have used block graphics to create a little game: Program 10a. You can copy my block graphics code to create simple graphics for your own Web pages: start by copying program 10 and then make changes to it to take it in the direction you need - this is exactly what I did to create a page to teach writing, and it illustrates how you can make the squares smaller and increase their number, though Internet Explorer quickly begins to struggle as you add more squares to arena, while Opera can't make the block size small enough. You can make the squares even smaller, as shown in Program 10b, but they don't display so well with Firefox, which is a shame, because it can handle a far greater number of squares than Internet Explorer.

Program 10a was able to take direct input from the keyboard. Program 11 makes it clearer how this can be done. There are two ways to read keyboard events (presses and releases of keys), and it is often best to use both of them at once, because the html onkeypress(event) instruction doesn't send through the codes for the cursor keys. To read the cursor keys you need to write a second function to handle onkeydown events, as shown in Program 11a, though in this program it doesn't filter out the cursor key values to make a sensible use of them. You should use onkeypress events to get the key inputs for letters, numbers and other symbols, but ignore the onkeydown events involving those same keys, writing a function to pick out only those events relating to the cursor keys and then getting it to carry out an appropriate action. Program 11b illustrates this by using the cursor-left key as a delete key. You could use this as an attractive way to get input from a user (much nicer than a crummy dialogue box), then that text could be processed in some way when a button is clicked, perhaps to translate it into another language. It would of course be better to use the real delete-left key (also known as the "backspace" key), but browsers usually use this as a back-page button and it's hard to override that function. I have found a way to switch this off for Internet Explorer, but it doesn't work with other browsers: Program 11c demonstrates this. If anyone can tweak the following and get it to work with Firefox, Opera, Safari, etc., please let me know: Program 11d. Note that m and n lose their codes rather than having them swapped round. Interestingly, this happens in Program 11c for Opera as well.
indentThe line in all the above programs which needs the most explanation is: if(window.event){x=e.keyCode} else{x=e.which}. You don't actually need to understand it fully as you can just copy it to use it in your own programs (making sure you also copy the related code in the body tag), but you may want to know a little about what's going on. Internet Explorer works differently from other browsers, so it insists on using ".keyCode" instead of ".which" to extract the key numbers from keyboard events. The easiest way to tell if the browser being used is Internet Explorer is to test to see if "window.event" is meaningful to the browser: "if(window.event)" performs this test, considering it to be true with Explorer and false with the other browsers: this then determines whether .keyCode or .which is used to extract the key number from the event. The "event" is passed to the function by putting it in brackets after onkeypress or on keydown, and it is then simplified to "e" by the function (though I could have used any other letter or name for this). Explorer doesn't need events to be passed to event-handling functions in this way as the event-handling functions can pick up the events for themselves by using "event.keyCode" or "window.event.keyCode, but this doesn't work with other browsers, so make sure you always do it the way I have shown you.

Program 12 shows you direct animation graphics, but it only works with some older versions of Internet Explorer, so you won't see a thing happen if you're using anything else. <object id="giveitaname" style="background-color: black; width: 400; height: 400" classid="CLSID:369303c2-d7aC-11d0-89d5-00a0c90833e6">: this coding is important as it calls on the aid of some graphics software (related to DirectX) to work with the browser, so you need to copy it carefully every time want to use direct animation in a Web page.
indentIf you could see that, it was rather nice. By clicking on "both+" you can get a circle to roll out of the frame. Microsoft discontinued the direct animation project and replaced it with VML: Vector Markup Language. The other browsers all use SVG instead: Scalable Vector Graphics. I haven't got round to learning these myself yet, but I'll teach them here once I have, starting with SVG. They are extremely useful for creating diagrams which use a couple of hundred bytes instead of tens of thousands of bytes, and they allow you to manipulate them with JavaScript.

Program 13 is

Program 14 is

To be continued...

Program 15. An earlier version of this program illustrates neatly how important it is to think carefully about performance. Program 15a makes the mistake of testing to see if a calculation results in a fraction inside the subroutine "calc": this slows down the program significantly (unless you click on the "allow fractions" button). Program 15 gets round this problem by recalculating every line that leads to a solution, and it's only during the recalculation that it looks out for fractions. Try typing in 8 75 2 6 6 8 and 433: the first solution it finds is rather fun.

Timer...

Program 16 is