Functions and control flow · Coding Class
This topic is not available in the selected language or version. Showing the start of this section.
Apply the chapter in three steps: an exercise, a program project, and a debugging task. Implement first, then consult the hints and completion criteria. Use a separate file or working directory for each task.
1. Exercise · Check a range endpoint
Section titled “1. Exercise · Check a range endpoint”Sum 1..5, compare with 1..6, and also run 5..5.
Completion: The totals are 10, 15, and 0.
Hint: The endpoint is excluded.
2. Build a program · Build an even-number total
Section titled “2. Build a program · Build an even-number total”Write sum_even(limit: Int) -> Int to sum even numbers from zero up to, but excluding, limit. Print calls with 7, 1, and 0.
Completion: Output is 12, 0, 0. Keep calculation in the function and calls/output in main.
Hint: Select even numbers with number % 2 == 0.
3. Debug · Fix a missing return path
Section titled “3. Debug · Fix a missing return path”The positive function below does not return for every input. Make all paths return a Bool.
Start with this deliberately broken program.
fn positive(value: Int) -> Bool { if value > 0 { return true; }}fn main() { println(positive(0)); }xen check class_return.xenDiagnostic excerpt:
function 'positive' may fall through without returning a valueCompletion: Inputs 1, 0, and -1 yield true, false, and false.
Hint: Return false after the if, or return from an else branch.
Verify and record
Section titled “Verify and record”Use xen check file.xen followed by xen run file.xen for ordinary programs; use xen test file.xen for test-only files. Record the original error, its cause, and the corrected result, then rerun every input in the completion criteria.