You are on page 1of 20

Programming Techniques ::

Control Flow & Loops


jamie@drfrostmaths.com
www.drfrostmaths.com
@DrFrostMaths

Last modified: 23rd June 2019


www.drfrostmaths.com Registering on the DrFrostMaths platform allows you to save all the code
and progress in the various Computer Science mini-tasks.
Everything is completely free. It also gives you access to the maths platform allowing you to practise
Why not register? GCSE and A Level questions from Edexcel, OCR and AQA.

With Computer Science questions by:

Your code on any mini-tasks


will be preserved.

Note: The Tiffin/DFM Computer Using these slides: Green question Slides are intentionally designed to double up as
Science course uses JavaScript as its boxes can be clicked while in revision notes for students, while being optimised
core language. Most code examples Presentation mode to reveal. for classroom usage. The Mini-Tasks on the DFM
are therefore in JavaScript. platform are purposely ordered to correspond to
? these slides, giving your flexibility over your lesson
structure.
The flow of a program
var x = prompt(“Enter a number”);
var y = prompt(“Enter another number”);
var z = Number(x) + Number(y);
console.log(“The sum of these is “+z);

We have already seen that a program consists of a series of statements (in


JavaScript and many other languages, separated with semicolons).

When the program runs, a pointer is maintained to the memory address of


the line of code currently being run, which then advances to the next
statement, in the order they appear.
The flow of a program
var x = Number(prompt(“Enter a number”));
Var f = factorial(x);
Console.log(x+”! = “+f);

function factorial(n) {
if(n==0)return 1;
var f = 1;
for(var i=1; i<=n; i++) {
f*= i;
}
return f;
}

However, there are many constructs in programming that cause a program to jump to a
different part of the program. In later lessons we will consider subroutines such as
functions, which runs a block of code elsewhere in memory before jumping back, but here
we will consider special constructs such as if statements and while, for and do loops.

In the functions slides we will see that code is converted to assembly code
instructions (that we never see), with “GO TO line X” instructions to
jump to a different part of the program.
Statement blocks

{
console.log(“Statement 1!”);
console.log(“Statement 2!”);
{
var x = 2; A statement block is simply a group of statements,
var y = 3; but acts a single statement. We use curly braces.
} On its own it is useless, but we will see it is
} indispensable for if statements and while, for
and do loops, as well as defining functions.

For code readability/ease of maintenance, we indent the code within a


block. We can use a tab character, but this typically takes up too much
space: I use three space characters. In Python the indenting is crucial to
the program running, as curly braces are not used.
IDEs (e.g. Visual Studio) will automatically insert an appropriate number
of space characters if you press the Tab key.
if statements
! If statement:
if (condition) [statement-block]
else [statement-block]
The else statement is optional.

Examples: If the condition is true (which


must be a Boolean
expression)…
var num = prompt(“Input a number”);
if(num > 8)console.log(“Too big”);
else console.log(“Thank you!”) Then we run the statement
or statement block after it.
We don’t need curly braces
We can represent
this as a flow ‘Decisions’ are if there’s only one
chart… represented using statement.
num > 8? diamonds.

true Optionally we can include an


false Processes are represented
using rectangles. ‘else’ statement/statement
block, which is run if the
condition is false.
console.log(“Too big”) console.log(“Thank you”)
if statements

Examples:
We can chain if statements
var num = prompt(“Input a number”); together by having further if
if(num % 2 ==0) { statement within the else.
console.log(“Your number was even.”); Some languages have a
var numSquared = num ** 2; dedicated ‘elseif’ or ‘elsif’
keyword.
}
else if(num % 2 ==1) {
console.log(“Your number was odd.”);
var numSquared = num ** 2;
} else {
console.log(“Your input wasn’t an integer.”);
}
console.log(“The number squared was “+numSquared);

There’s a problem with this code. What is it?


When we cover functions we will encounter the idea of variable scope – i.e. what parts of the program declared variables are
accessible from. numSquared was declared within each if’s ‘then’ statement block, so is not accessible outside the block; in
general variables declared in a statement block will be destroyed at the end of the block and the memory freed up. The code
?
above will therefore output “The number squared was undefined”. We should therefore write var numSquared; before the
first if, and then remove the var where we’re assigning the value of numSquared.
Another problem: numSquared also won’t be set if the last else statement is used.
switch statements
var colour = prompt(“What is your favourite colour?”)
if(colour==“red”)...
else if(colour==“blue”)...
else if(colour==“green”)...
else if(colour==“burgundy”)...
else if(colour==“vomityellow”)...
...

This code is a bit clunky, as we have a number of nested if conditions, and we


have to repeat colour==

The code also runs slowly when there are a large number of options, as we
have to test each of the conditions until we match one (which may be the
last!)

Is there an alternative syntax we’re testing whether a variable is different fixed


values?
switch statements
var colour = prompt(“What is your favourite colour?”)
if(colour==“red”)alert(“Red!”);
else if(colour==“blue”)alert(“Blue!”);
else if(colour==“green”)alert(“Green!”);
else if(colour==“burgundy”)alert(“Burgundy!”);
else alert(“Another colour!”);
...

var colour = prompt(“What is your favourite colour?”)


switch(colour) {
After the switch keyword, we put the variable
case “blue” : whose value we are considering.
alert(“Blue!”);
We consider each value colour could be. This is
break; known in mathematics as a case analysis.
case “green” : break, as it is similarly used in for and while
alert(“Green!”); loops, causes the program to jump to the end of
the switch statement. Without it, all cases below it
break; (green, burgundy…) will be executed even though
... the value doesn’t match!
default : default is executed if colour is not of the above
alert(“Another colour!”); cases.
}
Let’s take a break… (pun intended) (not in GCSE syllabus)

The break keyword more generally immediately causes the program to stop the
loop and continue running at the point after the loop.

Suppose we wanted to write a program that finds the first prime


number above (or equal to) a given number n…

Without a break: With a break:

var n = prompt(“Input a number”); var n = prompt(“Input a number”);


var found = false; while(true) {
while(!found) { if(isPrime(n)) {
if(isPrime(n)) { console.log(n);
console.log(n); break;
found = true; }
We need a ‘flag’ But using break would
} n++; allow us to exit the while
which says when
n++; we’ve found the
} loop immediately, with no
} prime. The causes need for a flag.
the while loop to
stop when we Note that while(true)
need test the will indefinitely run until a
condition. break occurs.
switch vs nested if
You need to appreciate when we should use switch vs if:

Use an if statement if: Use a switch statement if:

 • You have a small number of • You have a large number of


different cases (e.g. ). cases.
• You have more complex • You are just testing whether a
? if your
conditions. e.g. ? to different
variable is equal
condition was , you can’t use a values, without a more
switch statement. complex condition (e.g. not
involving an inequality)
nested if: switch:
true
The biggest advantage of colour ==
Do stuff
‘red’?
switch statements is that
colour?
at runtime, the program false
can immediately jump to
true red blue
the correct case, via a colour ==
Do stuff
suitable mapping, without ‘green’? green
any of the other cases Do stuff
false Do stuff
needing to be tested: Do stuff
true
colour ==
Do stuff
‘blue’?

false
for statements
Suppose we wanted to output each integer between 3 and 100:
Stupid way: Non-Stupid way:
console.log(3);
console.log(4); for(var i=3; i<=100; i++) {
console.log(5); console.log(i);
... }
console.log(100);
#5: Once i
What we need is a variable whose value gets to 101,
will be each number between 3 and 100. the condition
#3: As the condition 101 < 100 is no
We want to start this at 3.
was true, this code longer true, so
gets run, outputting the for loop
#1: The first statement allows us to declare
“3” to the console. terminates.
this variable (we’ll call it i) and initialise its
value to the starting value of 3.
#4: Before we run the next
#2: Before the statement block between the { … } is iteration of the loop, we want
run, this Boolean condition is tested. Since 3 < 100, i to go up by 1, so that i=4.
it will get run! This third statement is
This statement block will then run where i is 3. intended to increment your
variable. Since 4 < 100, the
for loop will continue
running, and output 4 next.
for statements
Suppose we wanted to output each integer between 3 and 100:
Stupid way: Non-Stupid way:
console.log(3);
console.log(4); for(var i=3; i<=100; i++) {
console.log(5); console.log(i);
... }
console.log(100);

! For loop:
for(statement1; condition; statement2) [statement-block]
where:
• statement1 is executed before the loop and we typically declare a variable to use
in the loop.
• condition must be true in order to run the next iteration of the for loop.
• statement2 is executed after each iteration. We typically increment the variable
we declared.
• The statement/statement block is what is run on each iteration.
Further examples
What do the following fragments of code do?

var total = 0;
for(var i=1; i<=50; i++) {  
This finds ,
i.e. the 50th triangular number.
total+= i; ?
In maths we could write this as:
} where means ‘sum’.
console.log(total);

var total = 0;
for(var i=1; i<=50; i+=2) { This prints out all the odd numbers
console.log(i); between 1 and 49?(notice the i+=2,
which increments i by 2 each time)
}
Flow diagram for for loops

var total = 0;
for(var i=1; i<=50; i++) {
total+= i;
}
console.log(total);
set total = 0

The condition is always


checked before we run
For loop set i = 1
total+= i each time.

If the condition no
longer holds, we exit
Increment i by 1 i <= 50? the loop and go to the
code after the loop.

true false

Increment total by i

The i++ is run after Output total


each iteration (i.e. after
the total+= i)
while loops
While loops are a simpler version of for loops, where we still have some condition
which must remain true for the loop to continue, but there is not some variable
we are incrementing.
Given this, it’s theoretically possible to write a while loop as a for loop, by just
omitting the first and last statements (which related to the incrementing variable):
while(i<10)  for( ; i<10 ; ) But don’t do this!

While loops are typically used when we don’t


necessarily know how many times the loop will run.

for(var i=1; i<=50; i++) { Here, we know the


total+= i; loop will run 50 times.
}

var num = Number(prompt(“Input a number”));


while(num%2 == 0) { This code divides num by 2 until we’re left
num = num / 2; with an odd number. Because num is input
} by the user, we don’t know in advance
how many times the loop will run.
do while loops
Like for loops, while loops check the condition before the first iteration.
This means it’s possible for the statement block in your loop to never run:

while(false) { This line will never be


console.log(“The cake is a lie.”); run.
}

But sometimes, we want to make sure the statement block is executed at least
once, so run the block and then check the condition after it is run.
This effectively means we skip the condition check on the first iteration:

var i=0;
do { We do the ‘do’ bit and only then check the
console.log(“The number is “+i); condition. Note that the last output is 9,
i++; because after the number is incremented
} while (i<10); to 10, the check at the end fails.
The number is 0
The number is 1 In practice, do while loops are rarely
… used, but for and while loops are both
The number is 9 extremely common.
Test Your Understanding
What will each of these output?

var i = 1; var i = 1; for(var i=1; i<=7; i+=3)


while(i<1) { do { {
console.log(i); console.log(i); console.log(i);
i++; i++; }
} } while(i<1)

[Nothing!] 1 1
? ? 4 ?
7

var i = 30; var i = 30;


while(i>1) { while(i-- < 40) { Recall that i-- decrements the
console.log(i); console.log(i); value of i but returns the old value.
if(i%2==0)i = i/2; }
else i+=7;
}

30, 15, 22, 11, 18, 9, This will output 30, 29, 28,
16, 8, 4, 2 ? 27, … and keep?going forever.
Review
What’s the different between while(…){ … } and do { … } while(…) ?
The first tests the condition before each iteration. The latter tests it after each.
The latter guarantees the statement block?is run at least once.

What keyword must we include (in most languages) at the end of each ‘case’ in a
switch statement? What would happen if we forgot them?
break. If they weren’t there, the code for every case after the matching one would
also be run! ?
Why might we use while instead of a for loop?
If we didn’t know how many times our loop will run.
?
Under what circumstances could we not use a switch statement instead of nested
ifs?
switch can only match a variable against?set values. It doesn’t allow more arbitrary
conditions, e.g. involving inequalities.
Coding Mini-Tasks

Return to the DrFrostMaths


site to complete the various
mini-coding tasks on
functions.

You might also like