University of Sydney · FACULTY OF ENGINEERING

CIVL6001 Chap.8 Conditions, Loops and Reproducible Checks

- one subject, every graph, every model, every mark
6 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 8 of 8 · CIVL6001

Conditions, Loops and Reproducible Checks

Conditions translate engineering rules into explicit logical tests, while loops repeat a visible operation across a sequence. Reliable control flow begins with an initial state, handles missing values, updates one result and verifies termination. R may recycle unequal vectors or complete an incorrect loop without stopping, so successful execution must be paired with independent checks and deliberate failure cases.

An if statement should express mutually exclusive branches, including exact boundary values and missing inputs. The order of tests matters because a broad condition can capture values intended for a later branch. A loop needs an initial state, a sequence or stopping rule, an update and a result whose meaning remains stable after every iteration.

Counters should be initialised outside the loop, and while loops require both a tolerance and a maximum iteration guard so failure to converge cannot continue indefinitely. Climate datasets add alignment hazards. R can recycle a shorter vector during arithmetic, producing output with only a warning, while trimming records to equal length can silently pair the wrong timestamps.

Explicit length checks and joins on stable keys protect the physical correspondence of measurements. Verification should use a second method with different failure modes, such as comparing a loop count with a vectorised logical sum. Agreement increases confidence but does not prove semantic correctness, because both methods can share the wrong units or threshold.

Deliberate failure cases make protections observable: insert a missing value, duplicated timestamp, negative measurement or unequal vector and confirm that the script stops or reports the intended branch. Code is complete only when normal cases, boundaries and expected failures have been exercised. This approach turns control flow into a transparent statement of the engineering rule and its limits.

In this chapter

What this chapter covers

  • 01

    if and else branches

  • 02

    logical boundaries

  • 03

    loop initialisation

  • 04

    counters and accumulators

  • 05

    vector length safety

  • 06

    negative controls and assertions

Worked example · free

Count heat threshold exceedances

Q [5 marks]. This original practice weighting is not a University mark allocation. Temp contains 35, 39, 41, NA and 37. Count observed values above 38 with a loop and verify the result.
Condition and loop flowA value is tested, sent down one branch and then accumulated until the sequence ends.next valuecondition?update resultflag valuetruefalse
Each value is tested against one explicit condition, routed to an update or flag, and returned to the sequence until the dataset is exhausted.
  • 1Initialise count at zero.
  • 1Loop across each value.
  • 1Handle missingness explicitly.
  • 1Return a count of two.
  • 1Verify with a vectorised sum.
The loop counts 39 and 41, giving two exceedances among four observed values. One of five scheduled observations is missing. A vectorised logical sum should produce the same count.
Sia tip — Initialise outside the loop and compare the final result with an independent expression.
Glossary

Key terms

Conditional branch
A code path selected by the truth value of an explicit logical test.
Accumulator
An object updated across loop iterations to store a running result.
Negative control
A deliberate failure case used to prove that a validation check is active.
FAQ

Conditions, Loops and Reproducible Checks FAQ

When is a loop useful in R?

A loop is useful when repeated state changes or bespoke checks need to remain visible. Vectorised code may be shorter, but a clear loop can be easier to audit for cumulative calculations and teaching examples.

Why is vector recycling risky?

R can repeat a shorter vector during arithmetic and still return numbers. Climate records should normally be aligned by explicit timestamps and keys. Recycling does not prove that rows refer to the same observations.

What proves that code is correct?

No single successful run proves correctness. Use small known cases, independent calculations, assertions, expected failures, length checks and range checks. Verification should test both the numerical result and the engineering meaning of the operation.

Study strategy

Exam move

Write every control flow exercise as a contract before coding: initial state, input sequence, condition, update, termination and independent check. Begin with a sign classifier and make the positive, zero, negative and missing branches mutually exclusive. Test the exact boundary values rather than only obvious examples. Then recreate the threshold counter with the five element temperature vector.

Initialise the counter outside the loop, handle missingness before comparison and retain the indices of exceedances as well as the total. Verify the answer with a vectorised logical sum. Explain why agreement is useful and why it still does not prove correctness for every future input. Create an unequal length vector example and observe R recycling the shorter vector. Replace that behaviour with an explicit length check.

For real time series, align records by timestamp or another stable key rather than trimming both vectors to the same size, because a missing row in the middle can shift every later pair. Revisit the Week 2 π approximation as an iteration problem. Write the tolerance, maximum iteration count and known reference before starting. Inspect whether the sequence converges, oscillates or stops for the wrong reason.

A small numerical change is not proof that the formula or units are correct. Add one deliberate failure to each script: an NA, a negative sensor value, a duplicated key or a vector of the wrong length. Confirm that the assertion or branch produces the expected message. These negative controls show that protection is active. For oral revision, explain a loop without reading code.

State what remains true after each iteration, what the counter represents and how termination is guaranteed. Finish by comparing the loop result with an independent method and by printing enough detail to investigate discrepancies. The recurring lesson is that code which returns a number has completed execution; an engineering result is accepted only after its boundaries, units and verification checks also pass.

A+Everything unlocked
Unlocks this Bible + all 202 of your University of Sydney subjects - and 1,000+ Bibles across every Australian university.
Sia - your CIVL6001 tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works
CIVL6001 · Civil Engineering in a Changing Climate - independent study guide on the AskSia Library. More University of Sydney subjects · Microeconomics across all universities