Identify and resolve common control flow mistakes with this quiz covering branching errors, misplaced breaks, off-by-one missteps, and nested loop traps. Improve your understanding of program execution paths to write more reliable code and avoid subtle runtime bugs.
In the following code snippet, what control flow bug is most likely to cause an unintended infinite loop?nnint i = 0; while (i u003C 5) { /* ... */ }
Explanation: If 'i' is not incremented, the loop condition 'i u003C 5' will always be true if 'i' starts at 0, causing an infinite loop. Changing the condition to 'i u003C= 5' still ends the loop unless incrementing is missing. Placing a 'return' outside the loop does not cause an infinite loop. Initializing 'i' to 5 would result in the loop never running, not an infinite loop.
Given the following code, which mistake would cause a break statement in the wrong place to bypass intended logic?nnfor (int i = 0; i u003C 10; i++) { if (someCheck(i)) break; processItem(i); }
Explanation: If 'break' appears before 'processItem(i)', the loop will exit before processing the matching item, bypassing important logic. Swapping the loop type may change flow but not due to 'break' placement. Omitting 'break' would process all items. Initialization errors may cause different issues, like missing iterations, but not the described bypass.
Suppose a programmer writes: for (int j = 0; j u003C= 5; j++) { /* work */ }. What is a likely unintended effect of this off-by-one error?
Explanation: With 'j u003C= 5', the loop executes for j equal to 0 through 5, running six times, which is one more than expected if the loop should run five times (0 to 4). Skipping the first iteration would occur with a wrong start value. A failure to run at all would require a false condition initially. The loop does not alter which numbers are processed regarding parity.
In a nested loop, such as for (int x = 0; x u003C m; x++) { for (int y = 0; y u003C n; y++) { if (exitCondition) break; } }, what common misunderstanding could cause the outer loop to run longer than intended?
Explanation: A 'break' only exits the nearest enclosing loop, so the outer loop continues running. Using 'continue' simply skips to the next iteration of the inner loop and doesn't exit either. Switching loop order may produce different results but doesn't affect loop exit here. Not resetting variables could cause logical errors, but doesn't directly impact the described misunderstanding.
Consider this function: if (flag) { return 1; } else { return 2; } return 3;. What issue is present regarding control flow?
Explanation: After both 'return' statements, execution never reaches 'return 3;,' making that line unreachable. The 'else' clearly returns a value, so that distractor is incorrect. A default case isn't missing, as both branches are covered. There is no recursion in the provided code, so the last option is irrelevant.