0
0
C++programming~15 mins

Return inside loops in C++ - 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 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, 8
Create an integer variable called firstEven and initialize it to -1
Write a for loop using int i = 0; i < numbers.size(); i++ to check each number
Inside the loop, use an if statement to check if the current number is even
If the number is even, use return to immediately return that number
Outside the loop, return firstEven if no even number is found
Print 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
1
Create the data vector
Create a std::vector<int> called numbers with these exact values: 3, 7, 10, 5, 8
C++
Need a hint?

Use std::vector<int> numbers = {3, 7, 10, 5, 8}; to create the vector.

2
Add a variable to hold the default return value
Inside the function findFirstEven, create an integer variable called firstEven and set it to -1
C++
Need a hint?

Write int firstEven = -1; inside the function.

3
Write the loop and return inside it
Inside the function findFirstEven, write a for loop using int i = 0; i < numbers.size(); i++. Inside the loop, use an if statement to check if numbers[i] % 2 == 0. If true, immediately return numbers[i]. After the loop, return firstEven.
C++
Need a hint?

Use a for loop and inside it an if to check even numbers. Use return inside the if.

4
Call the function and print the result
In main(), call findFirstEven(numbers) and store the result in an integer variable called result. Then print result using std::cout.
C++
Need a hint?

Call the function, save the return value in result, then print it with std::cout << result << std::endl;.