8. Counting Loops

# 8. Counting Loops - ENGR 101 Sec 100 Fall 10 Counting Loops...

This preview shows pages 1–5. Sign up to view the full content.

ENGR 101, Sec 100, Fall 10 M. Wellman 1 Counting Loops ENGR 101, Lecture 8: 6 Oct 10 Announcements Project 4 out, due Wed 13 Oct 9pm Exam #1 grades

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
ENGR 101, Sec 100, Fall 10 M. Wellman 2 Finite Sums Suppose we want to compute a summation Sum( m ) = Sum(4) = Summation Function // Return the Sum (n=1 to m) 1/(n^2) double Sum(int m) { int n = 0; while (n < m) { n = n + 1; } return something ; } Rest of loop body goes here 0 1 2 3 4 . m –1 Trace: values for n in loop value after loop: m
ENGR 101, Sec 100, Fall 10 M. Wellman 3 Summation Function (Alt. count) // Return the Sum (n=1 to m) 1/(n^2) double Sum(int m) { int n = 1 ; while (n <= m) { n = n + 1; } return something ; } Rest of loop body goes here 1 2 3 4 . m –1 m Trace: values for n in loop value after loop: m +1 Summation Function (orig.) // Return the Sum (n=1 to m) 1/(n^2) double Sum(int m) { int n = 0; double sum = 0; while (n < m) { sum += 1.0 / ((n+1)*(n+1)); n = n + 1; } return sum ; } 0 1 2 3 4 m –1 Trace: values for n in loop value after loop: m

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
ENGR 101, Sec 100, Fall 10 M. Wellman 4 Summation Loop Invariant // Return the Sum (n=1 to m) 1/(n^2) double Sum(int m) { int n = 0; double sum = 0; while (n < m) { sum += 1.0 / ((n+1)*(n+1)); n = n + 1; } return sum; } 0 1 2 3 4 . m –1 m invariant Summation Loop Invariant (Alt.) // Return the Sum (n=1 to m) 1/(n^2) double Sum(int m) { int n = 1 ; double sum = 0; while (n <= m) { sum += 1.0 / ( n*n ); n = n + 1; } return sum; } sum = 1 p 2 p = 1 n 1 invariant 1 2 3 4 m –1 m m +1 initialization termination body
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 14

8. Counting Loops - ENGR 101 Sec 100 Fall 10 Counting Loops...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online