Recall & Review
beginner
What happens when a
return statement is executed inside a loop in C++?The function immediately stops executing and returns the specified value, exiting both the loop and the function.
Click to reveal answer
beginner
Can code after a
return inside a loop be executed?No, once
return runs, the function ends immediately, so any code after it inside the loop or function is skipped.Click to reveal answer
intermediate
Why might you use
return inside a loop?To stop searching or processing as soon as a condition is met, improving efficiency by not running unnecessary code.
Click to reveal answer
intermediate
What is the difference between
break and return inside a loop?break exits only the loop but continues the function, while return exits the entire function immediately.Click to reveal answer
beginner
Example: What will this function return?<br>
int findFirstPositive(int arr[], int size) {
for (int i = 0; i < size; i++) {
if (arr[i] > 0) {
return arr[i];
}
}
return -1;
}It returns the first positive number found in the array. If none is found, it returns -1.
Click to reveal answer
What happens when a
return statement is executed inside a loop?✗ Incorrect
Return ends the entire function immediately, not just the loop.
Which statement exits only the loop but not the function?
✗ Incorrect
break exits the loop but the function continues.If a
return is inside a loop, will code after the loop run?✗ Incorrect
Code after the loop runs only if the loop completes without hitting return.
Why use
return inside a loop?✗ Incorrect
Return stops the function immediately, useful to end early when done.
What does this code return?<br>
for (int i = 0; i < 5; i++) { if (i == 3) return i; }✗ Incorrect
When i equals 3, return ends the function and returns 3.
Explain what happens when a return statement is used inside a loop in a C++ function.
Think about how return affects the whole function, not just the loop.
You got /4 concepts.
Describe the difference between using break and return inside a loop.
Consider what happens after the loop ends in each case.
You got /4 concepts.