Programming Techniques::: Control Flow & Loops
Programming Techniques::: Control Flow & Loops
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);
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.
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);
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!)
The break keyword more generally immediately causes the program to stop the
loop and continue running at the point after the loop.
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
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
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?
[Nothing!] 1 1
? ? 4 ?
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