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 function that looks through an array of numbers and returns the first even number it finds using a return statement inside a loop.
📋 What You'll Learn
Create an integer array called
numbers with the values 3, 7, 10, 15, 20Create an integer variable called
size and set it to 5Write a function called
find_first_even that takes the array and its size as parametersInside the function, use a
for loop with variable i to check each numberReturn the first even number found inside the loop using
returnIf no even number is found, return -1
In
main, call find_first_even with numbers and sizePrint 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 the first available seat or the first error in a log.
💼 Career
Understanding how to return early from loops helps write efficient code and is a common pattern in software development.
Progress0 / 4 steps