Loops: Break and Continue - Introduction to Programming - C++
Loops: Break and Continue
Loops: Break and Continue
Introduction: Overall idea of break and continue
In the previous lessons, we learned how for, while, and do while loops repeat actions while their condition remains true. By default, a loop runs its entire body from top to bottom on every repetition and continues until the condition becomes false.
However, we often need to change this normal flow from inside the loop body based on an if condition:
break: Immediately stops and exits the loop completely. No more repetitions will happen; control jumps straight to the first statement after the loop.
continue: Immediately stops the current repetition and jumps to the next repetition. It skips all remaining lines inside the loop body for that single step.
Think of a loop as reading pages of a book:
break means closing the book and putting it away immediately.
continue means turning directly to the next page without finishing the current page.
Core concept: How break works
The break statement is used when our goal is accomplished early or when an invalid situation requires stopping immediately.
Execution flow of break
When C++ encounters break inside a loop:
It immediately exits the loop body.
It does not run the <update> step.
It does not check the <condition> again.
Execution resumes at the first line of code after the loop closing brace }.
Let us see what happens when we print numbers from 1 to 10, but stop early when :
i=4
This prints: 123
Here is what happens on each step:
i=1: 1==4 is false o prints 1.
i=2: 2==4 is false o prints 2.
i=3: 3==4 is false o prints 3.
i=4: 4==4 is true o runs breakoloop stops immediately.
Notice that 4,5,…,10 are never printed.
How `break` exits a `for` loop early
C++
source · C++line 1
1for (int i = 1; i <= 10; i = i + 1) {
2 if (i == 4) {
3 break;
4 }
5 cout << i << ' ';
6}
Initialize i = 1
L1
The loop variable i is created and starts at 1.
inv
When break runs, the loop terminates immediately regardless of the condition.
Variables box
Map
currentPart
<start>
i
1
condition
1 <= 10 is true
lastPrinted
nothing yet
outputSoFar
empty
currentPart⤳<start>i⤳1condition1 <= 10 is truelastPrintednothing yetoutputSoFarempty
iterations0
L1
01 / 12
Using break with while
break works identically inside a while loop. This pattern is very common when creating infinite loops that wait for a specific stop condition:
This prints: 12345
Core concept: How continue works
The continue statement is used when we want to skip certain unwanted or special values without stopping the rest of the loop.
Execution flow of continue
When C++ encounters continue:
It immediately skips all remaining lines in the loop body for the current iteration.
In a for loop: Control jumps directly to the <update> step (i = i + 1), and then checks the <condition> for the next iteration.
In a while loop: Control jumps directly to the <condition>.
Let us see what happens when we print numbers from 1 to 5, but skip i=3:
This prints: 1245
Notice that 3 is missing! When i=3, continue skips cout << i << ' ' and goes directly to i = i + 1, making i=4.
How `continue` skips the rest of an iteration
C++
source · C++line 1
1for (int i = 1; i <= 5; i = i + 1) {
2 if (i == 3) {
3 continue;
4 }
5 cout << i << ' ';
6}
Initialize i = 1
L1
The loop starts with i = 1.
inv
continue skips the rest of the body and jumps straight to the update step in a for loop.
Variables box
Map
currentPart
<start>
i
1
condition
1 <= 5 is true
lastPrinted
nothing yet
outputSoFar
empty
currentPart⤳<start>i⤳1condition1 <= 5 is truelastPrintednothing yetoutputSoFarempty
iterations0
L1
01 / 17
Crucial trap: Using continue with while
In a for loop, continue jumps automatically to the <update> header (i = i + 1).
In a while loop, the update statement is written manually inside the body. If you call continuebefore updating your loop variable, the update is skipped, causing an infinite loop!
To use continue safely in a while loop, update the counter before calling continue:
Comparing break and continue
Feature
break
continue
Effect
Stops the entire loop permanently
Skips only the rest of the current iteration
Where control goes in for
First line after the loop's }
Jumps to <update>, then <condition>
Where control goes in while
First line after the loop's }
Jumps directly to <condition>
Common Use Cases
Early stop upon finding an answer or reaching a sentinel value
Filtering or skipping unwanted values
Examples
Example 1: Find the smallest divisor greater than 1
Given an integer n (n>1), find the smallest divisor of n that is strictly greater than 1.
Example:
Approach and solution
We check possible divisors d starting from 2 upward. The very first number d that divides n without remainder (n%d==0) is guaranteed to be the smallest divisor.
Once we find it, we print d and use break to stop immediately, avoiding unnecessary further checks.
Algorithm:
Implementation:
Example 2: Print numbers not divisible by 3
Given an integer n, print all numbers from 1 to n in increasing order, skipping all numbers that are divisible by 3.
Example:
Approach and solution
We loop through all numbers i from 1 to n. If i is divisible by 3 (i%3==0), we call continue to skip the printing step. Otherwise, we print i.
Algorithm:
Implementation:
Example 3: Sum numbers until a negative number appears
You are given a sequence of integers. Compute the sum of all numbers until a negative number appears. The negative number itself should not be added to the sum.
Example:
Because 5+8+12=25.
Approach and solution
We use a while (true) loop to read numbers one by one. If the number x is negative (x<0), we stop the loop using break. Otherwise, we add x to sum.
Algorithm:
Implementation:
Example 4: Sum only positive numbers
Given n integers, calculate the sum of only the strictly positive numbers (x>0), ignoring all non-positive values (x≤0).
Example:
Because 4+7+5=16.
Approach and solution
We iterate n times. For each number x, if x≤0, we skip it using continue. Otherwise, we add x to sum.
Algorithm:
Implementation:
Example 5: Check if an element exists (Linear Search with early exit)
Given n integers and a target value k, determine if k is present in the sequence. Print YES if it exists, or NO otherwise.
Example:
Approach and solution
We keep a boolean variable found = false. We scan through the n numbers. As soon as we find x==k, we set found = true and break out of the loop immediately because finding one match is sufficient.
Algorithm:
Implementation:
Input:
15
Output:
3
1. Read n.
2. For d from 2 to n:
1. If n % d == 0:
1. Print d.
2. Break.
Input:
10
Output:
1 2 4 5 7 8 10
1. Read n.
2. For i from 1 to n:
1. If i % 3 == 0:
1. Continue.
2. Print i.
Input:
5 8 12 -3 9 4
Output:
25
1. Set sum = 0.
2. While true:
1. Read x.
2. If x < 0:
1. Break.
3. Add x to sum.
3. Print sum.
Input:
5
4 -2 7 0 5
Output:
16
1. Read n.
2. Set sum = 0.
3. For i from 1 to n:
1. Read x.
2. If x <= 0:
1. Continue.
3. Add x to sum.
4. Print sum.
Input:
6 15
3 8 15 2 9 15
Output:
YES
1. Read n and k.
2. Set found = false.
3. For i from 1 to n:
1. Read x.
2. If x == k:
1. Set found = true.
2. Break.
4. If found is true, print YES. Otherwise, print NO.
for(int i = 1; i <= 10; i = i + 1){ if(i == 4){ break;} cout << i << ' ';}
int i = 1;while(true){ if(i > 5){ break;} cout << i << ' '; i = i + 1;}
for(int i = 1; i <= 5; i = i + 1){ if(i == 3){ continue;} cout << i << ' ';}
// INCORRECT: Causes an infinite loop when i == 3!int i = 1;while(i <= 5){ if(i == 3){ continue; // i stays 3 forever!} cout << i << ' '; i = i + 1;}
// CORRECT: Updates i before continuingint i = 1;while(i <= 5){ if(i == 3){ i = i + 1; // Update before skipping! continue;} cout << i << ' '; i = i + 1;}
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; for(int d = 2; d <= n; d = d + 1){ if(n % d == 0){ cout << d << ''; break;}} return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; for(int i = 1; i <= n; i = i + 1){ if(i % 3 == 0){ continue;} cout << i << ' ';} cout << ''; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ long long sum = 0; int x; while(cin >> x){ if(x < 0){ break;} sum = sum + x;} cout << sum << ''; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; long long sum = 0; for(int i = 1; i <= n; i = i + 1){ int x; cin >> x; if(x <= 0){ continue;} sum = sum + x;} cout << sum << ''; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ int n, k; cin >> n >> k; bool found = false; for(int i = 1; i <= n; i = i + 1){ int x; cin >> x; if(x == k){ found = true; break;}} if(found){ cout << "YES\n";} else{ cout << "NO\n";} return 0;}