Sunday, April 26, 2009

Chunk finished

Finally I have managed to continue with this

Operators

Now we are going to talk operators. If you are now thinking of switchboard operators or machine operators then we guess you paid about as much attention during Maths class as the rest of us. If this is the case don't worry there is nothing difficult in this section. In fact operator is just a fancy word for a mathematical symbol, such as '+' or '-'. If you already know all this then fine, feel free to skip ahead if you wish.

We am going to divide this section into four; basic operators, relational operators, conditional operators, and assignment operators. Don't worry about any of those terms they will all be explained. Finally we will discuss a concept known as precedence.

We are going to look at several programming examples to understand the working of these operators, however we will also develop a program which enables us to visually see the result of our calculations. So to start create a save the following program for us to work with.

/*title: Operator
description: a program to demonstrate the use of operators
*/

//Set size and colour of sketch window
size(300,200);
background(255);

//Declare variables used for drawing
int xpos = 10;
int ypos = 10;
int endx = 290;
int endy = 50;

//Drawline
line( xpos , ypos , endx , endy );

Run this program, then save it as OperatorExample for later use.

Basic Operators

Almost everybody (if not everybody) will be familiar with the basic operators from school, these are addition, subtraction, multiplication, division and equality. From school you may remember these as a horizontal line for subtraction, an upright cross for addition, a cross rotated by 45 degrees for multiplication, a horizontal line with a dot above and below it for division and two horizontal lines for equality. Now take a moment to pause and look at your computer keyboard, how many of those symbols can you find?

I am willing to bet you found three (though I'm sure someone will have a radically different keyboard). On my keyboard I find -, + and =. OK so how do we do sums involving multiplication and division? The answer is we use two different symbols for these actions. We use / for division and * for multiplication. That is a backslash symbol and an asterisk. You may find these strange to use at first, but don't worry they soon become second nature.

To demonstrate the results of using these operators open Processing and in the blank sketch try typing this program in and running it. The println function displays the results of the expression in the black section at the bottom of the main window.

println( 5 + 4 );
println( 75 * 10);
float x = 4 * 3 / 5.6;
println(x);

You should get an output of 9, 750 and 2.142857.

The = (equals) operator may cause some confusion, that is because instead of using it for measuring equality we use it for assignment, that is it makes the value on the left-hand side of it equal the value on the right-hand side. We shall cover this in greater detail under assignment operators.

One final operator for this section is the % modulus operator, I found this rather confusing and seemingly of little use. However it is invaluable when you do need it. The way it works is this. When you divide two numbers they don't always divide perfectly. For example 7 divided by 2, 2 goes into 7 three times and leaves a remainder of 1. The modulus operator gives us a method of finding out what the remainder is. So for the previous example 7 % 2 returns a value of 1.

This can be demonstrated by running the following program.

println( 7 / 2 );
println( 7 % 2 );

This will output 3 and 1. The 3 might be confusing since you might be expecting a fraction in response. The reason for this is that it is returning an integer value which can only contain a whole number (see page xx).

We are now going to apply what we have learnt to our example program. So open OperatorExample and after the last line

//Drawline
line( xpos , ypos , endx , endy );

add these lines

//Change draw colour to red
stroke( 255 , 0 , 0 );

//Alter beginning and ending positions using basic operators
line( xpos + 20 , ypos * 5 , endx / 3 , endy - 50 );

Relational Operators

Again thinking back to Maths class in school you might remember Relational Operators. These basically measure two values against each other and tell you if they are the same or if one is greater than the other. The two you are most likely to remember are < (less than) and > (greater than).

Unlike the basic operators these return true or false value. To illustrate let us consider a common example if( 4 < 5 ) This translates into if 4 is less than 5. Since 4 is less than 5 the answer is true. So if we had if( 4 > 5 ) the answer would then be false, since 4 is not greater than 5.

There will be times when you need to check if a number is less or equal (or greater or equal) to another number. There are two handy operators to do this <= (less or equal) and >= (greater or equal), these differ from the previous two in that if( 5 < 5 ) would be false 5 is not less than 5, but if( 5 <= 5 ) would be true, 5 is not less than, but it is equal to itself.

Finally you may wish to simply compare two numbers and see if they are equal or not equal to each other. However the '=' operator has already been taken for use as the assignment operator, so to get around this we use == (equal to) and != (not equal to).

Some examples

if( 6 < 6 ) would be false
if( 6 <= 6 ) would be true
if( 6 > 5 ) would be true
if( 6 == 6 ) would be true
if( 6 != 6 ) would be false

To prove this let us run a program to demonstrate the above.

println( 6 < 6 );
println( 6 <= 6 );
println( 6 > 5 );
println( 6 == 6 );
println( 6 != 6 );

You should have recieved an output of false, true, true, true, false.

Again open our example program and add the following lines on to the end

//Use conditional operators to decide what is drawn
if( xpos >= ypos ) {

//Change draw colour to green
stroke( 0 , 255 , 0 );
line( xpos , ypos + 20 , endx , endy + 20 );

}
else {

//Change draw colour to blue
stroke( 0 , 0 , 255 );
line( xpos , ypos + 20 , endx , endy + 20 );

}

Don't worry if you don't understand the meaning of if and else yet, we cover these later on pages xx to xx. But try to spend a few minutes working out what you think this program will do before you run it.

Conditional Operators

Conditional operators are very often found in conjunction with relational operators to create more complex expressions. They are used to evaluate true and false values. There are two such operators && (and) and || (or). && returns a value of true when the expression on both the left and right-hand sides are true. || returns true if one or both of the left and right-hand side expressions are true.

Left-hand side Operator Right-hand side Result
true && true true
true && false false
false && true false
false && false false
true || true true
true || false true
false || true true
false || false false

Some real world examples of this:

if( y < 20 && x > 50 ) would be true if y is less than 20 and x is greater than 50
if( y < 20 || x > 50 ) would be true y is less than 20 or x is greater than 50

The following program will output the final column of the above table

println( true && true );
println( true && false );
println( false && true );
println( false && false );
println( true || true );
println( true || false );
println( false || true );
println( false || false );

Running this should give you a result that matches the final column of the above table.

One other operator which fits into this category is ! (not), this reverses the true or false value of an expression or variable.

For example

if( 6 < 6 ) is false
if( !( 6 < 6 ) is true because the not operator has reversed the false value.

You are most likely to see ! used with variables like this if( !doorIsOpen && windowIsClosed )

Again to demonstrate this run the following program.

boolean doorIsOpen = true;
boolean windowIsClosed = true;
println( "doorIsOpen && windowIsClosed = ");
print( doorIsOpen && windowIsClosed);
println( "!doorIsOpen && windowIsClosed = ");
print( !doorIsOpen && windowIsClosed);

You should be able to see that the not operator reversed the true value of doorIsOpen and so the expression evaluated as false.

Again open our sample program and this time change the line

if( xpos >= ypos ) {

to read

if( xpos >= ypos && ypos < 5 ) {

Again try to predict the response before running it.

Assignment Operators

We have already touched upon assignment operators earlier in this section when we mentioned the '=' assignment operator. Just a reminded the = operator is only for assignment. If we need to test for equality we need to use '=='. Thus x = 5; makes the variable x contain the value 5. x == 5 would compare the contents of the variable x with the value 5 and return a true or false value depending on the value of x.

Now logically you may think there could only be one assignment operator, it may surprise you therefore if I tell you there are actually eight assignment operators. Before I tell you what they are I'm going to illustrate the need for more than just '='.

We already know that the expression int x = 5; puts the value of 5 into the variable called x. This is quite useful, but what if we want to do something more to that value. What if we want to add 15 to the value already held by x? Logically you might think that you could write x + 15;

Well let us test that logic, type the following into Processing and press run.

int x = 5;
x + 15;
print( x );

You should receive an error along the lines of Syntax error on token "+", invalid AssignmentOperator. The reason is that we need to assign the result of the expression to something, in this case we wanted to assign it to x. The correct syntax ( or way to write this) would be x = x + 15;

If you scratch your head and look confused at this point you wouldn't be the first person to do so. What happens here is that the expression on the right of the assignment operator is evaluated first, so that 15 is added to the current value of x which is 5. The result of this (20) is then assigned on the left-hand side of the assignment operator to x. Now x equals 20.

So the above program should look more like this

int x = 5;
x = x + 15;
print( x );

This should compile and run just fine.

Now programmers are often called lazy because they like to type as little as possible in order to write a program. For a short program like these example programs extra typing is not much of a problem, but when you start typing in some of the longer programs later in this book you will be glad for any available shortcuts. The extra assignment operators are exactly that shortcuts.

So for the above example the we could shorten the line x = x + 15; to x += 15; to test that this is a shortcut with no changes in meaning replace the second line in the above program with the shortcut version and run it.

So five of the assignment operators are this style of shortcut, += , -= , *= , /= and %= .

A demonstration of how you would use these follows.

float length = 5.34;
println(length);
println( length += 5 );
println( length -= 5 );
println( length *= 5 );
println( length /= 5 );
println( length %= 2 );

If you look at each of the operators above you will see that the operator is surround on its left and right-hand sides. So length /= 5, the operator has length on the left side and 5 on the rightside, the correct term for the parts surrounding it are operands, so we would say these operators always have two operands. Another term for this is to say they are binary operators. Some operators take one operand, these are called unary operators. Why are we telling you this? The reason is that that last two assignment operators are unary operators.

A very common operation is to repeatedly add 1 to a variable, for example x = x + 1. We have already seen that you could shorten this to x += 1; but a mentioned earlier programmers like to type as little as possible. As a result we have a whole new shorthand operator for this common occurance '++' so we can just write x++; of course we also have 'x--' to replace x = x - 1;

You may see this operator being used as x++; or ++x; in many cases it doesn't matter if the operator appears before or after the operand, but in certain circumstances it does. In the case of x++ the operator is called the postfix increment operator and in the case of ++x it is called the prefix increment operator. The difference is only when you are using these operators in a bigger expression.

Try running this program

int x = 5;
println( x++ );
x = 5;
println( ++x );

You should see a result of 5 and 6. The reason is that for x++ the value of x is used before it is incremented, whereas for ++x the value of x is incremented before it is used. The difference is enough to cause huge headaches later on if you use the wrong one in the wrong place, but don't let that put you off using these shortcuts. The benefits outweigh any possible negative points. The first benefit is that you will look extremely professional, the second is that you can write you programs every so slightly faster, the third is less keystrokes which protects you from RSI and finally confuses novice programmers and you are no longer a novice.

Finally we will alter our sample program to take into account what we have learnt here.

We will be making some major changes, so to make it easier we will put the whole program here for you to see.

/*title: Operator
description: a program to demonstrate the use of operators
*/

//Declare variables used for drawing
int xpos = 10;
int ypos = 10;
int endx = 290;
int endy = 190;
int ourRed = 255;
int ourGreen = 255;
int ourBlue = 0;

void setup{

//Set size and colour of sketch window
size(300,200);
background(255);

}

void draw(){

//Make sure we don't draw off the window
if( ypos <= 190 || endy >= 10){

//Change the draw colour
stroke( --ourRed , ourGreen , ourBlue++);
line( xpos , ypos++ , endx , endy-- );

}
}

Precedence

The final topic in this section is precedence. Basically the term precedence means the rules which control the order in which operators take effect. Like the last discussion about postfix and prefix operators this is a topic which you might get away with knowing nothing about until the day you come across the side effects and your calculations keep coming out wrong.

As we touched on earlier mathematical expressions are evaluated from left to right. However this only holds true when all the operators used in the expression have the same precedence.

To demonstrate try this small program, try to work out the answers before running it, then see if you get the answer you expected.

println( 2 * 5 + 2 );
println( 2 + 2 * 5 );

If the expressions evaluated strictly from right to left you might expect to get 14 and 12, yet when we run it we get 12 and 12. This is because multiplication and division operators have a higher precedence then subtraction and addition operators, this means that the multiplication takes place before the addition in the first line and so the result is the same as the second line. But don't worry about having to learn the order of precedence of all the operators (though you can if you want), the only important thing to know is that parentheses have the highest order of precedence and expressions contained with in these are evaluated first.

Try this with the program above, alter the first line to read

println( 2 * ( 5 + 2 ) );

Now re-run it. This time you should get an output of 14 and 12. We have forced the addition to take place first.

When you have several parentheses nested inside each other the innermost gets evaluated first and then it works its way outwards. So instead of learning the order of precedence you can just use parentheses to make sure that expressions are evaluated exactly as you wish.

One thing to be aware of is in very complicated expressions it can be possible to accidently miss out one of the parentheses which will prevent the program from running, there needs to be as many closing ')' parentheses as there are '(' opening parentheses. Processing has a nice feature in that if you select one of the pair of parentheses it will show you the matching one of the pair which can help in tracking down any that are missing.

That is is for operators at the present. There are a few more we won't be covering yet, these are the bit-wise operators and appear later at page xx. However they are very advanced and the ones you have already learnt will get you through 99.9% of your programming needs.

Sunday, December 28, 2008

Gulp

Just looked at the date on the last blog and realised how quickly time had gone. What has happened inbetween, well I have more or less kept up with all the blogs I'm subscribed to, some of them have amazed me in the depth of knowledge that their author's display.

I have finally received my graduate as a 2:1 with honours so I am happy. I have also signed up for one of the earlier chapters dealing with Operators. Since I have a week off next week I will be making a start tomorrow. I have been trying to get my hand it with writing, after a long break I have been writing poetry again and finally started on the book I meant to write 15 years ago. Now all I hope is that my new found enthusiasm survives into the new year. :)

By the way congratulations to everyone else who has graduated this year and an earlier happy new year to everyone.

Thursday, November 13, 2008

Book Arrived

Finally my book has arrived so I like many others am rejoicing. Now to sit down and start reading then play catchup with people like jannetta and mike ;). Well I won't get too ambitious.

Saturday, November 8, 2008

Book on the Way

Email from Waterstones today the book is in the post, finally I can play catch up. For some reason I don't get on well with PDF documents. I prefer a real book any day.

Sunday, November 2, 2008

Head Scratching

Not much time to play so far, had all the family over for a house warming this weekend. Tried to write a program that altered the colour of a peice of text based on mouse movements, only very limited success, for some reason code that looked like it should work didn't. I think I need to go back and start from the beginning, drawing seems easy enough, but some other areas are not so easy.

Found a website with some nice examples on today though. http://www.sjeiti.com/?page_id=6

Thursday, October 30, 2008



Thank you for your recent order at Waterstones.com.
Unfortunately the items below are not currently in stock in our warehouse, so we have placed an order with the publisher.
The items are:
IRA GREENBERG Foundation Processing


I wonder if Waterstones will place a bulk order with the publishers to keep up with unprecedented demand?

On Order

My gift card arrived 10 minutes ago and I've already used it at Waterstones.com. The power of the Internet is amazing sometimes, no need to drive for 30 minutes to my nearest branch to find the book is out of stock just sit at home and order. It was also one of the most pain free experiences for awhile, I expected problems with processing the gift card, but there were none.

The only thing is the quoted 2-3 weeks delivery time, I wonder how accurate that is. I blame all those other chunk writers getting there before me. So now to wait and continue playing (or studying as I tell my wife).

Sunday, October 26, 2008

No point starting a blog and leaving it empty

Like many of the other blogs in this project my first post will be an introduction to me. I have just finished M450 which was a grueling experience. I thought that as soon as I finish the project and wait to hear whether I achieved the BSc (Hons) I was going for that I would take a break from the OU. Already though my brains has developed an I can't scratch. I find myself looking at the prospectus of courses and thinking what if?

Fortunately I have just been tossed a temporary lifeline. I received an email about the mass writing project, somehow I had missed the article in sesame. Immediately I thought I am interested in this. I have always had dreams of writing, for the last 18 years I have been writing 3 different books in my head, occasionally I put some of paper, but the stories don't flow the same way.

Last year I started writing an open source book on C++ programming which is half finished and was put on hold since it took time from M450. Maybe soon I will get back to it. So this project immediately appealed to me I have a lot of experience with C++ and object oriented programming through this. My Java is more limited, I have used it during a couple of courses but somehow I can't get the same feel with it as C++.

I have looked at the Processing ide and already I am amazed by the power in such an unassuming package, I hadn't even heard of it before, but it takes me back to programming in basic, a couple of lines of code and you can get something up on screen. Even better you can then export this to embed in a web page. I am going to enjoy playing with this.

Already I have written more then I expected, I hope it is this easy for the project itself.