For Loops

In this example, n starts with 10 and counts backwards. It is important to think through the code and make sure that you don't have an endless loop. If we start with 10 and subtract 1 each time, n>=0 will eventually be false and the loop will end.

1
2
3
4
5
6
7
8
9
10
11
//Blast off: a count down
#include <iostream>
using namespace std;
void main() { 
  int n; //used to 'drive' the loop
  for(n=10; n>=0; n--) { //count BACKWARDS
    cout<<n<<"\n";
  } //end of for loop
  cout<<"Blast Off!\n";
  system("pause");
} //main
CODE
output

Note that "Blast off" prints just once, when the loop ends.

NEXT: For loop counts by 5