For in Crystal

# `for` is not a keyword in Crystal. Instead, we use various looping constructs.
# Here are some basic types of loops in Crystal.

# The most basic type, with a single condition.
i = 1
while i <= 3
  puts i
  i += 1
end

# A classic initial/condition/after loop using a Range.
(0..2).each do |j|
  puts j
end

# Another way of accomplishing the basic "do this N times" iteration
# is using a Range with `times`.
3.times do |i|
  puts "range #{i}"
end

# Crystal doesn't have a direct equivalent to Go's infinite `for` loop,
# but we can use `loop do` for similar functionality.
loop do
  puts "loop"
  break
end

# You can also `next` to the next iteration of the loop
# (equivalent to `continue` in other languages).
6.times do |n|
  next if n.even?
  puts n
end

To run the program, save it as for.cr and use the crystal command:

$ crystal for.cr
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Crystal doesn’t have a for keyword like in some other languages. Instead, it provides various looping constructs that achieve similar functionality:

  1. The while loop is used for condition-based loops.
  2. Ranges with each method are used for iterating over a sequence of numbers.
  3. The times method on integers is used for simple repetition.
  4. loop do creates an infinite loop that can be broken out of.
  5. The next keyword is used to skip to the next iteration (similar to continue in other languages).

These constructs provide flexible and expressive ways to create loops in Crystal, covering the same use cases as Go’s for loops.