Thursday 30 October 2008

Block 7 - first 2000 words (rough)

Well this is going to be ugly - getting the right formatting is a massive task. Anyway here are the first 2000 words or so before I start having to say 'Talar þu ensku?'


Variables

Computer programs need places to store information these places are called variables (because their value may change during the execution of the program). Before you can use a variable, you must declare it. This is usually done at the top of a program. Here is a simple variable declaration:



Processing allows you to be extremely creative with variable names, so take advantage of that flexibility to choose appropriate names for the ones in your programs; whilst it is very tempting to call variables a, b or temp; these names aren’t terribly meaningful when you come back to your program many months later. See below for more guidance about naming variables.


int numberOfWheels;


The first word, int, tells processing that the variable will hold integer (whole number) values. Processing is a typed language that is variables may belong to one of a number of different types we will return to types below. The second word numberOfWheels is the name we have chosen for the variable. And that’s it! You can now use the variable numberOfWheels in your program.


One question that might have occurred to you is, what is the value of numberOfWheels now we have declared it? The answer is we can’t be sure; although Processing can access our new variable, it has not been given an initial value. If you try to run the following program:


int numberOfWheels;


print (numberOfWheels);


You will see a warning at the bottom of the Processing window:


Semantic Error: The variable "numberOfWheels" may be accessed here before having been definitely assigned a value.


To avoid this error, it is good practice to initialise a variable at the same time as declaring it. As the name suggests, initialisation sets a starting value for the variable, doing this is a great help when debugging a program you can track the values of variables from the moment they are created and check that their values are what you expected. Initialisation is extremely simple, we can rewrite our declaration as follows:


int numberOfWheels = 4;


If you rewrite the simple program above with this declaration and initialisation, then run it, you should see the number 4 appear at the bottom of the Processing window.



Naming variables


Processing is a 'case sensitive' language meaning that it treats upper and lower case letters as different characters. So if you declare the variables myname, myName, Myname, MyName and MYNAME you create five different variables.


Most Processing programmers use so-called 'camel case' when naming variables. Camel-case is a method of naming where individual words are joined without spaces, the first letter is in lower case with the first letter of the subsequent words being capitalised; so a variable used to store the number of wheels on a toy car could be named numberOfWheels.


Processing does have some simple rules for naming variables:


  • Variable names may only contain letters, numbers, hyphens ( - ) and the underscore character ( _ );
  • You cannot use any of the reserved keywords as a variable name. A complete list of these words can be found here: (http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html).

    In addition to these strict rules it is recommended that avoid confusion by not giving variables the same name as any of your functions or objects.


    Finally, although Processing is case sensitive and allows you to create two variables with near identical names such as myName and MyName, we strongly recommend that you do NOT do so as it will inevitably lead to confusion.



    Variable types


    As we mentioned before, variables in Processing belong to one of several types. Processing is a so-called typed language which means it treats different forms of data in different ways - called types. Although types can make life ever-so-slightly more difficult for programmers they do prevent problems when programs are run by restricting the kind of operations which can be performed on each kind of variable.


    In this section we will introduce you to the most common types used in Processing and then show you how data can be transformed from one type to another. By the end of this section you should be able to select an appropriate type for your data and use these variables in small programs.


    There are two broad categories of types; the simplest types are known as primitive types whilst more complex types of information are unsurprisingly known as complex types.


    Here are Processing’s primitive types.



    Integer


    Explanation


    Whole number values (including negative numbers)


    Declaration


    int variableName;


    Example initialisation


    int numberOfWheels = 4;


    Range


    -2147483648 to 2147483647



    Float



    Explanation


    Decimal values (including negative numbers)


    Declaration


    float variableName;


    Example initialisation


    float maximumPrice = 12249.99;


    Range


    -3.40282347E+38 to 3.40282347E+38



    Character


    Explanation


    Individual alphanumeric and symbolic characters


    Declaration


    char variableName;


    Example initialisation


    char shirtSize = ‘L’; (don’t forget to use the single quotes)


    Range


    Unicode character range. See http://unicode.org/charts/


    Boolean


    Explanation


    Logical values


    Declaration


    boolean variableName;


    Example initialisation


    boolean isFamousArtist = true;


    Range


    Only two values permitted; true or false.


    Colour


    Explanation


    Colour values expressed in terms of Red, Green and Blue components


    Declaration


    color variableName; (color is spelt using the American convention)


    Example initialisation


    color canvasColour = (255,0,255); (sets canvasColour to magenta)


    Range


    Values must be given in triplets of Red, Green and Blue in that order. Each component has a minimum value of 0 and a maximum value of 255.



    A quick note about colour values


    If you're unfamiliar with colour values, a quick explanation is needed. Every possible colour can be produced by combining different brightnesses of the three primary colours Red, Green and Blue (usually abbreviated to R, G and B). If one of the three primaries is completely absent then it is given the value 0, the maximum intensity for one of the primaries is given the value 255.


    Fortunately, you don't need to work out these values for yourself. Processing includes a Color Selector window which can be opened from the Tools menu. Use the mouse pointer to find the colour you want to use, the corresponding RGB value is given in the three boxes R, G and B.




    Exercise


    Declare and initialise the following variables.


    1. An integer variable called distanceHome with an initial value of 0;


    2. A floating point variable called currentTemperature with an initial value of 12.3;


    3. A character variable called letterOfTheAlphabet with an initial value of M;


    4. A Boolean variable called returnTicket with an initial value of true;


    5. A colour variable called brightWhite whose Red, Green and Blue values are set to their maximum.



    Answers


    1. int distanceHome = 0;


    2. float currentTemperature = 12.3;


    3. char letterOfTheAlphabet = ‘M’; (don’t forget the single quotes)


    4. boolean returnTicket = true;


    5. color brightWhite = (255,255,255);



    Complex data types



    Arrays


    An array is an ordered list of data items. You can create an array of any type of data, but a single array can only hold one type of data - so you can create an array of integers or Boolean values, but not one containing both arrays and Booleans.


    Each element in an array has a unique index number. These numbers are allocated sequentially; the first element having an index of 0, the second having an index of 1 and so on…


    Arrays are created using the keyword new and their length must be stipulated at that time. An example piece of code that creates an array is:


    int numberArray = new int[5];


    the formal specification to create an array is:


    datatype[] name of array = new datatype[length of array];


    Array elements are accessed by giving the name of the array and the index number of the element enclosed in square brackets. For example, to access the third element in an array called numberArray:


    myValue = numberArray[2];


    to assign a value to the first element of numberArray:


    numberArray[0] = myValue;


    One important attribute of all arrays is their length. You can retrieve this value using the command name of array.length for example:


    numberOfPlayers = playerArray.length;



    Initialising arrays




    It is good practice to set initial values for each of the elements in an array before the array is used. Processing allows you to do this in two ways. The first is providing all of the initial values during the array declaration. The values are enclosed in curly brackets { }, each separated from the next value using commas, such as:


    float[] bankBalanceArray = {100.0, 250.5, 500.1};


    Alternatively, you can set initial values using a simple for loop:


    int[] numberArray = new int[5];


    for (int elementNumber = 0; elementNumber < numberArray.length; elementNumber = elementNumber + 1) {


    numberArray[elementNumber] = 0;


    }


    The second approach is ideal when you are creating very large arrays.



    Strings





    Converting between types




    Try entering the following code into a processing window then pressing Run.


    int aValue = 5;


    print (aValue / 2);


    The result is 2! You were hopefully expecting a result of 2.5, so has the computer made a mistake? Actually no, the incorrect result is down to aValue being declared as an integer. Dividing an integer produces an integer result, in this case, the wrong result.


    Before we can perform accurate divisions, we must convert the variable to a different type - in this case a floating point number. Fortunately Processing has a number of functions for converting between types. Try this program:


    int aValue = 5;


    print (float(aValue) / 2);


    The function float() converts the integer value aValue into a floating point number which can then be divided accurately by 2.


    The most useful conversion functions are given below.



    int(value)


    Input types


    int, char, byte, boolean, String, int[], char[], byte[], boolean[], String[]


    Output type


    Floating point number


    Examples


    int(3.75), int(aValue)


    Notes


    Returned values are always rounded down to an integer value - e.g. int(5.75) returns 5.



    float(value)


    Input types


    int, char, byte, boolean, String, int[], char[], byte[], boolean[], String[]


    Output type


    Floating point number


    Examples


    float(7), float(aValue)



    char(value)


    Input types


    int, byte, int[], byte[]


    Output type


    Character


    Examples


    char(5), char(aValue)



    boolean(value)


    Input types


    int, String, String[]


    Output type


    Boolean


    Examples


    boolean(“Hello”), boolean(aValue)


    Notes


    An integer value of 0 evaluates to false, all other values evaluate to true.



    Most programmers choose to declare variables near the top of a program or function. The only common exception to this practise are the variables used to control the operation of a for loop. As you learned in SECTION X, a for loop is used to iterate a series of instructions; the number of repetitions being governed by an integer loop variable. For example:


    for (int i = 0; i < 40; i = I +1 ) {


    ...


    ...


    }


    Many programmers give the loop variable a single letter name such as i, j or k (this is a hang-over from the ancient Fortran programming language), but you may prefer to give your loop variables meaningful names.


    One restriction on loop variables is that they have a limited scope - that is they can only be used inside the loop itself. Copy the following program section into a Processing window and Run it:


    for (int i = 0; i < 40; i = i + 1) {


    line(30, i, 80, i);


    }


    You should see a black rectangle in a new Sketch window. A brief explanation of the program might be needed. The variable i sets the y coordinates for the beginning and ending of the lines, beginning at 0 and ending at 40. After each line is draw, the program returns to the beginning of the loop, the value of i is incremented and the next line is drawn.


    If you modify your program as follows, then Run it:


    for (int i = 0; i < 40; i = i + 1) {


    line(30, i, 80, i);


    }


    print (i);


    You will see a warning message about a Semantic Error in your program; Processing is telling you that it cannot access the variable i outside of the loop where it is declared.



    Literals


    Variables get their name because they can assume different values at different times and places in a program. However, sometimes you will need to refer to a constant value known as a literal. Unlike languages such as Smalltalk and Ada, Processing does not distinguish between variables and literals. The declaration of a literal is exactly the same as that for a variable:


    int daysInWorkingWeek = 5;


    String startOfWeek = "Sunday";


    You may have already realised that since literals are treated exactly the same as variables it is entirely possible to write a program that assigns a new value to the literal. It is therefore your responsibility to ensure that any literal values remain unchanged throughout your program. You may find it useful to name your literals in a way that reminds you they are unchangeable literals. For instance:


    int literalDaysInWorkingWeek = 5;


    String literalStartOfWeek = "Sunday";


    or perhaps use the old-fashioned approach of writing the whole of the variable name in upper case, such as:


    int DAYSINWORKINGWEEK = 5;


    although you may find this approach makes for less readable code.



    Constants


    Processing has a number of pre-defined mathematical constants which should not be confused with literals. These constants are PI, HALF_PI and TWO_PI.


  • Friday 24 October 2008

    Mass mobilisation

    So whilst we're writing a book as a collaborative effort, 1/9 of the population of Iceland has got together online to protest at Britain's (mis)use of Anti-Terror legislation to seize assets held in Britain and collapse one of their working banks. So if you fancy joining in this 21st Century Vikingry, click on one of the images below:

    Book content soon - I promise - just as soon as I'm back from - ummmm - Iceland.