Sunday, 7 December 2008

Loops and the if Statement - First Draft

If there were no loops in our code, then our programs wouldn't last long, or they would have to contain a huge amount of repetitive code.
Looping structures all consist of the same basic format. A conditional statement. followed by the block of code to repeat.
An if statement isnt really a looping construct, but as it follows the same type of format, we will discuss it here.
The basic form of an if statement is as follows:
if(condition/s){do this}

if(a==10){ //if a is equal to 10 THEN
a=0;} //do this

if(a >=10&&b==100){ //if a is greater than 10 and b has a value of 10 THEN
a=0; //do this
b=0;} //and do this

if(a>=10&&b==100)||(!isEnabled){//as above OR isEnabled is false
a=0; //do this
isEnabled=false;} //and do this

The functionality of an if block can be extended by adding an else block.

if(a <> //if a is less than 100 THEN
a++;} //let a=a+1 (increment a)
else{ //otherwise (if a is greater or equal to 100)
a=0;} //do this

The if statements can be even further extended, with the else if block. You can use as many else if blocks as you like. The else and else if blocks cant be used on their own and must be proceeded by an if statement. Great care should be taken to ensure that the brackets are in the right places.

if(a < face="courier new"> if(a < =50){
a=+2; }
else if(a <>
a++; }

Examples of using if, else if and else consructs in chunk 16, can be seen on lines 36 and 124.
All looping structures have a conditional statement and an executable block, that is only carried out, if the condtion holds.

No comments:

Post a Comment