Loops
The loop
keyword tells Cairo to loop and execute a block of code until you explicitly told to to stop.
The while
keyword tells Cairo to loop and execute a block of code as long as a condition is met.
The for
keyword tells Cairo to loop and execute a block of code over for each item in a collection.
Example
fn main() {
let mut res: u8 = 1;
loop {
if res == 5 {
break;
}
res += 1;
};
assert!(res == 5);
while res != 1 {
res -= 1;
};
assert!(res == 1);
for n in 1..5_u8 { // Range of 1 to 5
assert!(res == n);
res += 1;
};
}
You can experiment with this example in cairovm.codes and read more about loops in the Cairo Book. |