.Introduction:-
Sometimes, it is desirable to skip the execution of a loop for a certain test condition or terminate it immediately without checking the condition.
In scenarios like these,
continue;
or a break;
statement is used.
.Break Statement:-
The break; statement terminates for loop/ while loop / do..while loop)
Example 1--C++ Program to demonstrate working of break statement
#include <iostream>
using namespace std;
int main( )
{
float n, sum = 0.0;
for(;;)
{
cout << "Enter a number: ";
cin >> n;
if (n!=0.0)
{
sum=sum+n;
}
else
{
// terminates the loop if number equals 0.0
break;
}
}
cout << "Sum = " << sum;
return 0;
}
An infinite for loop has been used here.
for (; ;)
To terminate this infinite loop, we are using break statement .
same result can also be achieved using while(true)
.Break Statement:-
Example 1- Program to write all the natural numbers from 1 to 100 except multiples of 4.
#include<iostream>
using namespace std;
int main ()
{
int i;
for(i=1;i<=100;i++)
{
if (i%4!=0)
{cout<<i<<endl;}
else
{continue;}
}
return 0;
}