0
0
Goprogramming~15 mins

Return inside loops in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the numbers slice
Create a slice of integers called numbers with the exact values 3, 7, 10, 5, 8.
Go
Need a hint?

Use var numbers = []int{3, 7, 10, 5, 8} to create the slice.

2
Create the firstEven function
Create a function called firstEven that takes a parameter nums of type []int and returns an int.
Go
Need a hint?

Define the function with func firstEven(nums []int) int and return an integer.

3
Add loop and return inside firstEven
Inside the firstEven function, use a for loop with variables i and num to iterate over nums. Inside the loop, use an if statement to check if num % 2 == 0. If yes, return num immediately.
Go
Need a hint?

Use for i, num := range nums and inside it check if num%2 == 0 then return num.

4
Call firstEven and print the result
In the main function, call firstEven(numbers) and print the returned value using fmt.Println. Remember to import fmt.
Go
Need a hint?

Use result := firstEven(numbers) and then fmt.Println(result) inside main.