Return inside loops
📖 Scenario: Imagine you have a list of numbers and you want to find the first number that is bigger than a certain limit. This is like looking for the first ripe apple in a basket.
🎯 Goal: You will write a function that looks through a list of numbers and returns the first number that is greater than a given limit. You will learn how return works inside a loop to stop the search as soon as the answer is found.
📋 What You'll Learn
Create an array called
numbers with the exact values: [3, 7, 10, 2, 8]Create a variable called
limit and set it to 6Write a function called
findFirstGreater that takes numbers and limit as parameters and uses a for loop with variable num to check each numberInside the loop, use
return to immediately return the first number greater than limitIf no number is greater, return
nullCall
findFirstGreater(numbers, limit) and print the result💡 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 product in stock.
💼 Career
Understanding how to use return inside loops helps in writing efficient code that stops processing as soon as the needed result is found, which is important in many programming jobs.
Progress0 / 4 steps