Look at the code below. What will it print when run?
#include <iostream> int findFirstEven(int arr[], int size) { for (int i = 0; i < size; i++) { if (arr[i] % 2 == 0) { return arr[i]; } } return -1; } int main() { int numbers[] = {3, 7, 5, 8, 10}; std::cout << findFirstEven(numbers, 5); return 0; }
Return inside the loop stops the function immediately when condition is met.
The function checks each number in order. It returns the first even number it finds. The first even number is 8, so it prints 8.
What will this C++ function return when called with the array below?
#include <iostream> int findNegative(int arr[], int size) { for (int i = 0; i < size; i++) { if (arr[i] < 0) { break; } } return 0; } int main() { int data[] = {1, 2, 3, 4, 5}; std::cout << findNegative(data, 5); return 0; }
Notice the function returns 0 after the loop finishes.
The loop never finds a negative number, so it never breaks early. The function returns 0 at the end.
Examine the code below. The function is supposed to return the first positive number, but it always returns 0. Why?
#include <iostream> int firstPositive(int arr[], int size) { for (int i = 0; i < size; i++) { if (arr[i] > 0) { return 0; } } return -1; } int main() { int nums[] = {-3, -1, 4, 5}; std::cout << firstPositive(nums, 4); return 0; }
Look carefully at what is returned inside the loop.
The function returns 0 inside the loop instead of the positive number found. So it never returns the actual positive number.
Which of the following code snippets will cause a compilation error?
Check if the return statements match the function's return type.
Option B tries to return nothing (void) in a function declared to return int, causing a compilation error.
Consider the following C++ code. What will it print?
#include <iostream> int nestedLoop() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j > 3) { return i * j; } } } return 0; } int main() { std::cout << nestedLoop(); return 0; }
The function returns as soon as the product i*j is greater than 3.
The first product greater than 3 is 2*2=4, so the function returns 4 immediately.