6.2: Loops
Learning Objectives
By the end of this lesson, you should be able to:
Explain how loops are used in the control flow of a program.
Use a
whileloop to run a code block for a fixed number of times.Use loops within loops.
Be familiar with both the
for-loop andwhile-loop syntax.
Introduction
We've defined an array, added values to it, and inspected those values individually, but haven't yet learned how to systematically manipulate each element in the array, no matter how long the array is. To do this we will learn 1 more control structure: "loops".
In SWE Fundamentals we will mostly use loops to iterate over array elements. Loops can also be used without arrays, for example to perform an action until a condition is no longer true, but we will not see this often in SWE Fundamentals.
A loop defines a code block (with curly braces) that runs until the loop condition is no longer met. We'll look at loops in isolation first, then see them in the context of arrays.
While Loop
While loops are the most fundamental type of loop in programming, and the concept exists in many programming languages. The following is a "while loop" that runs 10 times, i.e. until its condition is no longer met. Notice how we define a counter before the loop, and increment the counter at the end of the loop. The loop finishes when the counter reaches 10.
While Loop with Input-Based Condition
Let's create a program that outputs values in a loop, where the loop condition depends on user input.
Note that except for rare exceptions, the incrementation of the counter (counter = counter + 1) should be the last statement in the loop block. If you find yourself writing any statements below that, it may not be what you intended.
Loops and Conditionals
While Loop with Input-Based Condition and Conditionals Inside Loop
Let's create a program that outputs values in a loop, where loop condition depends on user input, with additional conditional statements inside the loop. In the following example, the conditionals inside the loop help the program combine 2 different strings into program output.
Conditional Logic Variations
Loops and conditionals alone are powerful tools to create output patterns. One of the main tricks with loops is identifying the pattern we want and working backward to construct the logic within the loop. The following example uses the modulus (%) operator in a conditional in a loop to alternate strings in output.
Loops and Functions
We can also combine loops and functions. Functions in loops allow us to move code blocks (i.e. complex logic) outside loop definitions, breaking down our code into smaller components, helping simplify our code logic.
In the following example, we define rollDice as a standalone function, and call rollDice from inside our loop. This helps keep our loop logic clean by separating the details of rollDice out from the loop.
Loops and Loops
Nested Loops to Simulate Dimensions
If we put a loop inside a loop we can represent 2 dimensions of output. Note we use <br> to create new rows. <br> is a newline HTML tag that can help us format our output.
For Loops
Most languages have variations on the while loop above that behave similarly. One common variation is the "for loop". For loops are a more concise syntax for looping over a fixed number of iterations. Whenever we have a fixed number of iterations we should use a for loop if possible. The 2 following examples behave the same, but the for loop syntax is more concise.
While Loop Syntax
For Loop Syntax
The key difference in for loop syntax is that all loop management code is consolidated in the top parenthesis group. However, when the code runs, each step actually happens in the same order as in the while loop example. These steps are the following.
Declare and initialise counter variable
Evaluate condition
Increment counter
To solidify understanding of loops, we suggest using while loops until you are comfortable with loop mechanics.
Base Exercises
Follow Along
Implement the above code.
Simple Loop with Variations
Create a loop in the
mainfunction. Make the loop run 6 times, adding"hello"tomyOutputValuewith each loop iteration.What happens if
counterstarts as a number other than zero?What happens if, inside the loop, you alter the
counterby adding a number other than one?What happens if you change the condition inside the loop from
counter < 6tocounter <= 6?
Loop within Loop
Create nested loops in the
mainfunction, where the outer loop runs 3 times and the inner loop runs 3 times per outer loop. Concatenate"hello"tomyOutputValuein the inner loop. How many times do we see"hello"?Add
"<br>"tomyOutputValuein the outer loop so that the program makes a new line for each outer loop.What happens if
outerCounterstarts as a number other than zero?What happens if
innerCounterstarts as a number other than zero?What happens if, inside the loop, you alter
outerCounterby adding a number other than one?What happens if, inside the loop, you alter
innerCounterby adding a number other than one?What happens if you change the outer loop condition from
outerCounter < 3toouterCounter <= 3?What happens if you change the inner loop condition from
innerCounter < 3toinnerCounter <= 3?Update loop conditions to use
inputto control how many times the loops run.Update our code such that the inner loop runs twice the number of times as the outer loop. How many more times do we see
"hello"?
Infinite Loop
Make a loop that never stops running. Be prepared to stop / kill this Chrome tab, because it will freeze. We should be able to observe this tab's performance in Windows Task Manager or MacOS Activity Monitor.
Last updated