Loops

Examples in V
// V has only one looping construct: for.
numbers := [1, 2, 3, 4, 5]
for num in numbers {
	println(num)
}
names := ['Sam', 'Peter']
for i, name in names {
	println('$i) $name')  // Output: 0) Sam
}                         //         1) Peter

// The for value in loop is used for going through elements of an array. If an index is required, an alternative form for index, value in can be used.
// Note, that the value is read-only. If you need to modify the array while looping, you have to use indexing:
mut numbers2 := [1, 2, 3, 4, 5]
for i, num in numbers2 {
	println(num)
	numbers2[i] = 0
}

// This form of the loop is similar to while loops in other languages.
// The loop will stop iterating once the boolean condition evaluates to false.
// Again, there are no parentheses surrounding the condition, and the braces are always required.
mut sum := 0
mut i := 0
for i <= 100 {
	sum += i
	i++
}
println(sum) // "5050"

// The condition can be omitted, this results in an infinite loop.
mut num := 0
for {
	num++
	if num >= 10 {
		break
	}
}
println(num) // "10"

// Finally, there's the traditional C style for loop. It's safer than the `while` form because with the latter it's easy to forget to update the counter and get stuck in an infinite loop.
// Here i doesn't need to be declared with mut since it's always going to be mutable by definition.
for i := 0; i < 10; i++ {
	// Don't print 6
	if i == 6 {
		continue
	}
	println(i)
}