C++ – For Statement
Working samples:
1 2 3 4 5 6 7 8 9 10 11 | // 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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 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!
1 2 3 4 5 6 7 8 9 10 11 12 | // 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!