Control flow in Cairo allows you to control the execution path of your programs based on conditions and repetition.
Use if expressions to execute code based on conditions:
let number = 42;
if number > 0 {
println!("Positive number");
} else if number < 0 {
println!("Negative number");
} else {
println!("Zero");
}
if is an expression, so it can return values:
let result = if condition { 5 } else { 10 };
Use loop to repeat code.
A loop runs indefinitely unless you stop it; use break to exit the loop when a condition is met.
let mut counter = 0;
loop {
if counter == 5 {
break;
}
println!("Counter: {}", counter);
counter += 1;
}
Loops can return values using break:
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Returns 20
}
};
Use continue to skip to the next iteration:
let mut i = 0;
loop {
i += 1;
if i % 2 == 0 {
continue; // Skip even numbers
}
if i > 10 {
break;
}
println!("{}", i); // Only prints odd numbers
}
In this exercise you'll help manage a small bakery's daily operations using Cairo's control flow constructs.
Implement calculate_total that calculates the cost of an order based on pastry type and quantity:
calculate_total(Pastry::Croissant, 4) // Returns: 12 (4 * 3)
calculate_total(Pastry::Cookie, 10) // Returns: 10 (10 * 1)
Implement apply_discount that applies discounts based on order total.
Apply the percentage discount to the total, then round down to the nearest whole coin (floor).
apply_discount(25) // Returns: 22
apply_discount(15) // Returns: 14
apply_discount(8) // Returns: 8
Implement baking_schedule that creates a daily baking plan.
The bakery bakes in batches of 5 orders per hour:
baking_schedule(18) // Returns: [5, 5, 5, 3] (3 full batches + 3 remaining)
baking_schedule(10) // Returns: [5, 5] (2 full batches)
baking_schedule(3) // Returns: [3] (1 partial batch)
Use appropriate control flow constructs (if/else, loop) to solve each problem efficiently.
Sign up to Exercism to learn and master Cairo with 25 concepts68 exercises, and real human mentoring, all for free.