Difference between revisions of "W1154 For Loop"

From Coder Merlin
m (Merlin moved page W1152 For Loop to W1154 For Loop without leaving a redirect)
 
(28 intermediate revisions by 3 users not shown)
Line 2: Line 2:
== Prerequisites ==
== Prerequisites ==
* [[W1151 Conditional and Flow Chart]]
* [[W1151 Conditional and Flow Chart]]
* [[W1152 While Loop]]
* [[W1153 Repeat-While Loop]]
== Introduction ==
== Introduction ==
Loops are the general term for ''executing a defined segment of code zero or more times'', where the number of iterations is dependent upon test conditions within the loop.  The '''for loop''' is a construct which enables us to execute a segment of code a ''defined number'' of times.  It is thus the most appropriate choice when we know in advance how to calculate the number of iterations prior to beginning the loop.  While this construct is not strictly necessary, it provides [[Glossary#Syntactic_Sugar|syntactic sugar]] by clarifying intent.
The '''for loop''' is a construct which enables us to execute a segment of code a ''defined number'' of times.  It is thus the most appropriate choice when we know in advance how to calculate the number of iterations prior to beginning the loop.  While this construct is not strictly necessary, it provides {{GlossaryReference|Syntactic_Sugar|syntactic sugar}} by clarifying intent.
 
== For Loops ==
'''for loops''' execute for a defined count of iterations, as such, the ''test condition'' is implied within the definition.  Through each iteration, a ''loop control variable'' is adjusted toward its final goal.  When that goal is reached, the loop exits.
 
Both '''while''' and '''repeat-while''' loops require the ''explicit definition'' of a '''loop control variable''' which must be ''explicitly incremented'' (or otherwise adjusted) and ''explicitly checked'' each time through the loop to determine if the loop has completed. In contrast, a '''for loop''' handles this work for us ''implicitly'' by defining the loop control variable, incrementing (or otherwise adjusting) it automatically, and checking for the completion condition.
 
'''The actual implementation is identical to that of a ''while loop''.'''
 
== Intervals ==
Assume two numbers, '''a''' and '''b''', such that '''b > a'''.  An '''interval''' is the set of numbers lying between these two numbers.  Both '''a''' and '''b''' are the endpoints of the interval, the '''lower bound''' and the '''upper bound''' respectively.  An '''open interval''' does not include either of the endpoints, a '''half-open interval''' include just one of its endpoints, while a '''closed interval''' includes both of its endpoints.
 
=== Interval Notation ===
{| class="wikitable" style="text-align: center;"
! Notation !! Interpretation !! Description
|-
| (a, b) || a < x < b || An open interval; both endpoints are excluded.
|-
| (a, b] || a < x ≤ b || A half-open interval; the lower bound is excluded. 
|-
| [a, b) || a ≤ x < b || A half-open interval; the upper bound is excluded.
|-
| [a, b] || a ≤ x ≤ b || A closed interval; both endpoints are included.
|}
 
=== Interval Classifications ===
An '''empty interval''' has no elements.  Examples include: 
* (b, a), (b, a], [b, a), [b, a]
* (a, a), (a, a], [a, a)
 
A '''degenerate interval''' has a single element.  An example is:
* [a, a]
 
== Swift For Loops ==
Because iterating over a discrete interval is very common, Swift supports several different ways of implementing '''for loops'''. 
 
=== Swift Ranges ===
A range in Swift represents either a closed interval or a half-open interval.  In both cases, one may iterate of the range.
 
==== ClosedRange ====
A '''ClosedRange''' includes both the lower bound and the upper bound.  It's written using '''...''' between the lower and upper bounds.  For example, the equivalent of [4, 7] is:
<syntaxhighlight lang="swift">
4 ... 7
</syntaxhighlight>
 
An example of a loop using a ClosedRange is:
<syntaxhighlight lang="swift">
for x in lowerBound...upperBound {
    print(x);
}
</syntaxhighlight>
 
==== Range ====
A '''Range''' includes the lower bound but excludes the upper bound. It's written using '''..<''' between the lower and upper bounds.  For example,  the equivalent of [4, 7) is:
<syntaxhighlight lang="swift">
4 ..< 7
</syntaxhighlight>
 
An example of a loop using a Range is:
<syntaxhighlight lang="swift">
for x in lowerBound..<upperBound {
    print(x);
}
</syntaxhighlight>
 
=== Swift Strides ===
A '''stride''' in Swift represents either a sequence based upon a closed interval or a half-open interval.


== General Loop ==
==== Closed Stride ====
[[File:General Loop - No Test.png|thumb|right|link=|General Loop]]
A '''closed stride''' includes the lower bound and ''may'' include the upper bound, stepping as specifiedIt uses the keyword '''through''' for the upper bound and is written as ''stride(from:4, '''through''':7, by:1)''.
In the case of a general loop, we can see that the three statements in the figure on the right will be repeated.  However, without a '''test condition''' this loop would theoretically execute forever and is formally termed an '''infinite loop'''.  To be useful, a ''test condition'' is required in order to inform the CPU when the loop should be exited.  Thus, loops generally have two distinct parts: 
* A '''test condition''' which informs the CPU when the loop should exit
* A '''body''' which is the code which is repeated for each iteration of the loop
<br clear='all'/>


== For Loops ==
An example of a loop using a closed stride is:
''for loops'' execute for a defined count of iterations, as such, the ''test condition'' is implied within the definition. Through each iteration, a ''loop control variable'' is adjusted toward its final goalWhen that goal is reached, the loop exits.
<syntaxhighlight lang="swift">
for x in stride(from:lowerBound, through:upperBound, by:1) {
    print(x);
}
</syntaxhighlight>
 
==== Half-Open Stride ====
A '''half-open stride''' includes the lower bound but excludes the upper bound, stepping as specified.  It uses the keyword '''to''' for the upper bound and is written as ''stride(from:4, '''to''':7, by:1)''.
 
An example of a loop using a half-open stride is:
<syntaxhighlight lang="swift">
for x in stride(from:lowerBound, to:upperBound, by:1) {
    print(x)
}
</syntaxhighlight>
 
==== Stride By ====
Strides do not necessarily have to increment '''by''' 1; '''by''' can be any arbitrary value. A positive stride iterates upward; a negative stride iterates downward.  One advantage of strides is that they may use floating point values.
 
== The Special Meaning of "_", or I Don't Care ==
Sometimes, we don't care about the value of a variableFor example, there are occasions where we want to execute something a certain number of times but we don't need to keep track of the specific iteration.  The <code>_</code> (underscore) character is intended for this purpose.


For example, if we want to print "Hello, World!" exactly one hundred times, we could type the following:
<syntaxhighlight lang="swift">
for _ in 1 ... 100 {
    print("Hello, World!")
}
</syntaxhighlight>


{{Caution|
== Key Concepts ==
Each iteration of the loop '''must''' perform some action, albeit slight, to move the loop closer to completionIf this does not occur, the loop would execute an infinite number of times.
{{KeyConcepts|
* The '''for loop''' is a construct which enables us to execute a segment of code a ''defined number'' of times.
** Both while and repeat-while loops require the ''explicit definition'' of a loop control variable which must be ''explicitly adjusted'' and ''explicitly checked'' each time through the loop.  In contrast, a for loop handles this work ''implicitly''.
** The actual implementation is identical to that of a while loop.
* '''Intervals''': Assume two numbers, a and b, such that b > a. An '''interval''' is the set of numbers lying between these two numbers.
** Both a and b are the endpoints of the interval, the '''lower bound''' and the '''upper bound''' respectively.
** An '''open interval''' does not include either of the endpoints
** A '''half-open interval''' include just one of its endpoints
** A '''closed interval''' includes both of its endpoints
** An '''empty interval''' has no elements
** A '''degenerate interval''' has a single element
* Swift defines two range types:
** A '''ClosedRange''' includes both the lower bound and the upper bound and is written using '''...'''
** A '''Range''' include the lower bound but excludes the upper bound and is written using '''..<'''
** A ''half-open stride'' includes the lower bound and ''may'' include the upper bound and is written using '''stride(from:a, to:b, by:s)'''
** A ''closed stride'' includes the lower bound and ''may'' include the upper bound and is written using '''stride(from:a, through:b, by:s)'''
}}
}}


== Key Concepts ==
{{ComingSoon|
M1154-20 requires understanding of functions described in W1205.  Therefore, that unit should be moved earlier and then M1154-20 into that unit.}}
 
== Exercises ==
== Exercises ==
{{Exercises|
* {{MMMAssignment|M1154-10}}
* {{MMMAssignment|M1154-20}}
* {{Assignment|X1154}} Using Draw.IO create a single XML file named "Flowcharts.drawio" with one page for each flowchart below.  Create a new subdirectory, J1154, in your Journals directory. Upload the file to the directory via SFTP. Be sure to push the file to your GitHub repository.  When done, tag the repository as J1154.Final.
*# Finding the greatest number of three
*# Finding the GCD of two numbers using Euclid's Algorithm
*# Determining whether or not a number is prime
}}
== References ==
== References ==
* [https://developer.apple.com/documentation/swift/range Range] (Swift Documentation)
* [https://developer.apple.com/documentation/swift/closedrange ClosedRange] (Swift Documentation)
* [https://developer.apple.com/documentation/swift/1641347-stride Half-Open Stride] (Swift Documentation)
* [https://developer.apple.com/documentation/swift/1641185-stride Closed Stride] (Swift Documentation)
* [https://en.wikipedia.org/wiki/Interval_(mathematics) Interval] (Wikipedia)

Latest revision as of 18:25, 27 November 2021

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Roller Coaster Loop

Prerequisites[edit]

Introduction[edit]

The for loop is a construct which enables us to execute a segment of code a defined number of times. It is thus the most appropriate choice when we know in advance how to calculate the number of iterations prior to beginning the loop. While this construct is not strictly necessary, it provides syntactic sugar by clarifying intent.

For Loops[edit]

for loops execute for a defined count of iterations, as such, the test condition is implied within the definition. Through each iteration, a loop control variable is adjusted toward its final goal. When that goal is reached, the loop exits.

Both while and repeat-while loops require the explicit definition of a loop control variable which must be explicitly incremented (or otherwise adjusted) and explicitly checked each time through the loop to determine if the loop has completed. In contrast, a for loop handles this work for us implicitly by defining the loop control variable, incrementing (or otherwise adjusting) it automatically, and checking for the completion condition.

The actual implementation is identical to that of a while loop.

Intervals[edit]

Assume two numbers, a and b, such that b > a. An interval is the set of numbers lying between these two numbers. Both a and b are the endpoints of the interval, the lower bound and the upper bound respectively. An open interval does not include either of the endpoints, a half-open interval include just one of its endpoints, while a closed interval includes both of its endpoints.

Interval Notation[edit]

Notation Interpretation Description
(a, b) a < x < b An open interval; both endpoints are excluded.
(a, b] a < x ≤ b A half-open interval; the lower bound is excluded.
[a, b) a ≤ x < b A half-open interval; the upper bound is excluded.
[a, b] a ≤ x ≤ b A closed interval; both endpoints are included.

Interval Classifications[edit]

An empty interval has no elements. Examples include:

  • (b, a), (b, a], [b, a), [b, a]
  • (a, a), (a, a], [a, a)

A degenerate interval has a single element. An example is:

  • [a, a]

Swift For Loops[edit]

Because iterating over a discrete interval is very common, Swift supports several different ways of implementing for loops.

Swift Ranges[edit]

A range in Swift represents either a closed interval or a half-open interval. In both cases, one may iterate of the range.

ClosedRange[edit]

A ClosedRange includes both the lower bound and the upper bound. It's written using ... between the lower and upper bounds. For example, the equivalent of [4, 7] is:

4 ... 7

An example of a loop using a ClosedRange is:

for x in lowerBound...upperBound {
    print(x);
}

Range[edit]

A Range includes the lower bound but excludes the upper bound. It's written using ..< between the lower and upper bounds. For example, the equivalent of [4, 7) is:

4 ..< 7

An example of a loop using a Range is:

for x in lowerBound..<upperBound {
    print(x);
}

Swift Strides[edit]

A stride in Swift represents either a sequence based upon a closed interval or a half-open interval.

Closed Stride[edit]

A closed stride includes the lower bound and may include the upper bound, stepping as specified. It uses the keyword through for the upper bound and is written as stride(from:4, through:7, by:1).

An example of a loop using a closed stride is:

for x in stride(from:lowerBound, through:upperBound, by:1) {
    print(x);
}

Half-Open Stride[edit]

A half-open stride includes the lower bound but excludes the upper bound, stepping as specified. It uses the keyword to for the upper bound and is written as stride(from:4, to:7, by:1).

An example of a loop using a half-open stride is:

for x in stride(from:lowerBound, to:upperBound, by:1) {
    print(x)
}

Stride By[edit]

Strides do not necessarily have to increment by 1; by can be any arbitrary value. A positive stride iterates upward; a negative stride iterates downward. One advantage of strides is that they may use floating point values.

The Special Meaning of "_", or I Don't Care[edit]

Sometimes, we don't care about the value of a variable. For example, there are occasions where we want to execute something a certain number of times but we don't need to keep track of the specific iteration. The _ (underscore) character is intended for this purpose.

For example, if we want to print "Hello, World!" exactly one hundred times, we could type the following:

for _ in 1 ... 100 {
    print("Hello, World!")
}

Key Concepts[edit]

Key ConceptsKeyConceptsIcon.png
  • The for loop is a construct which enables us to execute a segment of code a defined number of times.
    • Both while and repeat-while loops require the explicit definition of a loop control variable which must be explicitly adjusted and explicitly checked each time through the loop. In contrast, a for loop handles this work implicitly.
    • The actual implementation is identical to that of a while loop.
  • Intervals: Assume two numbers, a and b, such that b > a. An interval is the set of numbers lying between these two numbers.
    • Both a and b are the endpoints of the interval, the lower bound and the upper bound respectively.
    • An open interval does not include either of the endpoints
    • A half-open interval include just one of its endpoints
    • A closed interval includes both of its endpoints
    • An empty interval has no elements
    • A degenerate interval has a single element
  • Swift defines two range types:
    • A ClosedRange includes both the lower bound and the upper bound and is written using ...
    • A Range include the lower bound but excludes the upper bound and is written using ..<
    • A half-open stride includes the lower bound and may include the upper bound and is written using stride(from:a, to:b, by:s)
    • A closed stride includes the lower bound and may include the upper bound and is written using stride(from:a, through:b, by:s)
ComingSoonIcon.png
Coming Soon
M1154-20 requires understanding of functions described in W1205. Therefore, that unit should be moved earlier and then M1154-20 into that unit.

Exercises[edit]

ExercisesExercisesIcon.png
  •  M1154-10  Complete  Merlin Mission Manager  Mission M1154-10.
  •  M1154-20  Complete  Merlin Mission Manager  Mission M1154-20.
  •  X1154  Using Draw.IO create a single XML file named "Flowcharts.drawio" with one page for each flowchart below. Create a new subdirectory, J1154, in your Journals directory. Upload the file to the directory via SFTP. Be sure to push the file to your GitHub repository. When done, tag the repository as J1154.Final.
    1. Finding the greatest number of three
    2. Finding the GCD of two numbers using Euclid's Algorithm
    3. Determining whether or not a number is prime

References[edit]