A language agnostic book on programming.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

403 lines
18 KiB

Control statements are almost exactly as they sound, statements that control our programs.
Well, they control the flow of our code.
With control statements we can change the course of our programs based on various conditions.
\subsection{If Statements}
If statement allow us to execute a given block of code based on a given condition.
There are three main parts to an if statement \pigVal{if}, the \pigVal{conditional} and a \pigVal{code block}.
\begin{lstlisting}[caption={If Statement}]
name = ``brett''
if( name == ``brett'' )
print ``Name is brett''
\end{lstlisting}
In this simple example the code block \pigOut{print ``Name is brett''} will only execute if the conditional \pigOut{name == ``brett''} is true.
So the output of this code will be \pigOut{Name is brett}.
\begin{lstlisting}[caption={False If Statement}]
name = ``brett''
if( name == ``john'' )
print ``Name is john''
\end{lstlisting}
In this example there will be no output, this is because the conditional \pigOut{name == ``john''} equates to false so the code block \pigOut{print ``Name is john''} will never get executed.
\subsection{If-Else Statements}
If statements are great and help us execute portions of our code based on the values of other variables, including based on input from users.
But what if the condition of the if statement equates to false?
With if statements we can append an else statement and a block of code to the end of an if statement that will get called if the if statement is false.
\begin{lstlisting}[caption={If-Else Statement}]
name = ``brett''
if name == ``john'':
print ``Name is john''
else:
print ``Name is not john''
\end{lstlisting}
The output of this program will be \pigOut{Name is not john}.
When the program hits the if statement it evaluates the conditional \pigVar{name == ``john''} which evaluates to \pigVal{false}.
Normally the program will continue on its way but since we provided an else statement that gets executed instead.
An If-Else statement allows us to program ``if this then do this, otherwise do this.''
\subsection{Else If Statements}
Ok... wait, we just did If-Else statements not we are doing Else if statements?
Yes, but they are different I swear!
An If-Else statement allows us to execute code regardless of whether a conditional is true or false but with an else if statement we can provide multiple conditionals to an if statements.
\begin{lstlisting}[caption={Else If Statement}]
name = ``brett''
if name == ``john'':
print ``Name is john''
else if name == ``brett''
print ``Name is brett''
\end{lstlisting}
See? I told you it was different.
So the output of this program is \pigOut{Name is brett} and this is because when the program gets to the if statement and evaluates it as false, it then continues down the list of conditionals.
This works similar to how the else statement before worked, but this time we are giving the if statement multiple conditionals to check.
We can expand this example by adding more else if statements.
\begin{lstlisting}[caption={Else If Statement 2}]
name = ``brett''
if name == ``john'':
print ``Name is john''
else if name == ``brett''
print ``Name is brett''
else if name == ``barbara'':
print ``Name is barbara''
\end{lstlisting}
Just like the first example this program will output \pigOut{Name is brett}.
This is because when the program gets to \pigVar{name == ``john''} it evaluates to false causing the program to skip to the next conditional \pigVar{name ==''brett''}, which then evaluates to true causing the code block given to execute.
The last conditional \pigVar{name == ``barbara''} will then be skipped and the program will continue past the if statement.
\par
Now... what is we add an else statement to the end of this?
With an if statement we could append an else statement to the end telling it what to do if the conditional failed.
With an else if statement we can also append an else statement to the end telling it what to do if all of the conditionals fail.
\begin{lstlisting}[caption={Else If Else Statement}]
name = ``brett''
if name == ``john'':
print ``Name is john''
else if name == ``barbara'':
print ``Name is barbara''
else:
print ``Well, I`m not sure what your name is''
\end{lstlisting}
This program will output \pigOut{Well, I'm not sure what your name is} because both conditionals, \pigVar{name == ``john''} and \pigVar{name == ``barbara''}, evaluate to false causing the if statement to continue on its merry way.
\subsection{Switch Statements}
A Switch statement is similar to a grouping of If, Else If and Else statements but where the conditional is always a direct comparison to a value.
Switch statements are useful when you have a set number of values to compare a variable against.
For example, the following If statements are a perfect candidate for a switch statement.
\begin{lstlisting}[caption={Switch Statement Candidate}]
name = ``brett''
if name == ``john'':
print ``name is john''
else if name == ``barbara'':
print ``name is barbara''
else if name == ``eugene'':
print ``name is eugene''
else if name == ``brett'':
print ``name is brett''
else:
print ``not sure what your name is''
\end{lstlisting}
With a Switch statement it can be rewritten as.
\begin{lstlisting}[caption={Switch Statement Example}]
name = ``brett''
switch name:
case ``john'':
print ``name is john''
break
case ``barbara'':
print ``name is barbara''
break
case ``eugene'':
print ``name is eugene''
break
case ``brett'':
print ``name is brett''
break
default:
print ``not sure what your name is''
break
\end{lstlisting}
Both of these programs work in a similar manner, take a variable and do a direct comparison to a set of values until a match is made or else use a default action.
As well they will both output the same \pigOut{name is brett}.
Think of a Switch statement as a set of If, Else If, Else statements where the conditionals are always a single \pigVar{==}.
\par
A switch statement introduces a few new keywords, the switch followed by the variable name we wish to compare against.
Then we can have as many case statements following, each with the value that we wish to compare our variable against.
The only other weird part is that we are also introducing the break statement, which is required to terminate each case statement code block.
What the break statement says to do is ``break'' away from the entire switch statement.
As an excersise, try removing all of the break statements from the above example and run it again, what changed?
\par
We have mainly been comparing string variables against string values but you can also use Switch statements to compare numbers as well.
\begin{lstlisting}[caption={Switch Statement Numbers Example}]
age = 22
switch age:
case 20:
print ``not old enough to drink''
break
case 21:
print ``congratulations, do not over do it''
break
case 22:
print ``you`ve been doing this awhile''
break
\end{lstlisting}
As you can see, we can also compare our number variable against number values.
In this example we also have left out the default case, this case is optional, similar to the else statement.
\subsection{For Loops}
We have seen some statements that will help the direction of our code, but what about repeating code?
Lets say that we need to manually determine what the square of a number is using multiplication (rather than the exponential operator \verb|^|).
This can be expressed fairly easily.
\begin{lstlisting}[caption={Square Without Loop}]
num = 5
newNum = num * num
print newNum
\end{lstlisting}
Fairly easy enough and we know the output of this code will be \pigOut{25}.
Now lets say we need to do this same thing but to the power of 5.
\begin{lstlisting}[caption={Power of 5 Without Loop}]
num = 5
newNum = num * num * num * num * num
print newNum
\end{lstlisting}
Ok, now this is starting to get obnoxious.
Now what if we need it to the power of 100... I'm not programming that.
This is where loops come in, in particular the For loop.
The For loop is the perfect candidate when you need an action performed a set number of times.
\begin{lstlisting}[caption={For Loop}]
num = 5
newNum = num
for i = 0; i < 99; ++i:
newNum = newNum * num
print newNum
\end{lstlisting}
So the output of this code should be, \pigOut{7.888609052210123e+69}.
For loops can be odd to look at the first time so lets break it down part by part.
A For loop is broken into 4 parts, the Initializer, the Condition, the Update and the Code Block.
The Initializer, Condition and Update are all separated by semicolons.
\par
The Initializer, \pigVar{i = 0}, initializes some value that is going to be used throughout the loop, usually a counter; in this case \pigVar{i}.
Why is \pigVar{i} set to \pigVal{0}?
In computer programming we use a zero based counting system mainly out of tradition, but because of implementation choices made by language developers to base counting off of memory addressing offsets.
So... we just do, get in the habit now of counting from 0, everyone else does it.
\par
The Condition gets checked for every iteration of the loop and if the condition evaluates to true then the loop continues and once again executes the Code Block.
In this example \pigVar{i $<$ 99} is out Condition.
Why 99, I thought we were going to 100?
True, we are going to 100, but remember that we initially set \pigVar{newNum} to \pigVar{num} which is the same as \pigVar{num} to the first power.
Ok, so why do we use \pigVar{i $<$ 99}? won't that take us to 98?
Remember, we are using zero based counting, so 0 counts as ``1''.
\par
The Update is a statement that get executed after the Code Block and is used to update any variables we need before continuing.
In this case we are using the ``pre-increment'' operator to increase the value of \pigVar{i}, our counter, by 1.
We could have also used \pigVar{i += 1}, but \pigVar{++i} is just so elegant.
\par
Lastly, the Code Block get executed on every iteration of the loop.
The general flow of a For loop is, Initialize any variables, check the Condition if it is true then execute the Code Block, execute the Update statement, re-check the Condition, if it is true then execute the Code Block again or else leave the For loop and continue with the program.
\par
For loops are great, they save not only time, but they save a lot of typing and a lot of code duplication.
Lets say in out example above we wanted to raise 5 to the power of 50 rather than 100?
It is simple enough to change 99 to 49 and call our job done, but if we had written out \pigVar{num * num} 50 times, then it would be a pain to try and update this code.
\par
One thing to look out for with For loops, or any loops, are infinite loops, meaning a loop whose Condition will always evaluate to true.
Take the example above, if we were to change the Condition to \pigVar{i $>$= 0} then we would have an infinite loop because \pigVar{i} starts at 0 and is always increasing.
The same would be true if we changed the Condition to \pigVar{true} or \pigVar{1==1} or any other conditional statement that will always be true.
\subsection{While Loops}
So we have just seen how For loops are used to loop based on a condition and a counter for a set interval, but what if we wanted to just loop forever until a condition was met?
Well, we have While loops!
While loops are great for things such as iterating over a file or a result set from a database query or when the duration of loop is unknown.
\par
While loops contain two parts, the conditional and the code block.
The conditional is checked for each iteration of the loop, if it evaluates to \pigVal{true} then the code block is executed.
The main difference between a While loop and a For loop is that a For loop is usually designed so that it runs at least once or for a set number of times,
but a While loop has the potential to run the code block 0 times.
Let us jump into an example.
\begin{lstlisting}[caption={While Loop}]
num = 0
while num < 25:
print ``Loop''
num += 5
\end{lstlisting}
This program will print \pigOut{Loop} 5 times.
When the program gets to the While loop it first evaluates the conditional to see if the code block should be run once.
In this case \pigVar{num} is less than \pigVal{25} so the code block is executed, which prints \pigOut{Loop} and then increments \pigVar{num} by \pigVal{5}.
This loop continues until \pigVar{num} is incremented to \pigVal{25}.
\par
This example is fairly simple and even in some resembles how a For loop works.
I contains an initialization of a counter variable, \pigVar{num} to \pigVal{0}.
The conditional ensures that \pigVar{num} is below \pigVal{25}.
Finally the update is when we increment \pigVar{num} by \pigVal{5}.
So let us take a look at an example that does not use numbers to see how the While loop can be useful.
\begin{lstlisting}[caption={While Loop Over File}]
file = OpenFile(``example.txt'')
line = ReadLineFromFile(file)
while line != EndOfFile:
print line
line = ReadLineFromFile(file)
CloseFile(file)
\end{lstlisting}
As you can guess from this program, a file \pigVal{example.txt} is opened and the first line is read into the variable \pigVar{line}.
When the While loop is reached the conditional checks to see if the end of the file has been reached.
It is possible for this conditional to evaluate to \pigVal{false} the first check (if the file is empty).
For each iteration of the loop the line read is printed out.
Lastly another line is read from \pigVar{file} into \pigVar{line}; without line 6 {pigVar{line = ReadLineFromFile(file)} then the loop would continue forever as \pigVar{line} would
not update and the conditional will always evaluate to the \pigVal{true}.
\par
Although the above example uses some concepts you might not be familiar with (functions and file input/output), it should illustrate the usefulness of the While loop and
how it can differ from a For loop.
\subsection{Do-While Loops}
A Do-While loop is very similar to a While loop except in a single regard; the code block is guaranteed to run at least once.
So as we are familiar with While loops lets jump right into an example.
\begin{lstlisting}[caption={Do-While Loop}]
num = 0
do:
print ``Loop''
num += 5
while num < 25
\end{lstlisting}
This example is just like the first While loop example we looked at and will run exactly the same number of times.
The only difference is that the \pigOut{Loop} is printed and \pigVar{num} is incremented by \pigVal{5} before the conditional is checked for the first time.
Now let us take a look at an example where the Do-While loop is useful.
\begin{lstlisting}[caption={Another Do-While Loop}]
num = 0
do:
print ``Loop''
num += 5
while num > 10
\end{lstlisting}
This program will output \pigOut{Loop} only once.
The code block is executed before the conditional is checked for \pigOut{Loop} is printed then \pigVar{num} is incremented to \pigVal{5}.
Finally the conditional is checked but since \pigVar{num} is less than \pigVal{10} it evaluates to \pigVal{false} and Do-While loop stops.
\subsection{Break Statements}
We have seen a sample of Break statements already in Switch statements.
They are used to break away from control statements and are used mainly in loops.
If you are looping through and come across condition where the loop needs to stop then a break statement can be used to end the loop and continue the
program after the loop.
Lets look at an example.
\begin{lstlisting}[caption={Break Statement}]
print ``Loop Started''
for i = 0; i < 1000; ++i:
if i > 20:
break;
print i
print ``Loop Finished''
\end{lstlisting}
What will the output of this code be?
It will first output \pigOut{Loop Started} followed by a listing of 0 through 20 followed by \pigOut{Loop Finished}.
\par
As we have seen before Break statements are also used in Switch statements.
If you take a look at their purpose in loops you can see how they are useful in Switch statements as well.
When a Switch statement reached a matching case a block of code is executed followed by a Break statement telling the Switch statement to
stop matching cases and continue with the program.
\subsection{Continue Statements}
Continue statements are used in a similar fashion to Break statements but with a different consequence.
Where Break statements stop a loops execution a Continue statement tells it to skip the remaining of the code block.
Lets jump into it.
\begin{lstlisting}[caption={Continue Statement}]
print ``Loop Started''
for i = 0; i < 1000; ++i:
if i > 20 && i < 980:
continue
print i
print ``Loop Ended''
\end{lstlisting}
This program will output \pigOut{Loop Started} followed by a listing of 0 through 20 then 980 through 999 and lastly \pigOut{Loop Ended}.
So as you can see unlike a Break statement which stops a loop in its tracks a Continue statement just says stop processing this iteration of the loop and continue to the next.
\subsection{Conclusion}
We have finished a substantial chapter so lets re-cap.
We have covered how to go about controlling the flow of our programs.
To make decisions based on the value of variables as well as to continue the execution of code until a given condition is met and even how to control those features.
\par
If, If-Else and Else-If statements allow us to use conditionals to perform given blocks of code given the output of the conditional.
\par
Switch statements are used to perform a given block of code given the specific value of a variable.
\par
For loops allow us to use a counter to execute a given block of code based on the size of the counter.
\par
While and Do-While loops allow us to execute a given block of code while a conditional evaluates to true.
A While loop checks the conditional before executing the code block while a Do-While will execute the code block first before checking the conditional.
\par
Lastly, we use Break and Continue statements to control our control statements.
A Break statement is used to break free from a loop and stop its execution.
A Continue statement allows a loop to skip to the next iteration.