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 goes through a list of numbers and returns the first even number it finds using a return statement inside a loop.
📋 What You'll Learn
Create a vector called
numbers with the exact values: 3, 7, 10, 5, 8Create an integer variable called
firstEven and initialize it to -1Write a
for loop using int i = 0; i < numbers.size(); i++ to check each numberInside the loop, use an
if statement to check if the current number is evenIf the number is even, use
return to immediately return that numberOutside the loop, return
firstEven if no even number is foundPrint the returned value from the function
💡 Why This Matters
🌍 Real World
Finding the first item that meets a condition quickly is common in searching tasks, like finding the first available seat or the first error in a log.
💼 Career
Understanding how to return early from loops helps write efficient code in many programming jobs, especially when processing data or searching.
Progress0 / 4 steps