Variables and values · 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 · Trace a changing value
Section titled “1. Exercise · Trace a changing value”Start with price 12 and quantity 2. Increase quantity by 1 and save the total. Increase quantity again, then print the saved total and the new total.
Completion: The lines are 36 and 48; explain why changing quantity does not update the saved total.
Hint: A calculation stores its result at that moment.
2. Build a program · Build a receipt calculator
Section titled “2. Build a program · Build a receipt calculator”Use variables for price 7, quantity 4, and shipping 3. Print subtotal: 28 and total: 31. Also run with quantity 0; no condition is needed yet.
Completion: Quantity 0 gives subtotal 0 and total 3. Use int_to_str when joining numbers to strings.
Hint: Reuse the subtotal when calculating the total.
3. Debug · Choose mutable variables
Section titled “3. Debug · Choose mutable variables”Check the broken program below and fix just the declaration that needs to change.
Start with this deliberately broken program.
fn main() { let quantity = 2; quantity = quantity + 1; println(quantity);}xen check class_mutability.xenDiagnostic excerpt:
cannot assign immutable local 'quantity'Completion: Checking succeeds and output is 3, without redeclaring quantity.
Hint: A name assigned a new value needs let mut.
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.