If statements

So far, the Processing commands that we have written have been executed one after the other, in the order they are written. This is fine for very simple programs, but mostly we want certain commands to be executed and others not to be.
To skip some commands under certain conditions, we need to have special commands called control statements which control the order in which our commands are executed in a program. The most widely used control statement is called an ‘if statement’.

In this example by Sipho, he used an ‘if’ statement to determine what colour is drawn when the user moves the mouse around.

Sipho Msai Ngqayimbana

Sipho Msai Ngqayimbana

Checking the value of variables

If statements are used to check the value of a variable and then execute different blocks of commands, depending on the value of the variable. For example, if we set a Boolean variable “direction” whenever someone presses an arrow key, then we can check that variable, which decides which block of code to use when we draw the Pacman.

if (direction==0) //this checks the value of the variable 'direction', and whether it's true that it equals zero
{
	//if it is true, then draw pacman arc facing right
	arc(pacX, pacY, radius,radius, radians(45), radians(315));
}
else //if the condition is not true, 
{ 
	//if it is not true, then draw pacman arc facing left
 	arc(pacX, pacY, radius,radius, radians(225), radians(360+135)); 
}
Advertisements

3 thoughts on “If statements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s