Friday, 17 May 2013

Jump statements


The break statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite
loop, or to force it to end before its natural end. For example, we are going to stop the count down before its
natural end (maybe because of an engine check failure?):
// break loop example
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the
statement block had been reached, causing it to jump to the start of the following iteration. For example, we are
going to skip the number 5 in our countdown:
// continue loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

No comments:

Post a Comment