Loops

Tom Kelliher, CS 116

Nov. 29, 2000

Administrivia

Announcements

Return exams on Friday.

Assignment

Read 8.2.

From Last Time

Lab 6.

Outline

  1. Introduction.

  2. while loops.

  3. for loops.

  4. Exercises.

  5. Nested loops.

Coming Up

Arrays.

Introduction

  1. Why? How do they fit in with sequential, selection?

    Example: summation.

  2. Components of a loop:
    1. Condition: Tested at the beginning of each iteration. If true, iteration proceeds, otherwise terminated.

    2. Loop body: the set of statements executed during each iteration.

while Loop

  1. Form:
    while (<condition>)
       statement;
    
    How do we achieve a multi-statement loop body?

  2. Semantics. When to use.

  3. Example 1: Sum a sequence of numbers, stopping when 0 is input.
    int input;
    int sum = 0;
    
    input = getNextInput();
    
    while (input != 0)
    {
       sum += input;
       input = getNextInput();
    }
    

  4. Example 2: Count the number of digits in a number.
    int digitCount(int n)
    {
       int count = 0;
    
       if (n == 0)
          return 1;
    
       while (n != 0)
       {
          ++count;
          n /= 10;
       }
    
       return count;
    }
    

  5. Example 3: An infinite loop.
    while (true)
       statement;
    

for Loops

  1. Form:
    for (<initialization>; <condition>; <update>)
       statement;
    

  2. Semantics. When to use. The loop index variable.

  3. Example 1: Sum a sequence of numbers. First number is count of numbers to sum.
    int count;
    int sum = 0;
    int i;
    
    count = getNextInput();
    
    for (i = 0; i < count; ++i)
       sum += getNextInput();
    

  4. Example 2: Compute .
    int summation(int n)
    {
       int sum = 0;
       int i;
    
       for (i = 0; i <= n; ++i)
          sum += i;
    
       return sum;
    }
    

  5. Example 3: Sum evens between 0 and n.
    int evenSummation(int n)
    {
       int sum = 0;
       int i;
    
       for (i = 0; i <= n; i += 2)
          sum += i;
    
       return sum;
    }
    

Exercises

Complete the bodies of the following methods:

  1. Compute using a for loop:
    double pow(double x, int n)
    {
       // ...
    }
    

  2. Compute . (, by definition). Use a while loop.
    int fact(int n)
    {
       // ...
    }
    

Nested Loops

Yes, loops can be nested, like ifs.

How many times is statement executed in each of the following:

  1. int i;
    int j;
    
    for (i = 0; i < 5; ++i)
       for (j = 0; j < 5; ++j)
          statement;
    

  2. int i;
    int j;
    
    for (i = 0; i < 5; ++i)
       for (j = i; j < 5; ++j)
          statement;
    



Thomas P. Kelliher
Tue Nov 28 15:57:41 EST 2000
Tom Kelliher