for

for (expr1; expr2; expr3)        3 expressions separated by semicolons
  stmt body
The 3 expressions mean:
for (initialization; condition; update)
Example:
initialization
condition, if true
body
update
condition, if true
body 
update
condition, if not true exit for loop


//loop 5 times, from 1 thru 5:
int i;                   		   Output will be:
for (i=1; i<=5; i++)                          1
  cout << i << endl;                             2
// i's value is 6 after the loop                 3
                                                 4
                                                 5

//loop n times, from 1 thru n: the most common loop in the universe.
int n, i;
cin >> n;
for (i=1; i<=n; i++)      //loop from 1 thru n
  cout << i << endl;
// i's value is n+1


//sometimes a "backward" loop.  sometimes not by one.
//loop from n downto 0 by 2's
int n, i;
cin >> n;
for (i=n; i>0; i-=2) 
  cout << i << endl;

//if n is 10, outputs 10 8 6 4 2 
//if n is 9, outputs 9 7 5 3 1
// i's value is now 0 or -1

for loop preferred over while loop when know at start of loop execution how many
iterations are to be done.  "definite iteration".
while preferred over for when don't know at start of loop execution how many
iterations are to be done.  "indefinite iteration".



// table of fahrenheit and centrigrade equivalents
// from -60 F to 120 F by 10s
// C= 5/9 *(F-32)
for (fahr=-60; fahr<=120; fahr+=10)
  cout << setw(4) << fahr << setw(5) << 5.0/9.0*(fahr-32) << endl;


// table from 30 to 110 by 5's
for (fahr=30; fahr<=110; fahr+=5)
   cout << setw(4) << fahr << setw(5) << 5.0/9.0*(fahr-32) << endl;

Program to do temperature conversions (either way), from any starting value to any ending value by any increment. (see program)

Temperature conversion program fahrtemp.cpp


Write a program to sum a bunch of numbers from user.  Find average,
min and max too.



-----------------------------------
Draw "right triangle" of asterisks:
if of size 5:
    *
   **
  ***
 ****
*****

"Formula" or pattern?  on row i print i stars, preceded by size-i blanks

cin >> size;
for (row=1; row<=size; row++) {      //each row
  // row's size-row spaces
  for (col=1; col<=size-row; col++)
    cout << ' ';
  // row's stars
  for (col=1; col<=row; col++)
    cout << '*';
  cout << endl;
}

Also, "right triangles" in the three other arrangements, boxes, rectangles, "big X", framed big X, "diamonds", box within a box...

Next (do loop)


©David Wills