LECTURE 9: Repetition and Loop Statements (Chapter 5)

 

Loops provide a means of repeating a series of executable statements (the loop body) as long as the condition controlling the loop usually found in the loop header) evaluates to TRUE.

  

The loop control condition is a logical expression that evaluates to either TRUE or FALSE.  Often, this expression involves a single variable, called a loop control variable.

 

The loop body is the block of code that contains the series of executable statements associated with the loop condition. The loop body will be repeated as long as the loop condition evaluates to TRUE, when the loop condition evaluates to FALSE the loop will stop. Each time the loop body is repeated the loop is said to have gone through iteration.

 

There are 3 types of repetition statements:

1. WHILE loops

2. DO-WHILE loops

3. FOR loops

 

WHILE loops

 

Basic form of the while loop

 

 

while (condition)

{

statement1;

statement2;

}

 

 

 

 

Standard way of using while loop

 

  // Before the loop construct, initialize any loop control

  //   variable(s) (the variables appearing in the condition

  //   in the loop header)

 

  initialize; // initialize loop control variable(s);

 

  while (condition) /* Loop header, test the loop condition */

  {

      // Loop body -- the dependent statements

      //    Dependent statements that are executed while (as

      //    long as) the condition evaluates to TRUE.  If the

      //    condition is false the first time, the loop will

      //    not execute at all.                               

 

      statement1;

      statement2;

          ...

 

      // The loop body must contain statements that update

      //    the loop control variable(s) These statements are

      //    found at the bottom of the loop body.

 

      update; // update loop control variable(s);

   }

 

   // First executable statement following the while construct

   // Control is transferred here when loop condition becomes false.

 

 

Note A: When the while loop construct has only ONE dependent statement then the curly braces { } are optional. In this case, we can write:

 

      while (condition)

         dependent statement;

 

However, it's ALWAYS a good idea to use the curly braces { } even though they're not  required.

 

Note B: The dependent statement or statements contained within the curly braces { } are executed each time the condition [contained within the parenthesis ( ) in the loop header] evaluates to TRUE.  When the condition contained within the parenthesis ( ) evaluates to FALSE, the loop stops and the dependent statement or statements contained within the curly braces { } are NOT executed.  Program execution continues with the first executable statement after the end of the "while" loop construct.

 

Example 1:  A while loop to display seven asterisks …

 

int countstars = 0;    // initialize loop control variable

while (countstars < n) // countstars is loop control variable

{

   printf(‘*’);             // loop body starts here

   ++ countstars;      // or countstars += 1  (increment)

}

 

Note the pattern used here.  We initialize the loop control variable, or countstars, then test it (in the loop control expression).  Finally, at the bottom of the loop, we “update” the countstars.

 

DO-WHILE loops

 


Basic form of the do-while loop

 

 

do

{

statement1;

statement2;

} while (condition);

 

 

 

 

Standard way of using while loop

 

// Before the loop construct, initialize any loop control

//   variable(s) (the variables appearing in the condition

//   in the loop header)

 

initialize; // initialize loop control variable(s);

 

do

{

// Loop body -- the dependent statements.

//    Dependent statements that are executed at least

//    once and then repeated as long as the loop condition

//    (below) evaluates to TRUE                              

 

statement1;

statement2;

          ...

 

// The loop body must contain statements that update

//    the loop control variable(s) These statements are

//    found at the bottom of the loop body.

 

update; // update loop control variable(s);

} while (condition);

 

// First executable statement following the do-while construct

// Control is transferred here when loop condition becomes false.

 

Note C:  The semi-colon ; is required after the closing parenthesis at the end of the do-while loop construct!

 

Note D: The variable or variables used in the loop condition normally should be initialized BEFORE the loop is entered, and then updated (in the loop body) before the loop condition is tested at the end of each repetition of the loop body.

 

Note E: The dependent statement or statements contained within the curly braces { } are executed at least once.  They are then repeated each time the condition [contained within the parenthesis  ( ) in the last line of the loop] evaluates to TRUE.  When the condition contained within the parenthesis ( ) evaluates to FALSE, the loop stops and the dependent statement or statements contained within the curly braces { } are NOT repeated.  Program execution continues with the first executable statement after the end of the do-while loop construct.

    

Note F: When the "do-while" loop construct has only ONE dependent statement then the curly braces { } are optional:

 

   do

      dependent statement;

   while (condition);

 

However, it's ALWAYS a good idea to use the curly braces { } even though they're not required:

 

Example 2:  A do-while loop to print some number, n, of stars in a row.

 

int countstars = 0;    // initialize loop control variable

do                     // countstars is loop control variable

{

   printf(‘*’);      // loop body starts here

   ++ countstars;      // or countstars += 1  (increment)

} while (countstars < n)

 

 

FOR loops

 

Basic form of the for loop

 

 

for (initialize; condition; update)

{

statement1;

statement2;

}

 

Standard way of using for loop

 

for(initialization;// for loop initialization –

//    initialize the variables(s)used

//    in the loop condition               

condition;    // for loop test condition

update)       // for loop update of the variable(s)

//    used in the loop condition                

{

// For loop body, execute the dependent statements

//     once for each specified loop repetition

dependent statement 1;

dependent statement 2;

          ...

}

 

Note F:  The for loop construct is used exclusively as a counting loop unlike the while and do-while loop constructs which can be used for either counting, sentinel or flag controlled loops.

 

Note G:  The loop "header" in a for loop construct contains the initialization of the condition variable(s), the condition test (involving these variables(s)), and the update of the condition variable.  As a result, the variable that is used in the loop condition is initialized and updated in the loop header as opposed to the loop "body".

     

Note H: 

--   The initialization of the variable(s) used in the loop condition occurs ONCE at the start of the loop execution. 

--   The condition testing occurs BEFORE each loop iteration and continues with each loop iteration until the condition evaluates to FALSE and the loop stops. 

--   The update of the variable(s) used in the loop condition occurs AFTER each loop iteration has completed but BEFORE the loop condition is evaluated and continues with each loop iteration until the condition evaluates to FALSE and the loop stops.

 

 Note I: When the for loop construct has only ONE dependent statement then the curly braces { } are optional:

          for (initialization; condition; update)

               dependent statement;

 

 However, it's ALWAYS a good idea to use the curly braces { } even though they're not required:

 

 Note J: The dependent statement or statements contained within the curly  braces { } are executed each time the condition evaluates to TRUE. When the condition evaluates to FALSE, the loop stops and the dependent statement or statements contained within the curly braces { } are NOT executed.  Program execution continues with the first executable statement after the end of the for loop construct.

 

Example 3: A for loop to display seven asterisks …

 

for (int countstars = 0; countstars < n; countstars++)

{

   printf(‘*’);

}

 

 There are three general categories of loops

 

Category A: Counting controlled loops (most conveniently  implemented using a for loop)

 

·         Counting controlled loops repeat a series of executable statements a specified number of times using a variable to count the number loop iterations completed.

·         The number of times that the loop body will be repeated MUST be known before checking the loop condition the first time and must NOT be changed within the loop body.

·         The counting variable MUST be initialized to a known value before checking the loop condition the first time.

·         The counting variable MUST be updated within the loop body or the loop condition will never evaluate to FALSE creating an infinite loop that will never stop.

·         The counting variables can be incremented (increased in value) by any amount or decremented (decreased in value) by any amount.

 

Example 5: A Celsius to Fahrenheit Temperature Conversion Table

 

float ctemp, ftemp;

printf(“     ctemp          ftemp”);

for (int ctemp = 100; ctemp <= 0; ctemp--)

{

    ftemp = (9.0/5.0) * ctemp + 32;

    printf (“%10.1f     %10.1f\n”, ctemp, ftemp);

}

 

What would happen if I had written (9/5) rather than (9.0/5.0)?

What would happen if I had left off the parentheses from around (9.0/5.0)?

Where is the mixed-mode of the calculation of ftemp introduced and how could I have corrected this problem?

 

Category B: Sentinel controlled loops (Most conveniently implemented using a while loop)

 

·         Sentinel controlled loops repeat a series of executable statements until a specified condition has been met using a variable to store a value that is compared to the sentinel value or values.

·         The number of times that the loop body will be repeated is NOT known before checking the loop condition the first tim.

·         The sentinel variable MUST be initialized to a known value before checking the loop condition the first time.

·         The sentinel variable MUST be updated within the loop body or the loop condition will never evaluate to FALSE creating an infinite loop that will never stop.

 

Example 6: Reading and summing a collection of positive floating point numbers (until a 0.0 value is read)

 

float item;

 

float sum = 0;   // initialize the sum

// Get the first item to be read.

// This is how we initialize the loop control variable,

//   (“item” in this example) in cases where a sentinel

//   value is involved.

 

printf (“Enter a positive number.  Use 0 to stop)”);

scanf (“%f”, &item);

while (item != 0.0)  // test for sentinel value 0.0

{

              sum += item;  // sum = sum + item;

                 // Now get the next item.  This is how we update

                 //   the loop control variable wherever a sentinel

              //   value is involved.

              printf (“Enter a positive number.  Use 0 to stop)”);

   scanf (“%f”, &item);

   }

           printf (“The sum of the values just read is: %f”, sum);

 

Re-write this loop to count the number of items read.  Note that this number is not known before hand so it is more convenient to use a while loop here.

 

                Hand trace this loop to be sure it works.  Use values 1.1, 2.2, and 3.3

                What will happen of the first printf /scanf pair is omitted?  Trace the loop. 

                What will happen if the second printf/scanf pair is omitted?  Trace the loop.

 

Category C: Flag controlled loops (Most conveniently implemented using a while loop)

 

·         Flag controlled loops repeat a series of executable statements until a specified condition has been met using a flag variable to store a TRUE or FALSE value

·         The number of times that the loop body will be repeated is NOT known before checking the loop condition the first time.

·         The flag variable MUST be initialized to a known value before checking the loop condition the first time.

·         The flag variable MUST be updated within the loop body or the loop condition will never evaluate to FALSE creating an infinite loop that will never stop.