### 2.3. New Loop Rules

When we encounter a loop, we compute the run time by adding up the time required for an average number of iterations.

Special Case: constant # of iterations If we knew that the loop would terminate after exactly k iterations, where k was a constant, then the rule would be

t_(text(loop)) = t_{text{init}} + \sum_{i=0}^k (t_{text{condition}}(i) + t_{text{body}}(i))

where t_{text{condition}}(i) is the average time required to evaluate the condition on the ith iteration, and t_{text{body}(i) is the time to evaluate the body on the ith iteration.

General case: unknown # of iterations But in many cases, the number of iterations is not a constant but depends on the inputs. In general, if p_k is the probability that the loop would terminate after k iterations, the average running time would be:

t_(text(loop)) = t_{text{init}} + \sum_{k=0}^{\infty} p_k (t_{text{condition}}(k+1: k) + \sum_{i=0}^k (t_{text{condition}}(i: k) + t_{text{body}}(i: k)))

where t_{text{condition}}(i: k) is the average time required to evaluate the condition on the ith iteration when the loop will take k total iterations, and t_{text{body}}(i: k) is defined similarly for loop bodies.

This is a fairly messy formula, but we'll usually fall back on special cases.

• The t_{text{condition}}(k+1: k) term reflects the fact that, on the final iteration, we evaluate the condition but do not execute the body.

• The \infty is not a mistake. It expresses the general case that some loops could execute an arbitrary number of times depending upon the input. If, however, we knew that a loop never executed more than, say, 100 times, then the probabilities p_{101}, p_{102}, \ldots would all be zero.

• Suppose that we knew that k was a constant. Then p_k = 1 for that single value of k, and p_j = 0 for all j != k. That leads directly to our earlier special case.

Special case: fixed bound on body & condition If (t_{text{condition}}(i: k) + t_{text{body}}(i: k)) does not vary from one iteration to another, then

t_(text(loop)) = t_{text{init}} + \sum_{k=0}^{\infty} p_k ( (k+1)*t_{text{condition}} + k*t_{text{body}})

Special case: fixed bound and equally probable iterations If the loop condition and body times do not vary across iterations, and we know that the loop takes anywhere from M to N iterations, and that each number of iterations in that range is equally likely, then

t_(text(loop)) = t_{text{init}} + O(1 + (M + N)/2 . (t_{text{condition}} + t_{text{body}}))`

### In the Forum:

(no threads at this time)