Introduction
Loop control helps us manage how many times a loop runs. It stops loops from running forever and lets us repeat tasks easily.
Loop control helps us manage how many times a loop runs. It stops loops from running forever and lets us repeat tasks easily.
for (initialization; condition; update) { // code to repeat } while (condition) { // code to repeat } // Loop control statements: break; // exit the loop immediately continue; // skip to next loop iteration
break stops the loop completely.
continue skips the rest of the current loop and moves to the next cycle.
for (int i = 0; i < 5; i++) { if (i == 3) { break; // stop loop when i is 3 } std::cout << i << " "; }
for (int i = 0; i < 5; i++) { if (i == 3) { continue; // skip printing 3 } std::cout << i << " "; }
This program shows how break stops a loop early and how continue skips one loop step.
#include <iostream> int main() { std::cout << "Counting with break:\n"; for (int i = 1; i <= 10; i++) { if (i > 5) { break; // stop loop after 5 } std::cout << i << " "; } std::cout << "\nSkipping number 3 with continue:\n"; for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // skip 3 } std::cout << i << " "; } std::cout << std::endl; return 0; }
Without loop control, loops might run forever and crash your program.
Use break carefully to avoid skipping important code after the loop.
continue only skips the current loop cycle, not the whole loop.
Loop control helps manage how loops run and stop.
break exits the loop immediately.
continue skips to the next loop cycle.
break; is used to exit a loop immediately.continue; skips to next iteration, exit; and stop; are invalid here.for(int i = 1; i <= 5; i++) {
if(i == 3) continue;
std::cout << i << " ";
}continue; skips printing.for(int i = 0; i < 5; i++) {
if(i == 2)
continue
std::cout << i << " ";
}continue statement must end with a semicolon.Pass the test and this pattern moves unknown