Control Structures
Syntax:
if-else
if ( cond )
statement if cond == true;
if ( cond )
{
statements if cond == true;
}
if ( cond )
{
statements if cond == true;
}
else
{
statements if cond == false;
}
if( cond1 )
statement if cond1 == true;
else if ( cond2 )
statement if cond1 == false and cond2 ==
true;
while
while ( cond )
statement;
while ( cond )
{
statements;
}
break
break;
Note: 'for' loops and 'switch' statements will be added to the language in future revs.
General:
Control Structures allow us to alter the flow of execution of a
function. Without them execution of a function would start at
the first line, proceed to the second, then third and so on until
the last line. While linear execution like this does have
it's uses generally we want to be able to change the line of
execution.
Let's pretend that the library function 'min' didn't exist and we had to write one of our own (the min function takes two doubles as arguments and returns the smaller of the two). We'd start off with something like this:
double min(double a, double b)
{
. . .
}
To return a value from a function we use the 'return' function. So somewhere in our function body we need:
return( a );
and
return( b );
The return(a) needs to execute when 'a' is less than 'b' otherwise return(b) needs to execute. What we need is some way to test whether 'a' is less than 'b' and if so execute return(a), otherwise execute return(b). We can accomplish that with an 'if' control structure:
double min(double a, double b)
{
if( a < b )
{
return( a );
}
else
{
return( b );
}
}
We read the code above: "If a is less than b, return a; else return b". Compare that with the way we described the problem above and programming might not seem so cryptic after all. While the example above might be the most verbose way of coding a more compact, and completely equivalent, way of doing it would be:
double min(double a, double b)
{
if( a < b )
return( a );
return( b );
}
Since only one statement followed the 'if' structure we don't need to enclose the statement in braces ( we do have to if there's more than one statement). Also since the statement return(a) will cause us to leave the function we don't need to enclose the return(b) statement in the else block since the only way we could reach the line return(b) is if a is not less than b in which case return(b) is exactly what we want. Don't worry if you don't get all of that just yet, it is perfectly legal to write things as in the previous example, the above is just a style issue.
Note: As mentioned in Variables, to test for equality we need to use the '==' symbol, not '='. If we try to test equality with if( a = b) then we are testing whether 'b' is successfully assigned to 'a', not the equality of the values of each. Instead we need to use if( a == b) to get the desired results.
So the 'if' control structure allows us to execute a section of code only if a certain condition is met. That certainly breaks up the linearity of the execution. But what if we wanted the same statement to execute several times? For example let's write a function that returns the factorial of a number. ( the factorial of n is 1*2*3*4…*n. In math the factorial of a number is indicated by putting a '!' in front of the number: !5 = 120. If you look on your calculator there's probably a button labeled n! or X!).
We could write a function that returns the factorial of 5 like so:
int factFive()
{
int value;
value = 1;
value = value * 2;
value = value * 3;
value = value * 4;
value = value * 5;
return( value );
}
Now that's all fine and dandy as long as you're only ever interested in getting the factorial of five. If you wanted the factorial of six you'd have to write another function to return !6. It would be a lot nicer if we could have one function that would return the factorial of whatever number we passed to it.
Notice above that we're executing almost exactly the same line of code 4 times. The only thing that's different is the last number. Notice also that there's a pattern to those last numbers, each is one greater than the last. What if we could make it so that we only needed to write that line once, and then call it multiple times? We could also use a variable for the last number and each time we called the line of code that variable would increase in value by one.
int fact( int number )
{
int i = 2;
int runningTotal = 1;
while( i <= number )
{
runningTotal =
runningTotal * i;
i = i + 1;
}
return( runningTotal );
}
There we go! The 'while' structure will execute it's enclosed statements until the condition expression ( i <= number in this case ) evaluates to false. This type of control structure is referred to as a "loop" since the flow of execution loops around until the condition is no longer true.
Nerd Alert: For those of you that are cringing at a loop based factorial function don't worry we'll come back to it when we get to function recursion.
Let's walk through the steps of the function as though we had called: fact(3).
First we declare and initialize two variables, i and runningTotal. We will use runningTotal to hold the computed value of the factorial as we loop through the numbers. The variable i will be used for two things, one is value that we multiply runningTotal by to get the new value of the factorial up to that point. The other use for i is that it allows us to exit the loop (otherwise we'd be looping forever).
Next we start execution of the loop. The body of the while structure will only execute if the condition is true, in the case of the first time through i is 2 and number is 3, since 2 is less than or equal to 3 the condition is true and we move on to the first line in the while loop. At this point runningTotal equals it's initialization value of 1. So executing runningTotal = runningTotal * i; can be translated as: runningTotal = 1 * 2. Now runningTotal is equal to 2 and the next line makes i equal 3. Since the last line of code in the loop has executed we jump back up to the condition and test it again to see if we need to go through the loop again. This next time i is now 3 and number is still 3. Again the condition is true so once more through the loop. The value of runningTotal is updated to 2 * 3 or 6; i is again incremented and we jump back up to the condition. This time i equals 4 and the condition 4 < 3 is false so we don't go through the loop again. At this point execution of the function resumes on the line immediately after the while structure, the return( runningTotal ); line in this case.
Sometimes it might be necessary to leave a loop early. In those cases you can use a 'break' statement to leave the control structure and continue execution immediately afterwards:
while( 1 )
{
if( !a = getNumber() )
break;
. . .
}
// execution continues here after the break statement
. . .
In the case above we actually need the break statement if we ever hope to leave the loop ( the expression '1' always evaluates to true so the loop will always execute unless a break statement is called). Here we're using an 'if' to test some condition, and if that condition is true we are going to break from the loop.
This brings up the topic of "infinite loops". This is one of the most common pitfalls for beginning programmers. Make sure you have a way out of your loop! You need to be guaranteed that your condition will evaluate to false at some point. If you can't make that guarantee then you need to provide another way out of the loop, with a 'break', after some condition is met. In our factorial example our condition tested the inequality of two numbers, one of them remained the same value and the other incremented steadily. In that case we were guaranteed that at some point the expression would evaluate to false. What if both numbers varied though? Could we guarantee that without question at some point it would evaluate to false? No. In all probability it would but we can't say for certain. Take the following kinds of common mistakes:
while( i < 10 )
{
runningValue = runningValue + i;
}
while( i > j )
{
i = i + 1;
j = j + 1;
}
These are just a couple example where at a quick glance things would appear to be fine, but upon closer inspection we find that we're gonna be stuck in those loops for quite a long time. In the first example the value of 'i' never changes so it will never be less than 10 (assuming of course that i was greater than or equal to 10 in the first place, but if it wasn't we would never have entered the loop and couldn't get stuck there). In the second one both values vary which means we should be skeptical about whether or not the expression is guaranteed to evaluate to false. In this case it's guaranteed not to evaluate to false since both variables vary the same.
Converted from CHM to HTML with chm2web Pro 2.82 (unicode) |