View Subcategory

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
fantom
x := 1
while (x < 150) {
Env.cur.out.print("$x,")
x *= 2
}
echo

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
fantom
rnd := 0
while(rnd != 6) {
rnd = Int.random(1..6)
Env.cur.out.print(rnd)
if (rnd != 6)
Env.cur.out.print(",")
}
echo

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
fantom
5.times { Env.cur.out.print("Hello") }
for (i := 0; i < 5; i++)
Env.cur.out.print("Hello")
(1..5).each { Env.cur.out.print("Hello") }

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
fantom
(10..1).each { Env.cur.out.print("$it .. ") }
Env.cur.out.print("Liftoff!")
for (i := 10; i >= 1; i--)
Env.cur.out.print("$i .. ")
Env.cur.out.print("Liftoff!")