Consider a loop that runs infinitely without any way to stop it. Why are loop control statements like break and continue important in C programming?
Think about what happens if a loop never stops or if you want to skip some steps inside it.
Loop control statements like break let you stop the loop early, and continue lets you skip the current iteration. This helps prevent infinite loops and lets you control which parts of the loop run.
What is the output of this C code?
int main() { int i; for(i = 0; i < 5; i++) { if(i == 3) { break; } printf("%d ", i); } return 0; }
Look at when the loop stops due to break.
The loop prints numbers from 0 up to 2. When i becomes 3, the break stops the loop before printing 3.
What will this C program print?
int main() { int i; for(i = 0; i < 5; i++) { if(i == 2) { continue; } printf("%d ", i); } return 0; }
Think about what continue does inside the loop.
The continue skips printing when i is 2, so 2 is not printed but the loop continues with 3 and 4.
What error or problem will this C code cause?
int main() { int i = 0; while(i < 5) { if(i == 3) { continue; } printf("%d ", i); i++; } return 0; }
Check what happens to i when continue is executed.
The continue skips the i++ increment when i == 3, so i stays 3 forever, causing an infinite loop.
In large C programs, why is proper use of loop control statements essential?
Think about what happens if a loop never ends or uses too many resources.
Loop control statements help stop loops when needed and skip unnecessary steps, preventing freezes and saving memory and CPU time.