Examples of Break and Continue in C++
C++: Break and Continue Statement
Break statement is used to stop the process or execution of code. It works as an exit statement. Continue statement is also known as the jump statement. It is used to skip a segment of code.
Syntax of Break Statement
break;
Syntax of Continue Statement
continue;
Implementation of Break Statement in C++
Problem 1: Breaking out of a loop
Write a program to to exit a while loop early when the user enters the letter ‘q’.
Run
#include <iostream> using namespace std; int main() { char c; cout << "Enter a character ('q' to quit): "; cin >> c; while (c != 'q') { cout << "You entered: " << c << endl; cout << "Enter a character ('q' to quit): "; cin >> c; } cout << "Quitting program." << endl; return 0; }
Output
Enter a character ('q' to quit): q Quitting program.
Problem 2: Breaking out of a switch statement
Write a program to exit a switch statement early based on the value of a variable.
Run
#include <iostream> using namespace std; int main() { int x; cout << "Enter a number: "; cin >> x; switch (x) { case 1: cout << "You entered 1." << endl; break; case 2: cout << "You entered 2." << endl; break; case 3: cout << "You entered 3." << endl; break; default: cout << "You entered something else." << endl; break; } return 0; }
Output
Enter a number: 5 You entered something else.
Problem 3: Breaking out of a nested loop
Write a program to exit a nested for loop early based on the value of a variable.
Run
#include <iostream> using namespace std; int main() { int x; cout << "Enter a number: "; cin >> x; for (int i = 1; i <= 10; ++i) { for (int j = 1; j <= 10; ++j) { if (i * j == x) { cout << "Found it!" << endl; break; } } } return 0; }
Output:
Enter a number: 7 Found it! Found it!
Implementation of Continue Statement in C++
Problem 1:
Write a program to print the series: 1,2,3,5,6,8,9,10
Run
#include <iostream> using namespace std; int main() { int i; for(i=1; i<=10; i++){ if(i==4 || i==7) { continue; } else{ printf("%d\n",i); } } return 0; }
Output:
1 2 3 5 6 8 9 10
Problem 2:
Write a program to skip a segment of code if the number is even.
Run
#include <iostream> using namespace std; int main () { int i = 0; while (i < 10) { if (i % 2 == 0) { i++; continue; } cout << i << endl; i++; } return 0; }
Output:
1 3 5 7 9
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment