What is Iteration? CMPT-101 Week 6 Iteration, Iteration, Iteration, Iteration, Iteration, Iteration,... To iterate means to do the same thing again and again and again and again... There are two primary ways to repeatedly execute a block of code: recursion loops Sometimes iteration is implies not recursive, but we ll use it in a more general sense. Recursion Recursion happens when a function calls itself a function that calls itself is recursive Recursion is elegant and powerful often inefficient in practice tricky to understand at first But sometimes it s the perfect tool for the job Understanding Recursion To understand recursion, you must first understand recursion. Recursively Adding Numbers Problem: Write a function that recursively calculates the sum of the ints from lo to hi (inclusive); assume lo is less than or equal to hi For example: sum(5,10) returns 45, because 5+6+7+8+9+10 = 45; sum(75,75) is 75; sum(-5,5) is 0 The Function Header and Documentation /* PURPOSE: adds ints from lo to hi RECEIVES: lo - the smallest int in the range hi - the highest int in the range (cannot be less than lo) RETURNS: sum of all ints from lo to hi (inclusive) */
No Mention of Recursion Yet! Notice that the function documentation doesn t say anything about recursion How the sum is calculated is an implementation detail Remember, the ordinary user of this function will be unconcerned with the implementation details unless the function works poorly! The Recursive Idea Look at an example: sum(5,10) 5 + 6 + 7 + 8 + 9 + 10 = sum(6,10) This shows that sum(5,10) = 5 + sum(6,10) sum(5,10) = 5 + sum(6,10) A Recursive Rule sum(6,10) = 6 + sum(7,10) sum(7,10) = 7 + sum(8,10) sum(8,10) = 8 + sum(9,10) sum(9,10) = 9 + sum(10,10) sum(10,10) = 10 base case From these examples, you can infer a general rule: sum(lo,hi) = lo + sum(lo+1,hi) sum is defined in terms of a (simpler) call to itself! This rule is not correct, since it doesn t tell you want to do when lo == hi, e.g. this rule doesn t tell you how to calculate sum(75,75) or sum(10,10), etc. A Recursive Rule Here s the completely correct rule: sum(lo,hi) = sum(lo,hi) = lo, if lo == hi sum(lo,hi) = lo + sum(lo+1,hi), if lo < hi Note that this rule is undefined when lo is greater than hi. Check for this case using an assert statement. A Recursive Function We can translate the previous recursive rule into a recursive C++ function quite straightforwardly header documentation is here... if (lo == hi) // base case return lo; else // recursive case return lo + sum(lo + 1,hi); Trace the function call sum(1,4) by hand to see how it works
Understanding Recursion Most programmers initially find recursion to be tricky to understand It doesn t seem to do anything --- it appears to work almost by magic! You ll learn more about recursion in later courses, e.g. CMPT-201 Many mathematical definitions are naturally recursive, so recursion makes implementing such functions almost trivial Understanding Recursion To understand recursion, try this: trace examples by hand implement them in C++ compare actual output to your hand-traced results do this with as many simple examples as you can find! Loops while Loops are Cool The other major way to repeatedly execute a code block is to use a loop C++ has three main looping constructs while loops do/while loops for loops this codeblock is the loop body while (cond) The loop terminates when cond is false cond is a bool expression before each execution of the body, cond is tested to make sure it s true What Does this Code Do? What Does this Code Do? int sum = 0; while (num >= 0) sum += num; // same as: sum = sum + num cout << \n << sum; entering any negative number causes this loop to terminate int sum = 0; while (num >= 0) sum += num; // shorthand for: sum = sum + num // while cout << \n << sum; typed in by the user Note: an actual program should have more user-friendly prompts and instructions, but on slides space is precious so I ve left those things out. 4 3 6 5 0 0 3-1 21
What Does this Code Do? int sum = 0; while (num >= 0) sum += num; // shorthand for: sum = sum + num // while cout << \n << sum; Answer: it reads in ints and adds them to sum, until the user enters a negative number, which terminates the loop. Then the sum of all the positive numbers is printed. Another Example Problem: Write a program that generates this output: Bold indicates user input 4-3 2 2 4-93 -1 0 You entered 7 numbers: 3 negative 4 positive 0 indicates the end of the input int neg = 0, pos = 0; while (num!= 0) if (num < 0) ++neg; else ++pos; Another Example this loop terminates when the user enters a 0 for each repetition of the loop, either neg or pos is incremented --- but not both cout << "You entered " << (neg + pos) << " numbers\n" << neg << " negative\n" << pos << " positive"; initialize variables get first item while (item is not a terminator) do process item get next item end while output results A Loop Idiom the first item is gotten outside the loop because it might be a terminating item, and in that case we don t want the loop body to execute even once You can use this as a template to help you design your own loops, although it doesn t apply in all cases. Notes on while Loops A while loop s body is executed 0 or more times the condition for the while loop is always tested before the loop body is executed You don t need to know ahead of time how many times the loop will execute Rule of thumb: if you re unsure about what kind of loop to use, use a while loop the body of a do/while is always executed once before checking cond do/while Loops Rock cond is a bool expression tested at the end of the loop after the body is executed do while (cond); After the body is executed, cond is checked: if it s true, the loop body is executed again; if it s false, the loop terminates
Example do/while Loop do cout << "Enter a non-zero int: "; while (num == 0); cout << "Thanks!"; Enter a non-zero int: 0 Enter a non-zero int: 0 this keeps prompting the user to enter a non-zero int for as long as the user keeps entering 0s! Loop Notes Always try to pick the best loop However, for practical reasons, many C++ programmers avoid the use of do/while loops... Enter a non-zero int: -1 Thanks! A Quote From Stroustrup for-loops In my experience, the [do/while loop] is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work correctly, something very much like the condition must hold even the first time through. More often than I would have guessed, I found that condition not to hold as expected, either when the program was first written and tested or later after the code preceding it has been modified. I also prefer the condition up front where I can see it. Consequently, I tend to avoid [do/while loops]. --- Bjarne Stroustup, The C++ Programming Language, 3rd Edition, p. 137 In C++, for-loops are a shorthand for a commonly used form of while loop init; while (cond) update; for(init; cond; update) these code fragments do the same thing An Example of a for Loop Compared to a while Loop int total = 0; return total; Initialization happens at the start of the loop, before the body is executed This loop causes i to take on the values lo, lo+1, lo+2,..., hi in succession The update happens after the loop body has been executed This condition is always checked at the top of the loop (and after i is initialized) equivalent code int total = 0; return total; the for-loop version is generally considered neater and shorter; plus it puts all the loop control information in one place int total = 0; int i = lo; while (i <= hi) ++i; // while return total;
for-loop Notes Use for-loops for counting loops, e.g. loops where you know ahead of time how many times they ll execute loops that need an index variable incremented throughout the loop s iterations Don t write strange, difficult to understand for loops use while loops for complex loops for-loop Notes cout << i; // Oops! Error! this is an error in modern C++ compilers because i only lives inside the body and header of the for-loop this for-loop s body has only one statement, so no brackets are necessary for-loop Notes cout << i; // okay in old C++ Beware: in older C++ compilers, this is legal! That is, in older C++ compilers, the scope of i in a for-loop extends past the end of the body