Download presentation
Presentation is loading. Please wait.
Published bySuzanna Lambert Modified over 9 years ago
1
1 ENERGY 211 / CME 211 Lecture 13 October 20, 2008
2
2 Recursion A recursive function is a function that, directly or indirectly, calls itself Each function call has its own copy of parameters and local variables Internally, function calls are maintained using a stack Make sure that recursion will end!
3
3 Example: Factorial int factorial(int n) { if (n==0) return 1; return n*factorial(n–1); } This will compute n! for any nonnegative integer n What is wrong with this function?
4
4 Applications of Recursion The factorial example is a simple illustration of recursion, but it can easily be implemented non-recursively Recursion useful whenever an algorithm solves a problem by applying itself to “smaller” instances of the problem Often, algorithms are more rapidly designed recursively, which encourages rapid application development
5
5 Mergesort Simplistic algorithms for sorting an array of n elements take O(n 2 ) comparisons In mergesort, the array is divided in half, and each half is sorted individually The two sorted halves are then merged in O(n) comparisons, for O(n log 2 n) comparisons overall Limiting case of recursion: an array with one element is already sorted!
6
6 Fast Fourier Transform The Fast Fourier Transform (FFT) computes the discrete Fourier transform of a vector of functions values It recursively transforms odd-numbered and even-numbered points, and then merges the results O(n 2 ) work reduced to O(n log 2 n) For efficiency, should use pointers that take larger and larger steps to access elements!
7
7 Debuggers A debugger is a tool that performs step- by-step execution of a program, allowing the programmer to study its behavior and find bugs IDEs, like MDS and Microsoft Visual Studio, typically include debuggers A debugger runs your program, stopping execution at user-specified breakpoints to allow inspection
8
8 The MDS Debugger Before debugging, use F9 to set breakpoints in your program F5 begins execution within the debugger, or resumes after breakpoint When stopped, F10 steps through next line F11 steps into function call Shift-F11 steps out of function Hover over variables to see values
9
9 The gdb Debugger gdb is the GNU debugger Run from UNIX prompt with executable filename as argument break command sets breakpoint, can specify function name or line number run command begins execution step command advances one line, steps into functions automatically cont resumes execution print shows value of given expression
10
10 Next Time Testing strategies Debugging strategies Designing software with testing and debugging in mind!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.