Code Snippets

This page contains snippets of code demonstrating ideas that are commonly used in Kojo programs. You can refer to this page as needed - while writing Kojo code.

Things to remember:

• anything after // on a line is a comment
• You put a block of code between { and }

#### Sequence

``````// Just write the instructions one line after the other
clear()
forward(100)
right()
forward(100)
// etc```
```

#### Repetition

repeat:

``````repeat (4) {
// for example:
forward(100)
right()
}```
```

for:

``````for (i <- 1 to 4) {
// the counter i is available to be used in your code;
// it ranges from 1 to 4 in this example (as specified above)
// for example:
forward(100 - 10*i)
right(90 + 5*i)
}```
```

#### User defined Commands

``````// definition of a command named square
def square(side: Int) {
repeat(4) {
forward(side)
right()
}
}
clear()
// two different calls to square command
square(100)
square(200)```
```

#### User Defined Calculations (Functions)

``````// definition of a function named sum
def sum(n1: Int, n2: Int) = {
n1 + n2
}
// call to the sum function within print command
print(sum(3, 5))
// another call to the sum function
print(sum(20, 7))```
```

Or:

``````// definition of function
def diagonal(x: Double) = {
math.sqrt(2*x*x)
}
// call to function within print command
print(diagonal(100))```
```

#### Selection

``````// with commands
val size = 50
if (size > 100) {
setFillColor(blue)
}
else {
setFillColor(green)
}
square(100)

// with expressions
val n = 100
val big = if (n > 50) true else false
println(big)```
```