A Break statement is used within loops to exit out of the loop. In the following example, the program will exit the loop when 'i' becomes 5.
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <=10)
{
cout << i << endl;
i++;
if (i == 6)
break;
}
return 0;
}
Here is another example
#include <iostream>
using namespace std;
int main() {
int i = 1;
double num = 0, tot = 0;
char ans;
while (true)
{
cout << "Enter number " << i << ":";
cin >> num;
tot = tot + num;
i++;
cout << "Do you want to add another number (y/n) : ";
cin >> ans;
if (ans == 'n')
break;
}
cout << "The total is: " << tot << endl;
return 0;
}
A Continue statement are used within loops to jump to next iteration. It is useful in situations, where it is necessary to skip the current iteration and jump to next iteration. When the program reaches continue statement, it immediately goes and executes from the top of the loop.
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 12)
{
i++;
if (i % 2 == 0)
continue;
cout << i << " * 12 = " << i * 12 << "\n";
}
return 0;
}
Another example
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i <= 100)
{
i = i + 1;
if (i % 2 == 0)
continue;
else if (i > 51)
break;
cout << i << endl;
}
return 0;
}
Comments
Post a Comment