The break
and continue
statements are used to control the flow of loops in C++.
🔹 break
Statement
- Immediately exits the loop.
- Used to terminate a loop when a condition is met.
🔹 continue
Statement
- Skips the current iteration and moves to the next iteration.
- Used to bypass certain iterations in a loop.
1️⃣ Printing Numbers in C++ (Using break
)
📌 Example: Print numbers from 1 to 10
, but stop when the number is 5
.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Stops the loop when i is 5
}
cout << i << " ";
}
return 0;
}
🔹 Output
1 2 3 4
✅ The loop stops when i == 5
.
2️⃣ Printing Continuous Numbers in C++ (Using continue
)
📌 Example: Print numbers from 1 to 10
, but skip 5.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skips when i is 5
}
cout << i << " ";
}
return 0;
}
🔹 Output
1 2 3 4 6 7 8 9 10
✅ continue
skips 5 but keeps printing other numbers.
3️⃣ Printing Even Numbers (Using continue
)
📌 Example: Print even numbers from 1 to 10
.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // Skip odd numbers
}
cout << i << " ";
}
return 0;
}
🔹 Output
2 4 6 8 10
✅ continue
skips odd numbers and prints only even numbers.
4️⃣ Printing Odd Numbers (Using continue
)
📌 Example: Print odd numbers from 1 to 10
.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
cout << i << " ";
}
return 0;
}
🔹 Output
1 3 5 7 9
✅ continue
skips even numbers and prints only odd numbers.
📌 Summary
Statement | Function |
---|---|
break |
Exits the loop completely |
continue |
Skips the current iteration but continues the loop |
Would you like more examples or a real-world use case? 🚀
0 Comments