Programming Chapter 3 Old

Note: this page has been replaced by Programming Chapter 3

Author: Lucas Goss

Game Time
What? I know we just started the chapter, but now we know enough about programming that we should be able to make games while we learn, which will hopefully make things more interesting. Now creating a game is no simple task, so we'll also go step by step. And since this is just a tutorial about programming, we'll make it a simple text game to make it as simple as possible.

Enum-ination
Enumerations are custom data types with a predefined set of values. To create one use the keyword enum followed by a name for the enumerator followed by a a list of strings between curly brackets separated by commons.

If Statement
The if statement is similar to the ternary operator as it tests a condition, but instead of returning a result it executes the next statement if it evaluates to true (so if you use a block {} you can execute multiple statements). else if can be used to test more conditions before using an else which is a catch all to execute if all the if statements were false.

"if" works in sequence. So the first if will be checked to see if it evaluates to true, and if true it goes into the block statement following the if while the rest of the statements are ignored. So in this case the first statement evaluates to false as temperature is less than 60, so it skips to the next statement. The second statement "else if..." evaluates to true, so the phrase "It is cold out." will be put in the log. The third statement is ignored as we've already got a statement that evaluated to true.

For Loop
The For loop is an iteration loop that allows you to repeat a statement over and over a certain number of times.

At the end of this loop the value of sum will be 45 (0+1+2+3+4+5+6+7+8+9).

There are three statements required by a for loop (reminder, statements are separated by a semi-colon):
 * The initial value, in this case it is i=0 (you can initialize variable earlier).
 * The condition to continue the loop, in this case while i<10 we continue.
 * The step the index takes, in this case increase i by 1 i++ (you can also do decrease).

But be careful of a never ending loop (it just keeps going, and going, and going...)

Jump
There are two main jump statements:
 * continue: jump back to the control statement.
 * break: break out of the control statement.

In this example sum will be 40 (0+1+2+3+4+6+7+8+9) since we skipped 5 and quit when i got to 10.

Programming Index : Previous Chapter : Next Chapter