xxxxxxxxxx
// program to print the value of i
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}
xxxxxxxxxx
break; statement helps in coming out of the current loop
Further in case of nested loop it gets you out of the innermost loop.
xxxxxxxxxx
/*Q;Design a program to print the employee IDs starting
from 1 until an Id occur who have resigned. IDs of
resigned persons are 7 and 10 .*/
#include<iostream>
using namespace std;
int main()
{
int meet=0;
for(int i=1;i<30;i++)
{
if(i==7||i==10)
break;
else
meet=1;
cout<<"Employee ID:"<<i<<endl;
}
return 0;
}
xxxxxxxxxx
#include <iostream>
int main()
{
while(1)
{
while(1)
{
// break;
//break only breaks the inner loop, so this will not work
// to exit the outer loop, you'll have to use 'goto':
goto breakOuter;
}
// IMPORTANT: Any code that happens after the inner loop will NOT be run
// when using the goto!
std::cout << "This won't be printed on the console" << std::endl;
}
breakOuter: // This is the point where goto will jump to
std::cout << "exited outer loop" << std::endl;
return 0;
}
xxxxxxxxxx
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}