Flow and Data
Branches
Choosing a Path
An if statement chooses which block runs. The condition is a logical value computed from current data.
Program
Play the script to watch a score choose the passing branch.
branches.R
Replay: real traced execution (multi-file project)
score <- 82
if (score >= 80) {
grade <- "pass"
} else {
grade <- "retry"
}
cat(grade, "\n", sep = "")
score <- 60
if (score >= 80) {
grade <- "pass"
} else {
grade <- "retry"
}
cat(grade, "\n", sep = "")
score <- 95
if (score >= 80) {
grade <- "pass"
} else {
grade <- "retry"
}
cat(grade, "\n", sep = "")
score ← 82
1score <- 822if (score >= 80) {values this step82scorescore >= 80 ← TRUE
1score <- 822if (score >= 80) {3 grade <- "pass"values this stepTRUEscore >= 8082scoregrade ← pass
2if (score >= 80) {3 grade <- "pass"4} else {values this steppassgradecat(grade, " ", sep = "")
6}7cat(grade, "\n", sep = "")outputpassvalues this steppassgrade
score ← 60
1score <- 602if (score >= 80) {values this step60scorescore >= 80 ← FALSE
1score <- 602if (score >= 80) {3 grade <- "pass"values this stepFALSEscore >= 8060scoregrade ← retry
4} else {5 grade <- "retry"6}values this stepretrygradecat(grade, " ", sep = "")
6}7cat(grade, "\n", sep = "")outputretryvalues this stepretrygrade
score ← 95
1score <- 952if (score >= 80) {values this step95scorescore >= 80 ← TRUE
1score <- 952if (score >= 80) {3 grade <- "pass"values this stepTRUEscore >= 8095scoregrade ← pass
2if (score >= 80) {3 grade <- "pass"4} else {values this steppassgradecat(grade, " ", sep = "")
6}7cat(grade, "\n", sep = "")outputpassvalues this steppassgrade
Choose the Grade
scorestarts at82.score >= 80evaluates toTRUE.- The
ifbranch setsgradetopass. - Lower scores would use the
elsebranch and becomeretry. | Score | Condition | Grade | | --- | --- | --- | |82|TRUE|pass| |60|FALSE|retry|
if
`if (condition)` runs the following block only when the condition is `TRUE`.
comparison
`score >= 80` returns a logical value.
else
`else` gives the fallback path when the condition is `FALSE`.
Exercise: branches.R
Use an if/else branch to print pass for scores at least 80 and retry otherwise