C++ – For Statement
Working samples:
// countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "liftoff!\n"; }
The result:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
// break loop example #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } }
The result:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
// continue loop example #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "liftoff!\n"; }
The result:
10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!