Return inside loops
๐ Scenario: Imagine you are checking a list of numbers to find the first even number. Once you find it, you want to stop checking and return that number immediately.
๐ฏ Goal: You will write a Go function that loops through a slice of integers and returns the first even number it finds. If no even number is found, it returns -1.
๐ What You'll Learn
Create a slice of integers named
numbers with the values 3, 7, 10, 5, 8.Create a function called
firstEven that takes a slice of integers as input and returns an integer.Inside
firstEven, use a for loop with index i and value num to iterate over the slice.Inside the loop, use an
if statement to check if num is even (divisible by 2). If yes, return num immediately.If the loop finishes without finding an even number,
return -1.In
main, call firstEven(numbers) and print the returned value.๐ก Why This Matters
๐ Real World
Finding the first item that meets a condition quickly is common in many programs, like searching for available seats, checking for errors, or validating inputs.
๐ผ Career
Understanding how to return early from loops helps write efficient code and is a common pattern in software development jobs.
Progress0 / 4 steps