Looping

While and Do While Loops

  1. While and do while loops execute a set of instructions until a certain statement is evaluated as false.
  2. General form of a while loop:

    while (this is true) {
    
        ...do this...
    
    }
    

  3. To guarantee the code executes at least one time, use do while

    do {
    
        ...do this...
    
    } while (this is true)
    

For Loops

  1. A for loop is appropriate in cases where the loop is based on a counter
  2. The for statement takes 3 arguments: The initial value for the counter variable, the test condition, and the method of incrementing the counter variable.
  3. As an example, the following program prints the numbers 1 to 10.

    #include <stdio.h>
    
    int main() {
    
        int numb;
    
        for (numb = 1; numb <= 10; numb++ ) {
    
            printf("%d\n",numb);
    
        }
    
    
        return 0;
    
    }
    
    Source File | DOS Executable (run from DOS prompt)

  4. As a side note, numb++ is the same as numb = numb + 1