QUESTION 25 · Jump Statements
What does break do inside a loop?
2 marksAnswer
It ends the nearest enclosing loop immediately.
- Control continues after that loop.
- In a switch, break leaves the switch instead of an enclosing loop.
QUESTION 25 · Jump Statements
It ends the nearest enclosing loop immediately.
QUESTION 26 · Jump Statements
The break statement immediately leaves the nearest enclosing loop or switch.
break;When execution reaches break, the remaining statements in that loop body are skipped. Control moves to the statement after the loop. In a for loop, the update is not performed for that abandoned iteration. The statement does not leave the whole function; use return when that is the intention.
The example counts from 1 towards 5. It prints 1 and 2. When i reaches 3, the if condition is true and break executes before printf. The loop ends, so neither 3 nor any later value is printed. The message Done then prints because it follows the loop.
A break in an inner loop leaves only that inner loop; the outer loop can continue. A break inside a switch nested in a loop leaves the switch. An early break may reduce work on a particular input, but worst-case complexity still depends on the longest permitted execution. A search through n items can still be O(n) in the worst case.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 5; ++i) {
if (i == 3) { break; }
printf("%d\n", i);
}
puts("Done");
return 0;
}This example uses values already written in the program.
1
2
DoneRelated questions in the jump statements category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Mention the pros and cons of goto in C.
Paper P04 · page 1