cairo by example


The loop keyword tells Cairo to execute a block of code over and over again forever (until it runs out of gas) or until you explicitly tell it to stop. This is the only kind of loop for now.

use debug::PrintTrait;

fn main() -> u128 {
    let mut i: u128 = 0;
    loop {
        if i > 9 { // Break condition
            break ();
        // Repeating code
        i = i + 1;

// In order to prevent infinite iteration, we have to explicitly declare the 'available_gas' value
// (The program wont compile and will generate 'out_of_gas' error)
fn test_main() {
    let a = main();
    assert(a == 10, ' incorrect loop value ');

To run the test, use cairo-test filename.cairo or just to run it without testing use cairo-run --single-file --available-gas 200000 filename.cairo.

For further information about this topic, check Cairo-Book.

Try it out!
  1. Install the toolchain:
    • For macOS and Linux, run our script:
    • curl -sL | bash -s 2.2.0
    • For Windows and others, please see the official guide
  2. Run the example:
    1. Copy the example into a loop.cairo file and run with:
    2. %!s(<nil>) loop.cairo

prev (primitive-types) next (constants)