void main() { // there are 3 types of loops, but they are all equivalent in power; some // forms are more natural for certain applications, which is why the 3 forms // exist; could get by with only the WHILE loop ///////////////////////////////////////////////////// // while // the WHILE loop is just like the IF statement, except it's // an IF that gets done over and over again until the condition // is not true // a loop to print out numbers from 1 to 10 int count=1; while (count<=10) { cout << count << endl; count=count+1; } // loop example from Animal House char answer='y'; while ((answer=='Y')||(answer=='y')) { cout << "Thank you sir! May I have another?\n"; cin >> answer; } ///////////////////////////////////////////////////// // do-while // for the last example, DO-WHILE is actually better; note the // inverted logic in the condition below, using ! for NOT do { cout << "Thank you sir! May I have another?\n"; cin >> answer; } while (!((answer=='Y')||(answer=='y'))); // in a DO-WHILE, the loop is always executed at least once ///////////////////////////////////////////////////// // for // the FOR loop is ideal when counting is involved, or when // a sequence is involved // add the numbers from 1 to 50 int i, sum; sum=0; for (i=1; i<=50; ++i) { sum=sum+i; } // count down from 100 for (i=100; i>0; --i) { cout << i << endl; } // as always, a single command counts as a block of code, so don't // need the curly braces when only one command in body; doesn't // hurt to have them though for (i=100; i>0; --i) cout << i << endl; //count down from 100 // the FOR loop can take less space than other loops, and can // make the intentions of the programmer clearer }