0
0
C++programming~5 mins

Return inside loops in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe function ends immediately and returns the value.
BOnly the loop ends, function continues.
CThe loop skips to the next iteration.
DThe loop pauses until user input.
Which statement exits only the loop but not the function?
Areturn
Bexit
Ccontinue
Dbreak
If a return is inside a loop, will code after the loop run?
AOnly if the loop finishes without return.
BNo, never.
COnly if the loop has one iteration.
DYes, always.
Why use return inside a loop?
ATo skip the current loop iteration.
BTo stop the function early when a condition is met.
CTo restart the loop.
DTo pause the function.
What does this code return?<br>
for (int i = 0; i < 5; i++) { if (i == 3) return i; }
A5
B0
C3
DLoop never ends
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.