Repetition Logic
Executing a set of statements for a specified number of times or while a condition is true—using R, Python, and Julia.
In computer programming, loops mirror everyday repetitive tasks. Just as a washing machine cycles clothes until they’re clean, for
loops iterate through data, much like scrubbing each element. Similarly, while
loops repeatedly execute until a condition is met, akin to reading a book’s pages sequentially until all chapters are finished. And when a chef tastes a dish and adjusts flavors, it echoes a do-while
loop—ensuring the recipe’s quality.
These loops streamline tasks, systematically repeating actions until completion or satisfaction, and reflecting the essence of both programming logic and real-world routines. Let’s dive into this computer science (CS) 101 concept that you will use (and reuse) in almost all your code, in most computer programming languages.
2002 NCAA Men’s Basketball Final Top 25 Ranking
Nearly ten years after the original post, the University of Maryland’s men’s basketball team secured victory in the 2002 NCAA national championship—a memorable achievement! Let’s explore different forms of repetition logic using the 2002 final Top 25 rankings.
FINAL_NCAA_MBB_2002_R <- c(
"Maryland",
"Kansas",
"Indiana",
"Oklahoma",
"Duke",
"Oregon",
"UConn",
"Cincinnati",
"Pittsburgh",
"Arizona",
"Illinois",
"Kent State",
"Kentucky",
"Alabama",
"Missouri",
"Gonzaga",
"Ohio State",
"Marquette",
"Texas",
"UCLA",
"Mississippi State",
"Southern Illinois",
"Florida",
"Xavier",
"NC State"
)
typeof(FINAL_NCAA_MBB_2002_R)
[1] "character"
FINAL_NCAA_MBB_2002_R[1]
[1] "Maryland"
length(FINAL_NCAA_MBB_2002_R)
[1] 25
FINAL_NCAA_MBB_2002_PY = [
"Maryland",
"Kansas",
"Indiana",
"Oklahoma",
"Duke",
"Oregon",
"UConn",
"Cincinnati",
"Pittsburgh",
"Arizona",
"Illinois",
"Kent State",
"Kentucky",
"Alabama",
"Missouri",
"Gonzaga",
"Ohio State",
"Marquette",
"Texas",
"UCLA",
"Mississippi State",
"Southern Illinois",
"Florida",
"Xavier",
"NC State"
]
type(FINAL_NCAA_MBB_2002_PY)
<class 'list'>
FINAL_NCAA_MBB_2002_PY[0] # Zero-based array indexing
'Maryland'
len(FINAL_NCAA_MBB_2002_PY)
25
const FINAL_NCAA_MBB_2002_JL = [
"Maryland",
"Kansas",
"Indiana",
"Oklahoma",
"Duke",
"Oregon",
"UConn",
"Cincinnati",
"Pittsburgh",
"Arizona",
"Illinois",
"Kent State",
"Kentucky",
"Alabama",
"Missouri",
"Gonzaga",
"Ohio State",
"Marquette",
"Texas",
"UCLA",
"Mississippi State",
"Southern Illinois",
"Florida",
"Xavier",
"NC State"
];
typeof(FINAL_NCAA_MBB_2002_JL)
Array{String,1}
FINAL_NCAA_MBB_2002_JL[1]
"Maryland"
length(FINAL_NCAA_MBB_2002_JL)
25
For
Loop
A for
loop iterates through the top 25 list in reverse order, starting at 25 and ending at 1. For each iteration, it processes the current item, ranks it, and then moves to the next, ensuring all items are ranked sequentially from 25 down to 1.
for (i in length(FINAL_NCAA_MBB_2002_R):1) {
if (i == 1) {
cat("And your 2002 national champions... ")
}
cat(paste("#", i, "-", FINAL_NCAA_MBB_2002_R[i]), "\n")
}
# 25 - NC State
# 24 - Xavier
# 23 - Florida
# 22 - Southern Illinois
# 21 - Mississippi State
# 20 - UCLA
# 19 - Texas
# 18 - Marquette
# 17 - Ohio State
# 16 - Gonzaga
# 15 - Missouri
# 14 - Alabama
# 13 - Kentucky
# 12 - Kent State
# 11 - Illinois
# 10 - Arizona
# 9 - Pittsburgh
# 8 - Cincinnati
# 7 - UConn
# 6 - Oregon
# 5 - Duke
# 4 - Oklahoma
# 3 - Indiana
# 2 - Kansas
And your 2002 national champions... # 1 - Maryland
for i in range(len(FINAL_NCAA_MBB_2002_PY), 0, -1):
if i == 1:
print("And your 2002 national champions... ", end = "")
print("#" + str(i) + " - ", end = "")
print(FINAL_NCAA_MBB_2002_PY[i - 1])
#25 - NC State
#24 - Xavier
#23 - Florida
#22 - Southern Illinois
#21 - Mississippi State
#20 - UCLA
#19 - Texas
#18 - Marquette
#17 - Ohio State
#16 - Gonzaga
#15 - Missouri
#14 - Alabama
#13 - Kentucky
#12 - Kent State
#11 - Illinois
#10 - Arizona
#9 - Pittsburgh
#8 - Cincinnati
#7 - UConn
#6 - Oregon
#5 - Duke
#4 - Oklahoma
#3 - Indiana
#2 - Kansas
And your 2002 national champions... #1 - Maryland
for i in reverse(1:length(FINAL_NCAA_MBB_2002_JL))
if i == 1
print("And your 2002 national champions... ")
end
println("#$i - ", FINAL_NCAA_MBB_2002_JL[i])
end
#25 - NC State
#24 - Xavier
#23 - Florida
#22 - Southern Illinois
#21 - Mississippi State
#20 - UCLA
#19 - Texas
#18 - Marquette
#17 - Ohio State
#16 - Gonzaga
#15 - Missouri
#14 - Alabama
#13 - Kentucky
#12 - Kent State
#11 - Illinois
#10 - Arizona
#9 - Pittsburgh
#8 - Cincinnati
#7 - UConn
#6 - Oregon
#5 - Duke
#4 - Oklahoma
#3 - Indiana
#2 - Kansas
And your 2002 national champions... #1 - Maryland
While
Loop
The while
loop is a repetition logic that runs while a condition remains true
. It’s, therefore, crucial to ensure that the condition eventually becomes false
to prevent infinite loops.
Unlike the for
loop, which works with a known number of iterations, the while
loop is more flexible and suitable when the iteration count isn’t predetermined. It’s, therefore, not the most efficient repetition logic for this particular task of generating a JSON output.
rankings <- 1:25
index <- 1
cat("// JSON output", "\n")
// JSON output
cat("{", "\n")
{
while (index <= length(FINAL_NCAA_MBB_2002_R)) {
cat(sprintf(' "rank": %d, "team": "%s",', rankings[index], FINAL_NCAA_MBB_2002_R[index]), '\n')
index <- index + 1 # Incremental operation to prevent infinite loops
}
"rank": 1, "team": "Maryland",
"rank": 2, "team": "Kansas",
"rank": 3, "team": "Indiana",
"rank": 4, "team": "Oklahoma",
"rank": 5, "team": "Duke",
"rank": 6, "team": "Oregon",
"rank": 7, "team": "UConn",
"rank": 8, "team": "Cincinnati",
"rank": 9, "team": "Pittsburgh",
"rank": 10, "team": "Arizona",
"rank": 11, "team": "Illinois",
"rank": 12, "team": "Kent State",
"rank": 13, "team": "Kentucky",
"rank": 14, "team": "Alabama",
"rank": 15, "team": "Missouri",
"rank": 16, "team": "Gonzaga",
"rank": 17, "team": "Ohio State",
"rank": 18, "team": "Marquette",
"rank": 19, "team": "Texas",
"rank": 20, "team": "UCLA",
"rank": 21, "team": "Mississippi State",
"rank": 22, "team": "Southern Illinois",
"rank": 23, "team": "Florida",
"rank": 24, "team": "Xavier",
"rank": 25, "team": "NC State",
cat("}")
}
rankings = list(range(1, 26))
index = 0
print("// JSON output")
// JSON output
print("{")
{
while index < len(FINAL_NCAA_MBB_2002_PY):
print(f' "rank": {rankings[index]}, "team": "{FINAL_NCAA_MBB_2002_PY[index]}",')
index += 1 # Incremental operation to prevent infinite loops
"rank": 1, "team": "Maryland",
"rank": 2, "team": "Kansas",
"rank": 3, "team": "Indiana",
"rank": 4, "team": "Oklahoma",
"rank": 5, "team": "Duke",
"rank": 6, "team": "Oregon",
"rank": 7, "team": "UConn",
"rank": 8, "team": "Cincinnati",
"rank": 9, "team": "Pittsburgh",
"rank": 10, "team": "Arizona",
"rank": 11, "team": "Illinois",
"rank": 12, "team": "Kent State",
"rank": 13, "team": "Kentucky",
"rank": 14, "team": "Alabama",
"rank": 15, "team": "Missouri",
"rank": 16, "team": "Gonzaga",
"rank": 17, "team": "Ohio State",
"rank": 18, "team": "Marquette",
"rank": 19, "team": "Texas",
"rank": 20, "team": "UCLA",
"rank": 21, "team": "Mississippi State",
"rank": 22, "team": "Southern Illinois",
"rank": 23, "team": "Florida",
"rank": 24, "team": "Xavier",
"rank": 25, "team": "NC State",
print("}")
}
rankings = 1:25
1:25
index = 1
1
println("// JSON output")
// JSON output
println("{")
{
while index <= length(FINAL_NCAA_MBB_2002_JL)
println(" \"rank\": ", rankings[index], ", \"team\": \"", FINAL_NCAA_MBB_2002_JL[index], "\",")
global index += 1 # Incremental operation to prevent infinite loops
end
"rank": 1, "team": "Maryland",
"rank": 2, "team": "Kansas",
"rank": 3, "team": "Indiana",
"rank": 4, "team": "Oklahoma",
"rank": 5, "team": "Duke",
"rank": 6, "team": "Oregon",
"rank": 7, "team": "UConn",
"rank": 8, "team": "Cincinnati",
"rank": 9, "team": "Pittsburgh",
"rank": 10, "team": "Arizona",
"rank": 11, "team": "Illinois",
"rank": 12, "team": "Kent State",
"rank": 13, "team": "Kentucky",
"rank": 14, "team": "Alabama",
"rank": 15, "team": "Missouri",
"rank": 16, "team": "Gonzaga",
"rank": 17, "team": "Ohio State",
"rank": 18, "team": "Marquette",
"rank": 19, "team": "Texas",
"rank": 20, "team": "UCLA",
"rank": 21, "team": "Mississippi State",
"rank": 22, "team": "Southern Illinois",
"rank": 23, "team": "Florida",
"rank": 24, "team": "Xavier",
"rank": 25, "team": "NC State",
println("}")
}
Summary
Repetition logic (commonly known as loops in programming) allows us to execute statements multiple times. There are three main types of loops: The for
loop is a fixed-count loop that runs a specific number of times based on an initialization step, a condition, and an alteration step, making it ideal for iterating over a range of values or sequences. The while
loop repeatedly runs its statements as long as a specified condition remains true
, making it useful when the number of iterations isn’t predetermined. The do-while
loop executes its body at least once before checking the condition; if the condition remains true
, it continues to repeat, commonly used for menu-driven programs or situations where at least one iteration is needed.
In DRY (Don’t Repeat Yourself) programming philosophy, repetition logic allows for efficient execution of repeated tasks—reducing redundancy and enhancing code maintainability.
Appendix A: Environment, Language Versions, and Coding Style
If you are interested in reproducing this work, here are the versions of R, Python, and Julia that I used. Additionally, my coding style here is verbose, in order to trace back where functions/methods and variables are originating from, and make this a learning experience for everyone—including me.
cat(
R.version$version.string, "-", R.version$nickname,
"\nOS:", Sys.info()["sysname"], R.version$platform,
"\nCPU:", benchmarkme::get_cpu()$no_of_cores, "x", benchmarkme::get_cpu()$model_name
)
R version 3.6.0 (2019-04-26) - Planting of a Tree
OS: Darwin x86_64-apple-darwin15.6.0
CPU: 4 x Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
import sys
import platform
import os
import cpuinfo
print(
"Python", sys.version,
"\nOS:", platform.system(), platform.platform(),
"\nCPU:", os.cpu_count(), "x", cpuinfo.get_cpu_info()["brand"]
)
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 20:42:06)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
OS: Darwin Darwin-19.6.0-x86_64-i386-64bit
CPU: 4 x Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
using InteractiveUtils
InteractiveUtils.versioninfo()
Julia Version 1.2.0
Commit c6da87ff4b (2019-08-20 00:03 UTC)
Platform Info:
OS: macOS (x86_64-apple-darwin18.6.0)
CPU: Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-6.0.1 (ORCJIT, ivybridge)
Further Readings
- Grolemund, G. (2014). Hands-On Programming with R: Write Your Own Functions and Simulations. O’Reilly.
- Kalicharan, N. (2021). Julia—Bit by Bit: Programming for Beginners. Springer. https://doi.org/10.1007/978-3-030-73936-2
- Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language (2nd ed.). Pearson.
- Lutz, M. (2013). Learning Python (5th ed.). O’Reilly.
- Wickham, H. (2019). Advanced R (2nd ed.). CRC. https://doi.org/10.1201/9781351201315