Control Flow
In ordinary code, execution runs sequentially from top to bottom. Control flow allows you to alter this based on conditions and repeat tasks.
If Statement
Section titled “If Statement”The if statement allows you branch your code depending on conditions. It consists of the if keyward, a condition expression in parentheses and the body.
if (a > 0) { print("positive")}It can optionally include an else branch:
if (a > 0) { print("positive")} else { print("non-positive")}By using another if statement as the body of the else branch, we can achieve else-if:
if (a > 0) { print("positive")} else if (a < 0) { print("negative")}While Loop
Section titled “While Loop”The while loop repeatedly execute a piece of code as long as the condition is evaluated to true.
var n = 10while (n > 0) { n--}For Loop
Section titled “For Loop”The for loop iterate through a collection:
fn sum(a: int[]) -> int { var sum = 0 for (i in a) { sum += i } return sum}It can also iterate over a range:
fn factorial(n: int) -> int { var f = n for (i in 1...n) { f *= i } return f}The 1...n is a range expression starting with and 1 and ends with n (exclusive).