Control Sructures - Repetition

Repetition Statements


while and do-while loops


Examples

Both of the following loops add up all of the numbers between 1 and 50.
 // while loop example 
 // loop body runs 50 times, condition checked 51 times 
 int i = 1, sum = 0; 
 while (i <= 50) 
 { 
    sum += i;		// means:  sum = sum + i; 
    i++; 		// means:  i = i + 1;
 } 

 cout << "Sum of numbers from 1 through 50 is " << sum; 
  

 // do/while loop example 
 // loop body runs 50 times, condition checked 50 times 
 int i = 1, sum = 0; 
 do 
 { 
    sum += i;		// means:  sum = sum + i; 
    i++; 		// means:  i = i + 1;
 } while (i <= 50); 

 cout << "Sum of numbers from 1 through 50 is " << sum; 

Example Links


The for loop


Examples of for loops


Special notes about for loops:

  1. It should be noted that if the control variable is declared inside the for header, it only has scope through the for loop's execution. Once the loop is finished, the variable is out of scope:
        for (int counter = 0; counter < 10; counter++) 
        {
           // loop body    
        } 
    
        cout << counter;	// illegal.  counter out of scope
    
    This can be avoided by declaring the control variable before the loop itself.
        int counter;    // declaration of control variable 
    
        for (counter = 0; counter < 10; counter++) 
        {
           // loop body    
        } 
    
        cout << counter;	// OK.  counter is in scope
    
  2. For loops also do not have to count one-by-one, or even upward. Examples:
        for (i = 100; i > 0; i--)
    
        for (c = 3; c <= 30; c+=4)
    
    The first example gives a loop header that starts counting at 100 and decrements its control variable, counting down to 1 (and quitting when i reaches 0).  The second example shows a loop that begins counting at 3 and counts by 4's (the second value of c will be 7, etc).

Special statements: break and continue