Look at this Go function. What will it print when called?
package main import "fmt" func findFirstEven(nums []int) int { for _, n := range nums { if n%2 == 0 { return n } } return -1 } func main() { fmt.Println(findFirstEven([]int{1, 3, 5, 6, 8})) }
Remember, return exits the function immediately.
The function returns the first even number it finds. It checks 1, 3, 5 (odd), then 6 (even), so it returns 6 immediately.
What value does this function return when called with []int{7, 9, 11}?
func findFirstEven(nums []int) int { for _, n := range nums { if n%2 == 0 { return n } } return -1 }
If no even number is found, what does the function return?
Since none of the numbers are even, the loop finishes without returning, so the function returns -1.
Look at this function. It is supposed to return the first even number from the slice, but it always returns 0. Why?
func findFirstEven(nums []int) int { for i := 0; i < len(nums); i++ { if nums[i]%2 == 0 { break } } return 0 }
What does break do inside a loop?
break exits the loop but the function continues and returns 0 always. To return the even number, return must be used inside the loop.
Which of these code snippets will cause a compile error due to incorrect use of return inside a loop?
Check if the function always returns a value on all paths.
Option A lacks a return statement after the loop, so if no even number is found, the function has no return value, causing a compile error.
What will this Go program print?
package main import "fmt" func findPair(nums []int, target int) (int, int) { for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { if nums[i]+nums[j] == target { return nums[i], nums[j] } } } return -1, -1 } func main() { a, b := findPair([]int{1, 3, 5, 7, 9}, 12) fmt.Println(a, b) }
The function returns the first pair that sums to the target.
The pairs checked in order are (1,3)=4, (1,5)=6, (1,7)=8, (1,9)=10, (3,5)=8, (3,7)=10, (3,9)=12. The first pair summing to 12 is (3,9), so the function returns 3 and 9 immediately.