// arrays.vr — arrays and for loops.
// Run with:  vr run examples/arrays.vr

fn sum(items) {
	mut total = 0
	for x in items {
		total = total + x
	}
	return total
}

fn main() {
	// array literal
	let a = [10, 20, 30]
	println(a)              // [10, 20, 30]
	println(len(a))         // 3

	// indexing: read and write
	println(a[0])           // 10
	a[1] = 99
	println(a)              // [10, 99, 30]

	// growing with push (mutates in place)
	push(a, 40)
	println(a)              // [10, 99, 30, 40]
	println(len(a))         // 4

	// iterate the array
	let total = sum(a)
	println("sum = ")
	println(total)          // 179

	// range for loops
	for i in 0..5 {
		println("i = " + i) // 0 1 2 3 4
	}

	for n in 1...3 {
		println("n = " + n) // 1 2 3 (inclusive)
	}

	// nested loops
	let grid = [[1, 2], [3, 4]]
	for row in grid {
		for cell in row {
			print(cell)
			print(" ")
		}
		println("")
	}
	println(grid[1][0])     // 3

	// build an array in a loop
	let squares = []
	for i in 0..5 {
		push(squares, i * i)
	}
	println(squares)        // [0, 1, 4, 9, 16]

	// loop variables are scoped to the loop
	let i = 100
	for i in 0..3 {
		println(i)
	}
	println("i is back to ")
	println(i)              // 100

	// break and continue
	for i in 0..10 {
		if i == 2 {
			continue        // skip 2
		}
		if i == 5 {
			break           // stop at 5
		}
		print(i)
		print(" ")
	}
	println("")

	// find the first even number in an array
	mut found = -1
	for x in a {
		if x % 2 == 0 {
			found = x
			break
		}
	}
	println("first even in a: " + found)   // 10

	assert sum([1, 2, 3, 4]) == 10
	assert len(squares) == 5
	assert squares[4] == 16
	assert a == a            // arrays compare by identity
	println("all array asserts passed")
}
